Skip to content

Commit 49ffccd

Browse files
lidge-junGSL-Rclaude
authored
feat(vertex): accept credential JSON with secure marker lifecycle (carry #6843) (#7139)
* feat(vertex): accept pasted GCP credential JSON in the API-key slot (#6821) Let the provider's API-key field take a Service Account JSON directly: - gcp-adc: a `gcp-sa:<account>` marker resolves the credential from the OS keychain (same service + entry factory as `keychain:` references) and runs the existing service_account JWT / authorized_user flow. The marker sits above GOOGLE_APPLICATION_CREDENTIALS in the source priority; everything downstream (token cache, refresh skew, in-flight dedup) is untouched. - api-keys: addProviderApiKey detects a pasted credential JSON (single, pretty-printed, or comma-separated for future pool rotation), verifies the "type" field, stores the secret in the OS keychain with a read-back check, and persists only the marker to config. File paths are rejected with paste guidance; unrecognized types are rejected before anything is stored. - router: usableResolvedApiKey registers the active `gcp-sa:` marker with the ADC resolver, so a marker in any pool entry becomes the active source. - adapters/google: vertex's API-key fast path skips `gcp-sa:` markers — they are not API-key material and must reach the ADC branch instead. Markers keep resolveProviderApiKey synchronous (no signature changes) and work naturally with the existing 429 key-pool failover: each pool entry can independently hold a raw key, an ${ENV} ref, a keychain: ref, or a gcp-sa: marker, and per-key cooldown rotation applies unchanged. Closes #6821 (partially — live model discovery for vertex mode is a separate discussion). Co-Authored-By: Claude <noreply@anthropic.com> * refactor(vertex): pass the marker account per request; review fixes (#6842) Address CodeRabbit findings: - gcp-adc: remove the process-global activeMarkerAccount/registration (a module-level marker would race across concurrent requests for different providers and could resolve one call with another provider's credential). The marker account now travels per request via getVertexAccessToken(options.markerAccount) and flows through currentAdcSourceKey/loadAdcCredentials as an argument. The reconcile sweep passes no marker (no request context) — marker entries are pruned by expiry instead. - adapters/google: pass gcpCredentialMarkerAccount(provider.apiKey) per request. router: drop the registration; the routed provider config carries the marker verbatim. - api-keys: delete a just-written keychain entry ONLY when the write created it — on a failed commit, an upsert must keep the credential the previous reference still names. - tests: narrow the adapter assertion to the ADC-shaped request (URL + Bearer header + no x-goog-api-key, with a stubbed fetch), and isolate the marker-source tests from host ADC state (empty CLOUDSDK_CONFIG, no GOOGLE_APPLICATION_CREDENTIALS, 404 fetch stub). Co-Authored-By: Claude <noreply@anthropic.com> * fix(vertex): preserve the marker through routing; harden paste handling (#6842) Address CodeRabbit round-2 findings: - router: usableResolvedApiKey returns gcp-sa: marker values UNCHANGED — replacing a marker with undefined (it resolves to no key material) would silently drop it from the routed config and send the vertex adapter to host ADC instead of the configured service account. - api-keys: storeGcpCredentialJson takes existedBefore and deletes the keychain entry after a read-back mismatch only when the entry did not exist before the write — a re-paste targets an account an existing marker already names, and deleting it would destroy the live credential. - api-keys: splitCredentialPaste honors the parseGcpCredentialJson contract (a single-line brace-leading literal is never eaten — it falls back to a plain key row), tracks JSON string/escape state in the brace scanner (a } inside a string field no longer splits early), and rejects non-separator content before/between objects instead of discarding it. - tests: router-level pass-through test (routedProviderConfig preserves the marker), end-to-end test (routed config feeds buildRequest, ADC branch wins), literal-key fallback + gap-rejection tests. Markers keep resolveProviderApiKey synchronous. Co-Authored-By: Claude <noreply@anthropic.com> * docs: attest review readiness checklist (4/4 ticked) * docs: attest readiness 4/4; trigger gate re-evaluation * fix(gcp-adc): suppress the GOOGLE_CLOUD_API_KEY fallback for named markers; strict paste validation (#6842) Address Prana review findings: - adapters/google: a `gcp-sa:` marker means the operator named ONE credential explicitly — the GOOGLE_CLOUD_API_KEY env fallback no longer fires. Without this guard, a marker + env key would silently route the provider's inference through the ambient env key instead of the configured service account. - providers/api-keys (capture): a parseable JSON object with an unrecognized "type" field (e.g. external_account) is REJECTED with guidance, not saved as a plaintext literal key — saving it would send it to the wire verbatim. Non-JSON brace values ({abc:def}) keep their key-compat behavior. - providers/api-keys (tail): content after the LAST object's close up to EOF is validated like the mid-gaps — trailing garbage is rejected, not silently kept. (Covers captureTrailing otherwise.) Registrations: per-finding regression tests added (explicit-credential-wins for markers, JSON-with-unknown-type rejection, tail-gap rejection). Co-Authored-By: Claude <noreply@anthropic.com> * test(vertex): cover trailing credential paste validation * fix(gcp-adc): validate markers and clean up credential lifecycle * fix(gcp-adc): clean credentials after provider batch and overwrite commits * fix(management): include durable provider markers in DELETE cleanup Co-Authored-By: Claude <noreply@anthropic.com> * fix(gcp-adc): validate required fields in parseGcpCredentialJson before persistence Co-Authored-By: Claude <noreply@anthropic.com> * style(management): keep GCP cleanup within file-size gate * fix(vertex): reject credential JSON before generic provider persistence * fix(vertex): preserve GCP keychain payloads across key migrations * fix(vertex): serialize credential writes with marker commits and cleanup * fix(cli): clean removed GCP credentials after provider overwrite * fix(cli): collect durable GCP markers under overwrite lock * fix(cli): validate raw keys before registry auth ignores them * fix(gcp-adc): isolate blank markers during credential cleanup * fix(vertex): close credential input, alias and removal lifecycle gaps Reject wrapped or malformed credential material before literal persistence or restore, and prevent keychain aliases exposing GCP JSON as wire keys. Revalidate marker readability before cached-token use. Capture deletion candidates and persist CLI/management removal under one mutation lock, preserving post-commit shared-reference cleanup. Cover mixed SA/key failover and DTO redaction with synthetic credentials. Co-authored-by: GSL-R <174104911+GSL-R@users.noreply.github.com> * fix(vertex): classify JSON-escaped credentials before alias resolution Decode structured JSON before credential classification so escaped field and type names cannot enter literal key resolution or keychain restore. Co-authored-by: GSL-R <174104911+GSL-R@users.noreply.github.com> * fix(vertex): refuse structured JSON carriers as literal keys Reject object, array and quoted-string carriers directly so nested or escaped GCP credential material cannot bypass alias, ingestion or restore validation. Preserve non-JSON literal token handling and dedicated supported GCP-object ingestion. Co-authored-by: GSL-R <174104911+GSL-R@users.noreply.github.com> * refactor(management): extract GCP credential route handling Move credential-input rejection responses and locked provider deletion into a cohesive sibling module. Preserve validation responses, mutation ordering, save callback and post-commit cleanup behavior while keeping provider-routes.ts below the fixed 2000-line limit after dev integration. Co-authored-by: GSL-R <174104911+GSL-R@users.noreply.github.com> --------- Co-authored-by: GSL-R <gslee0922@gmail.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: GSL-R <174104911+GSL-R@users.noreply.github.com>
1 parent 17e307d commit 49ffccd

23 files changed

Lines changed: 1887 additions & 44 deletions

‎docs-site/src/content/docs/reference/configuration/providers.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1502,6 +1502,32 @@ model key.
15021502

15031503
## Storing keys in the OS keychain
15041504

1505+
For Vertex, the dedicated API-key pool input (`POST /api/providers/keys`) accepts complete GCP
1506+
`service_account` or `authorized_user` credential JSON after the provider has been created.
1507+
The provider create/edit form and `ocx provider add --api-key` refuse credential JSON before
1508+
saving: create the provider without a key, then add the JSON through its key pool. Paste the
1509+
JSON contents, not a Windows, Unix, or relative file path. Multiple
1510+
JSON objects separated by commas or whitespace are stored together as separate pool entries;
1511+
the first becomes active. Configuration contains only `gcp-sa:<account>` references, never the
1512+
credential JSON. Mixed JSON/literal-key bulk pastes are rejected as a whole; add literal keys
1513+
separately. Storage failures leave the configuration unchanged and report a fixed error without
1514+
echoing credential material. Empty marker accounts are invalid and do not fall back to host credentials.
1515+
Paste one credential object or a sequence of objects, without an enclosing array or quoted string.
1516+
Malformed credential text is rejected. If a selected stored credential is removed or becomes unreadable,
1517+
Vertex refuses the request even when it previously cached an access token for that credential.
1518+
Removing a key or provider, or replacing a provider with `ocx provider add --force`, deletes its unreferenced GCP credentials after the configuration is
1519+
saved; a credential referenced by another provider is retained. If OS-store cleanup fails, a
1520+
warning requests manual inspection without undoing the committed configuration removal.
1521+
Ordinary keychain store/restore actions leave GCP markers and JSON in the OS store. Restoring
1522+
credential JSON through a `keychain:` alias is refused, and cleanup preserves accounts still
1523+
referenced through either marker spelling.
1524+
Using a `keychain:` alias containing GCP JSON as an API key also refuses the request; select its
1525+
`gcp-sa:` reference for Vertex authentication instead.
1526+
Literal API keys must be plain token text: JSON objects, arrays and quoted JSON strings are refused
1527+
in literal-key resolution and restore, including wrappers containing escaped credential text.
1528+
Credential writes and marker persistence share the cleanup transaction lock, so concurrent
1529+
removal cannot delete the stored JSON between read-back and the marker commit.
1530+
15051531
By default a provider's `apiKey` and `apiKeyPool` sit in `config.json` (mode 0600, atomic writes).
15061532
If you would rather keep the key material out of the file, move it into the OS credential store:
15071533

‎scripts/test-layout/layout.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"version": 1,
33
"root": "tests",
44
"explicitShards": ["layout-clients.json"],
5-
"explicit": { "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration",
5+
"explicit": { "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration",
66
"owner-registry-isolation.test.ts": "config",
77
"codex-history-pending-wal.test.ts": "codex-integration", "responses-anthropic-billing-send-budget.test.ts": "responses", "anthropic-billing-ownership.test.ts": "adapters/anthropic", "server-anthropic-billing.test.ts": "server", "server-anthropic-billing-boundaries.test.ts": "server", "router-anthropic-billing-failover.test.ts": "routing", "anthropic-billing-refusal.test.ts": "adapters/anthropic", "messages-request-id-headers.test.ts": "claude-integration", "bounded-file-read.test.ts": "lib", "responses-undeclared-tool-guard-inbound.test.ts": "responses", "explicit-empty-tool-catalog.test.ts": "responses", "explicit-empty-tool-catalog-history.test.ts": "responses",
88
"messages-request-id-endpoint.test.ts": "claude-integration",

‎src/adapters/google.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import type {
1717
import { isAllowedToolChoice, namespacedToolName, resolveToolChoiceWireName, toolChoiceToolPredicate } from "../types";
1818
import type { OcxTool } from "../types";
1919
import { contentPartsToText, parseDataUrl } from "./image";
20-
import { getVertexAccessToken } from "../lib/gcp-adc";
20+
import { GCP_CREDENTIAL_MARKER_PREFIX, gcpCredentialMarkerAccount, getVertexAccessToken } from "../lib/gcp-adc";
2121
import { fetchAntigravityWithRetry, fetchVertexWithRetry } from "./google-http";
2222
import { safeAntigravityHttpErrorMessage, safeVertexHttpErrorMessage } from "./google-errors";
2323
import { isVertexTruncatedTurn, vertexTruncationErrorEvent } from "./google-truncation";
@@ -174,7 +174,15 @@ function resolveDirectGeminiWireModelId(modelId: string, applyRenames: boolean):
174174

175175
/** Vertex API key: provider.apiKey if it looks real (not a sentinel), else GOOGLE_CLOUD_API_KEY env. */
176176
function resolveVertexApiKey(optKey?: string): string | undefined {
177-
const realKey = optKey && !optKey.startsWith("<") && optKey !== "N/A" ? optKey : undefined;
177+
// A `gcp-sa:` marker is the keychain-backed credential reference (see gcp-adc): it is not
178+
// API-key material, so it must not be sent as x-goog-api-key — the ADC branch below handles it.
179+
// AND the marker means the operator named one credential explicitly: the GOOGLE_CLOUD_API_KEY
180+
// env fallback must NOT fire (it would silently route this provider's inference through the
181+
// ambient env key instead of the configured service account).
182+
if (optKey && optKey.startsWith(GCP_CREDENTIAL_MARKER_PREFIX)) return undefined;
183+
const realKey = optKey && !optKey.startsWith("<") && optKey !== "N/A"
184+
? optKey
185+
: undefined;
178186
return realKey || process.env.GOOGLE_CLOUD_API_KEY;
179187
}
180188

@@ -1197,7 +1205,11 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
11971205
if (locationError) throw new Error(locationError);
11981206
const host = location === "global" ? "aiplatform.googleapis.com" : `${location}-aiplatform.googleapis.com`;
11991207
const url = `https://${host}/v1/projects/${project}/locations/${location}/publishers/google/models/${parsed.modelId}:${method}${streamParam}`;
1200-
const token = await getVertexAccessToken();
1208+
// The marker account travels per-request as an argument (never process-global state): a
1209+
// module-level "active marker" written at routing time would race across concurrent
1210+
// requests for different providers and could resolve one call with another's credential.
1211+
const markerAccount = gcpCredentialMarkerAccount(provider.apiKey);
1212+
const token = await getVertexAccessToken({ markerAccount });
12011213
headers["Authorization"] = `Bearer ${token}`;
12021214
return { url, method: "POST", headers, body: JSON.stringify(compiled.body) };
12031215
}

‎src/cli/provider.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@
88
* show <name> Show provider config details (secrets masked)
99
* set-default <name> Change the default provider
1010
*/
11-
import { hasOwnProvider, isValidProviderName, loadConfig, sanitizeModelCostsForDisplay, saveConfig, validateConfigCandidate, withConfigMutationLockSync } from "../config";
11+
import { hasOwnProvider, isValidProviderName, loadConfig, readConfigAdmissionSnapshot, sanitizeModelCostsForDisplay, saveConfig, validateConfigCandidate, withConfigMutationLockSync } from "../config";
1212
import { apiKeyTransportConfigError, modelCapabilitiesConfigError, mergeModelCapabilities } from "../config/provider-validation";
1313
import { hasHelpFlag, printSubcommandUsage } from "./help";
1414
import { getProviderRegistryEntry, PROVIDER_REGISTRY } from "../providers/registry";
1515
import { providerConfigSeed } from "../providers/derive";
1616
import { assertAnthropicInstanceLoginConfig } from "../oauth/store-anthropic-instance";
1717
import { dropProviderCustomModels } from "../providers/provider-id-rewrite";
18+
import { cleanupRemovedGcpCredentials, commitProviderGcpCredentialRemoval, providerGcpCredentialMarkers } from "../providers/gcp-credential-cleanup";
19+
import { providerCredentialInputError } from "../providers/api-keys";
1820
import type { OcxProviderConfig } from "../types";
1921
import { findLiveProxy } from "../server/proxy-liveness";
2022
import { syncModelsToCodex } from "../codex/sync";
@@ -223,6 +225,12 @@ async function handleAdd(args: string[], deps: ProviderCommandDeps): Promise<voi
223225
if (registryEntry) {
224226
provConfig = providerConfigSeed(registryEntry);
225227
if (apiKey) {
228+
const candidateError = providerCredentialInputError({ apiKey });
229+
if (candidateError) {
230+
console.error(`Error: ${candidateError}`);
231+
process.exitCode = 2;
232+
return;
233+
}
226234
if ((authMode ?? registryEntry.authKind) === "forward") {
227235
console.warn(`Warning: provider "${name}" uses ChatGPT login (forward auth); --api-key is ignored.`);
228236
} else if ((authMode ?? registryEntry.authKind) === "oauth") {
@@ -249,6 +257,12 @@ async function handleAdd(args: string[], deps: ProviderCommandDeps): Promise<voi
249257
}
250258

251259
if (responsesPath !== undefined) provConfig.responsesPath = responsesPath;
260+
const credentialError = providerCredentialInputError(provConfig);
261+
if (credentialError) {
262+
console.error(`Error: ${credentialError}`);
263+
process.exitCode = 2;
264+
return;
265+
}
252266
if (authMode !== undefined) provConfig.authMode = authMode as OcxProviderConfig["authMode"];
253267
if (name === "anthropic2") {
254268
if (provConfig.adapter !== "anthropic" || provConfig.authMode !== "oauth") delete provConfig.anthropicOAuthInstance;
@@ -328,12 +342,17 @@ async function handleAdd(args: string[], deps: ProviderCommandDeps): Promise<voi
328342
}
329343
const { initializeProviderModelSelection } = await import("../providers/initial-model-selection");
330344
let markerCollision = false;
345+
let removedCredentials: string[] = [];
331346
withConfigMutationLockSync(() => {
332347
if (provConfig.anthropicOAuthInstance) {
333348
try { assertAnthropicInstanceLoginConfig(config, name); }
334349
catch { markerCollision = true; return; }
335350
}
336351
initializeProviderModelSelection(name, provConfig, existingProvider, config);
352+
const durable = readConfigAdmissionSnapshot();
353+
const durableProvider = durable.kind === "read" && durable.diagnostics.source === "file"
354+
&& durable.diagnostics.error === null ? durable.diagnostics.config.providers[name] : undefined;
355+
removedCredentials = [config.providers[name], durableProvider].flatMap(provider => provider ? providerGcpCredentialMarkers(provider) : []);
337356
config.providers[name] = provConfig;
338357
if (setDefault) config.defaultProvider = name;
339358
validateAndSave(config);
@@ -344,6 +363,7 @@ async function handleAdd(args: string[], deps: ProviderCommandDeps): Promise<voi
344363
return;
345364
}
346365

366+
cleanupRemovedGcpCredentials(removedCredentials);
347367
let sync: LocalSyncResult | undefined;
348368
if (wantsSync) {
349369
try {
@@ -440,10 +460,12 @@ function handleRemove(args: string[]): void {
440460
process.exit(1);
441461
}
442462

443-
delete config.providers[name];
444-
const droppedCustomModels = dropProviderCustomModels(config, name);
445-
validateAndSave(config);
446-
463+
const droppedCustomModels = commitProviderGcpCredentialRemoval(config, name, () => {
464+
delete config.providers[name];
465+
const dropped = dropProviderCustomModels(config, name);
466+
validateAndSave(config);
467+
return dropped;
468+
});
447469

448470
if (wantsJson) {
449471
console.log(JSON.stringify({

0 commit comments

Comments
 (0)