Skip to content

Commit 7a68422

Browse files
Marvintheboredclaude
authored andcommitted
fix(auth): do not admit ambient environment credentials behind declared profiles
A provider credential present only in the process environment — named in neither the provider entry, `auth.profiles`, nor `auth.order` — was appended to the auth attempt list behind the operator's declared profiles. A run that left a declared profile could therefore continue on an undeclared credential, which may bill a different account, with no configuration authorizing the transition and nothing reporting that it happened. Add an explicit `authorization: "declared" | "ambient"` fact on direct auth sources and enforce it during source selection. The field is required rather than defaulted so every construction site is audited; `evidence` is left as provenance, since a declared credential can legitimately be environment-sourced via a `${VAR}` marker or a SecretRef. An ambient credential may still serve a provider with no declared profiles (the documented zero-config `PROVIDER_API_KEY` path), but it is no longer admitted behind declared profiles, nor substituted for declared profiles that turned out to be unusable. `auth.order` failover is unaffected: profiles are never filtered by this change. The read-only availability evaluator applies the same rule so status cannot advertise a credential the runtime refuses. This restores the invariant that held before 1b1cebf (#104685), where an environment candidate was reachable only when a provider had no declared profiles. The regression shipped in 2026.7.2-beta.1 onwards; no GA release is affected. Reported in #117956. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Nwk2KaB6zL71xa1i3Xwgwi
1 parent a88f3ff commit 7a68422

10 files changed

Lines changed: 400 additions & 44 deletions

‎src/agents/embedded-agent-runner/run/assistant-failover.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,14 @@ export async function handleAssistantFailover(params: {
213213
const markFailedProfilePromise = markFailedProfile();
214214
if (timeoutFailure && !params.isProbeSession && failedProfileId) {
215215
const timeoutLabel = terminal.idleTimedOut ? "idle timeout (model silent)" : "timed out";
216-
params.warn(`Profile ${failedProfileId} ${timeoutLabel}. Trying next account...`);
216+
// Only promise a next account when one was actually selected. Credentials
217+
// that config does not authorize are not rotation targets, so this can end
218+
// with no further account even when one exists in the environment.
219+
params.warn(
220+
rotated
221+
? `Profile ${failedProfileId} ${timeoutLabel}. Trying next account...`
222+
: `Profile ${failedProfileId} ${timeoutLabel}. No further authorized account for this provider; create a backup auth profile and add its id to auth.order to enable failover.`,
223+
);
217224
}
218225
if (params.cloudCodeAssistFormatError && failedProfileId) {
219226
params.warn(

‎src/agents/model-auth-availability.test.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -499,14 +499,18 @@ describe("createModelAuthAvailabilityResolver", () => {
499499
route: subscriptionRoute,
500500
mode: "oauth",
501501
},
502-
])("selects $label", ({ cfg, env, mode, profile, profileId, route }) => {
503-
expect(evaluate({ cfg, env, store: authStore({ [profileId]: profile }) })).toMatchObject({
504-
availability: true,
505-
evidence: "environment",
506-
selectedAuthMode: mode,
507-
selectedRoute: route,
508-
});
509-
});
502+
// An environment credential named nowhere in config is not authorized to
503+
// stand in for a declared profile, including a declared profile that turned
504+
// out to be unusable. Availability mirrors the runtime rule here so status
505+
// does not advertise a credential the run would refuse to use.
506+
])(
507+
"reports $label unavailable rather than substituting an ambient credential",
508+
({ cfg, env, profile, profileId }) => {
509+
expect(evaluate({ cfg, env, store: authStore({ [profileId]: profile }) })).toMatchObject({
510+
availability: false,
511+
});
512+
},
513+
);
510514

511515
it.each([
512516
{ env: { OPENAI_API_KEY: "resolved-key" }, availability: true },

‎src/agents/model-auth-availability.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import {
5454
buildProviderModelAuthSourcePlan,
5555
fromProviderModelAuthReadiness,
5656
toProviderModelAuthReadiness,
57+
type ProviderModelAuthAuthorization,
5758
type ProviderModelAuthEvidence,
5859
type ProviderModelAuthProfileSource,
5960
} from "./provider-model-auth-source-plan.js";
@@ -620,11 +621,15 @@ export function createModelAuthAvailabilityResolver(
620621
selectedAuthMode: configured?.auth,
621622
};
622623
};
623-
const directSource = (evaluation: AuthSourceEvaluation) =>
624+
const directSource = (
625+
evaluation: AuthSourceEvaluation,
626+
authorization: ProviderModelAuthAuthorization = "declared",
627+
) =>
624628
buildProviderModelAuthDirectSource({
625629
mode: evaluation.selectedAuthMode,
626630
availability: evaluation.availability,
627631
evidence: evaluation.evidence ?? "none",
632+
authorization,
628633
});
629634
const automaticProfileSource = (
630635
provider: string,
@@ -686,14 +691,28 @@ export function createModelAuthAvailabilityResolver(
686691
(hasDirectMaterial && shouldPreferExplicitConfigApiKeyAuth(params.cfg, provider));
687692
const environment = envAuth(provider);
688693
const environmentMode = environment ? (configured?.auth ?? environment.mode) : undefined;
694+
// Mirrors the runtime classification in runtime-plan/prepare-auth.ts: a
695+
// credential is ambient only when it came from the environment and the
696+
// provider entry declares no apiKey material pointing at it. Availability
697+
// and runtime must agree, or status advertises a credential the run will
698+
// refuse (or the reverse).
699+
const ambientEnvironmentCredential =
700+
!required && environmentMode !== undefined && environmentMode !== "aws-sdk"
701+
? !hasDirectMaterial
702+
: false;
689703
const direct =
690704
!required && environmentMode
691705
? buildProviderModelAuthDirectSource({
692706
mode: environmentMode,
693707
availability: modeAllowed(provider, target, environmentMode),
694708
evidence: environmentMode === "aws-sdk" ? "aws-sdk" : "environment",
709+
authorization: ambientEnvironmentCredential ? "ambient" : "declared",
695710
})
696-
: directSource(unprofiledEvaluation(provider, target));
711+
: ((evaluation) =>
712+
directSource(
713+
evaluation,
714+
evaluation.evidence === "environment" && !hasDirectMaterial ? "ambient" : "declared",
715+
))(unprofiledEvaluation(provider, target));
697716
const hasDirectFallback = hasDirectMaterial || direct.evidence !== "none";
698717
return {
699718
binding,

‎src/agents/provider-model-auth-source-plan.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,24 @@ export type ProviderModelAuthProfileSource = {
1818
cooldown: "active" | "clear";
1919
};
2020

21+
/**
22+
* Whether config authorizes this credential, as opposed to where it was found.
23+
*
24+
* `evidence` is provenance and is reported as such by status/probe surfaces; it
25+
* cannot carry authorization, because a *declared* credential can legitimately
26+
* be discovered in the environment (a `${VAR}` marker or a SecretRef naming a
27+
* canonical variable). `"ambient"` means the opposite: the credential appears in
28+
* neither the provider entry nor `auth.profiles`/`auth.order`, so nothing in
29+
* config points at it and it may bill an account the operator never named here.
30+
*/
31+
export type ProviderModelAuthAuthorization = "declared" | "ambient";
32+
2133
export type ProviderModelAuthDirectSource = {
2234
kind: "direct";
2335
mode?: string;
2436
readiness: ProviderModelAuthReadiness;
2537
evidence: ProviderModelAuthEvidence;
38+
authorization: ProviderModelAuthAuthorization;
2639
};
2740

2841
export type ProviderModelAuthSource =
@@ -61,6 +74,14 @@ export type ProviderModelAuthSourcePlan =
6174
orderedProfiles: readonly ProviderModelAuthProfileSource[];
6275
allowCooldown: boolean;
6376
fallback?: ProviderModelAuthDirectSource;
77+
/**
78+
* How many profiles the operator declared for this provider, before any
79+
* readiness, cooldown or route-compatibility filtering. Route filtering
80+
* rebuilds the plan from a narrowed profile list, so `profiles.kind` alone
81+
* cannot distinguish "operator declared nothing" (zero-config) from
82+
* "everything the operator declared was filtered out".
83+
*/
84+
declaredProfileCount: number;
6485
};
6586

6687
export function toProviderModelAuthReadiness(
@@ -80,12 +101,19 @@ export function buildProviderModelAuthDirectSource(params: {
80101
mode?: string;
81102
availability?: boolean;
82103
evidence: ProviderModelAuthEvidence;
104+
/**
105+
* Required, not defaulted: a permissive default would silently give every
106+
* unaudited construction site full standing, which is exactly how a source
107+
* escapes the ambient-credential rule. Make each caller state it.
108+
*/
109+
authorization: ProviderModelAuthAuthorization;
83110
}): ProviderModelAuthDirectSource {
84111
return {
85112
kind: "direct",
86113
mode: params.mode,
87114
readiness: toProviderModelAuthReadiness(params.availability),
88115
evidence: params.evidence,
116+
authorization: params.authorization,
89117
};
90118
}
91119

@@ -113,6 +141,8 @@ export function buildProviderModelAuthSourcePlan(params: {
113141
explicitOrder?: boolean;
114142
fallback?: ProviderModelAuthDirectSource;
115143
allowCooldown?: boolean;
144+
/** Overrides the declared count when rebuilding a plan from filtered profiles. */
145+
declaredProfileCount?: number;
116146
}): ProviderModelAuthSourcePlan {
117147
if (params.ownership) {
118148
return { kind: "required", ...params.ownership };
@@ -148,6 +178,7 @@ export function buildProviderModelAuthSourcePlan(params: {
148178
profiles,
149179
orderedProfiles: ordered,
150180
allowCooldown: params.allowCooldown === true,
181+
declaredProfileCount: params.declaredProfileCount ?? ordered.length,
151182
...(params.fallback ? { fallback: params.fallback } : {}),
152183
};
153184
}

‎src/agents/provider-model-route-auth.test.ts‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
} from "./provider-model-auth-source-plan.js";
77
import {
88
resolveProviderModelRouteMaterializationAuthMode,
9+
selectProviderModelAuthSources,
910
selectProviderModelRouteAuth,
1011
} from "./provider-model-route-auth.js";
1112

@@ -38,12 +39,16 @@ function profile(
3839
return { kind: "profile", profileId, mode, readiness, cooldown };
3940
}
4041

41-
function direct(mode: string): ProviderModelAuthDirectSource {
42+
function direct(
43+
mode: string,
44+
authorization: ProviderModelAuthDirectSource["authorization"] = "declared",
45+
): ProviderModelAuthDirectSource {
4246
return {
4347
kind: "direct",
4448
mode,
4549
readiness: "ready",
4650
evidence: "provider-config",
51+
authorization,
4752
};
4853
}
4954

@@ -406,3 +411,69 @@ describe("provider model route auth", () => {
406411
});
407412
});
408413
});
414+
415+
describe("ambient credential admission", () => {
416+
const ambient = (mode: string): ProviderModelAuthDirectSource => direct(mode, "ambient");
417+
const ready = (profileId: string, mode: string) => profile(profileId, mode, "ready");
418+
const select = (plan: Parameters<typeof selectProviderModelAuthSources>[0]["plan"]) =>
419+
selectProviderModelAuthSources({ provider: "openai", plan });
420+
421+
it("drops an ambient fallback queued behind usable profiles", () => {
422+
const decision = select(
423+
buildProviderModelAuthSourcePlan({
424+
profiles: [ready("openai:chatgpt", "oauth")],
425+
fallback: ambient("api-key"),
426+
}),
427+
);
428+
429+
expect(decision).toMatchObject({ kind: "selected" });
430+
expect(decision.kind === "selected" && decision.attempts).toMatchObject([{ kind: "profile" }]);
431+
});
432+
433+
it("keeps a declared fallback queued behind usable profiles", () => {
434+
const decision = select(
435+
buildProviderModelAuthSourcePlan({
436+
profiles: [ready("openai:chatgpt", "oauth")],
437+
fallback: direct("api-key"),
438+
}),
439+
);
440+
441+
expect(decision.kind === "selected" && decision.attempts).toMatchObject([
442+
{ kind: "profile" },
443+
{ kind: "direct" },
444+
]);
445+
});
446+
447+
it("keeps an ambient fallback when the provider declares no profiles", () => {
448+
const decision = select(
449+
buildProviderModelAuthSourcePlan({ profiles: [], fallback: ambient("api-key") }),
450+
);
451+
452+
expect(decision.kind === "selected" && decision.attempts).toMatchObject([{ kind: "direct" }]);
453+
});
454+
455+
it("does not substitute an ambient fallback for all-unavailable profiles", () => {
456+
const decision = select(
457+
buildProviderModelAuthSourcePlan({
458+
profiles: [profile("openai:chatgpt", "oauth", "unavailable")],
459+
fallback: ambient("api-key"),
460+
}),
461+
);
462+
463+
expect(decision.kind === "selected" && decision.attempts).toMatchObject([]);
464+
});
465+
466+
it("does not re-admit an ambient fallback when route filtering empties the profile list", () => {
467+
// Rebuild shape used by selectProviderModelRouteAuth when narrowing to a
468+
// route-compatible subset: no profiles survive, but the operator declared one.
469+
const decision = select(
470+
buildProviderModelAuthSourcePlan({
471+
profiles: [],
472+
declaredProfileCount: 1,
473+
fallback: ambient("api-key"),
474+
}),
475+
);
476+
477+
expect(decision.kind === "selected" && decision.attempts).toMatchObject([]);
478+
});
479+
});

‎src/agents/provider-model-route-auth.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,22 +178,38 @@ export function selectProviderModelAuthSources(params: {
178178
...(profiles.kind === "all-unavailable" ? { source: profiles.first } : {}),
179179
};
180180
}
181+
// An ambient credential — one config names nowhere — may serve a provider the
182+
// operator left entirely unconfigured (the documented zero-config
183+
// `PROVIDER_API_KEY` path), but it must never *succeed* a credential the
184+
// operator did declare. Those can bill different accounts, so that transition
185+
// needs a declaration, not a discovery. `auth.order` filtering already refuses
186+
// to silently try a declared profile the operator omitted from an explicit
187+
// order (docs/auth-credential-semantics.md, "Explicit auth order filtering");
188+
// an undeclared credential cannot rank above that.
189+
//
190+
// `declaredProfileCount` rather than `profiles.kind`: route filtering rebuilds
191+
// this plan from a narrowed profile list, so an operator who declared only
192+
// route-incompatible profiles must not be treated as zero-config.
193+
const authorizedFallback =
194+
fallback?.authorization === "ambient" && params.plan.declaredProfileCount > 0
195+
? undefined
196+
: fallback;
181197
if (profiles.kind === "usable") {
182198
const winner = selectReadyProfile(profiles.profiles);
183199
return {
184200
kind: "selected",
185201
selection: winner ? { kind: "selected", source: winner } : { kind: "none" },
186202
attempts: [
187203
...profiles.profiles.map((source) => ({ kind: "profile" as const, source })),
188-
...(fallback ? [directAttempt(fallback)] : []),
204+
...(authorizedFallback ? [directAttempt(authorizedFallback)] : []),
189205
],
190206
};
191207
}
192-
if (fallback) {
208+
if (authorizedFallback) {
193209
return {
194210
kind: "selected",
195-
selection: { kind: "selected", source: fallback },
196-
attempts: [directAttempt(fallback)],
211+
selection: { kind: "selected", source: authorizedFallback },
212+
attempts: [directAttempt(authorizedFallback)],
197213
};
198214
}
199215
return {
@@ -306,6 +322,10 @@ export function selectProviderModelRouteAuth(params: {
306322
),
307323
explicitOrder: params.sourcePlan.profiles.explicitOrder,
308324
allowCooldown: params.sourcePlan.allowCooldown,
325+
// Preserve what the operator actually declared. Filtering to a
326+
// route-compatible subset must not make a configured provider look
327+
// zero-config and thereby re-admit an ambient credential.
328+
declaredProfileCount: params.sourcePlan.declaredProfileCount,
309329
...(params.sourcePlan.fallback ? { fallback: params.sourcePlan.fallback } : {}),
310330
})
311331
: params.sourcePlan;

0 commit comments

Comments
 (0)