Skip to content

fix(auth): do not admit ambient environment credentials behind declared profiles - #118458

Merged
Patrick-Erichsen merged 1 commit into
openclaw:mainfrom
Marvinthebored:fix/ambient-credential-admission
Aug 4, 2026
Merged

Patrick-Erichsen merged 1 commit into
openclaw:mainfrom
Marvinthebored:fix/ambient-credential-admission

Conversation

@Marvinthebored

@Marvinthebored Marvinthebored commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Related: #117956

AI-assisted PR (Claude Code). Session log linked at the bottom. I understand what the code does and
have validated it locally and against a live gateway; evidence below.

Supersedes #118457, which closed automatically when I deleted the fork holding its head branch.
Same commit, no review had taken place on it.

What Problem This Solves

Fixes an issue where operators who authenticate a provider with a subscription auth profile, and who
also happen to have that provider's API key in their environment for some unrelated named consumer,
could silently have inference billed to the API key instead of their subscription.

The environment variable is never mentioned in their config — not in the provider entry, not in
auth.profiles, not in auth.order. It is picked up purely because it exists in the process
environment, and it is then queued as a backup credential behind the profiles they did declare. If a
run leaves the declared profile for any reason, it continues on the undeclared credential. Status
keeps reporting the subscription throughout, and nothing warns that the switch happened.

In #117956 this produced metered API usage on an account the operator had not routed anything to. It
was discovered from a billing console, not from any signal in the product.

This is a regression in the 2026.7.2 prereleases. Before 1b1cebfe4218 (#104685, 2026-07-11) an
environment credential was only reachable when a provider had no declared profiles — the documented
zero-config path. It was never queued behind declared profiles:

// embedded-agent-runner/run.ts, immediately before #104685
: providerOrderedProfiles.length > 0
    ? providerOrderedProfiles   // declared profiles only — no environment candidate appended
    : [undefined];              // no profiles at all -> a single direct/environment candidate
release affected
v2026.7.0 no
v2026.7.1 (current GA) no
v2026.7.2-beta.1 (2026-07-15) onward yes

No GA release is affected.

Why This Change Was Made

Credentials that config never names must not be able to inherit a declared credential's traffic,
because the two can bill different accounts. Moving between them should be something an operator
states, not something the runtime infers from an environment variable being present.

The change adds an explicit authorization: "declared" | "ambient" fact to direct auth sources and
enforces it during source selection. An ambient credential may still serve a provider that has no
declared profiles — the documented zero-config PROVIDER_API_KEY path is unchanged — but it is no
longer admitted behind declared profiles, nor substituted for declared profiles that turn out to be
unusable.

Two deliberate design decisions:

  • authorization is required, not defaulted. A permissive default is what let an entire module
    (model-auth-availability.ts) escape the rule during development. Making the compiler demand it
    forced every construction site to be audited.
  • It is not expressed through the existing evidence field. evidence is provenance — where a
    credential was found — and is reported as such by status and probe surfaces. It cannot carry
    authorization, because a declared credential is legitimately environment-sourced: a ${VAR} marker
    is reported as evidence: "environment" while being fully declared.

The same classification is applied in the read-only availability evaluator so status cannot advertise
a credential the runtime would refuse.

Non-goals. Failover currently treats a transport-level failure the same as a credential failure
when the harness does not own transport, so a network fault can advance a run to the next prepared
attempt. That is a separate concern from whether a credential should have been eligible at all, and
is left for a follow-up.

User Impact

Operators keep exactly the auth behavior they configured, and stop getting the behavior they did not:

  • Declared auth.order failover is unchanged — every ordered profile is still attempted, in order.
  • Zero-config PROVIDER_API_KEY is unchanged for providers with no auth profiles.
  • Declared apiKey material (literal, ${VAR} marker, SecretRef), setup-provider identities
    (Vertex/gcloud ADC), aws-sdk auth, user locks and provider bindings are all unaffected.
  • An undeclared environment credential is no longer silently used behind a declared profile.

Behavior that changes, all 2026.7.2-beta only:

  1. Declared profiles plus a bare PROVIDER_API_KEY used as an unstated backup — the declared
    credential's failure now surfaces instead of switching accounts silently.
  2. models.providers.<id>.auth set to api-key/oauth with no apiKey material, plus stored profiles
    and an environment credential — auth alone does not make the environment key declared.
  3. A provider whose only profile is unusable but which has an ambient key now reports unavailable
    rather than quietly serving from that key.

The supported way to express an API-key backup is unchanged and still works: create an API-key auth
profile and add its id to auth.order.<provider> (docs/concepts/model-failover.md). auth.order
carries routing metadata only and holds no credential, so the profile must exist first.

Evidence

1. Regression test reproduces the reported configuration and fails on main.
prepare-auth.ambient-credential.test.ts builds the config from #117956 (anthropic plugin disabled so
claude-cli resolves as a bare custom provider, one subscription OAuth profile, no auth.order,
ANTHROPIC_API_KEY in the environment) and asserts the prepared attempt list.

On main:

AssertionError: expected [ { kind: 'profile', …(2) }, …(1) ] to match object [ { kind: 'profile', …(1) } ]
      "kind": "profile",
+     "kind": "direct",

With this change: passes. The direct entry is the undeclared credential.

2. Same comparison, driven from a real host config file rather than a fixture — the affected
operator's openclaw.json with the plugin disabled and the key present:

STOCK    attempts: [ profile:anthropic:claude-cli, direct:undefined ]
PATCHED  attempts: [ profile:anthropic:claude-cli ]

3. Not provider-specific. The same host also had OPENAI_API_KEY set alongside a ChatGPT OAuth
profile. Identical exposure, with and without a store-level order override:

STOCK    profile:openai:chatgpt-account , DIRECT(env)
PATCHED  profile:openai:chatgpt-account

4. Declared auth.order failover is preserved — two tests, both with an ambient key deliberately
present in the environment:

scenario prepared attempts
two ordered profiles ["openai:primary", "openai:backup"]
documented subscription → API-key backup ["openai:chatgpt", "openai:platform"]

The second is the configuration this PR recommends to affected operators, so it needed to be pinned.

5. Selector branch coverage in provider-model-route-auth.test.ts: ambient dropped behind usable
profiles; declared fallback preserved behind usable profiles; ambient preserved with no declared
profiles; ambient not substituted for all-unavailable profiles; ambient not re-admitted when route
filtering empties the profile list.

6. Live gateway. Built and restarted a real gateway on this change, then exercised both routes
through a Discord channel. Normal operation is unaffected — the transcript records
api=cli provider=claude-cli model=claude-opus-5, i.e. the subscription path. Reproducing the
incident configuration (plugin disabled, deliberately invalid dummy key in env.vars) the run stayed
on the declared profile — modelApi: "anthropic-messages" — and completed with no auth error and no
rotation; the dummy key was never used.

7. Local validation. Typecheck clean, lint clean, 263 tests passing across the auth scope
(planner, selector, resolver, availability, setup-provider, and the new regression file).

Note for reviewers: this change is scoped to admission — which credentials are eligible. It does not
attempt to prove which credential a given run ultimately materializes, since that depends on the
failover behavior listed as a non-goal above.


🤖 Generated with Claude Code

https://claude.ai/code/session_01Nwk2KaB6zL71xa1i3Xwgwi

…ed 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 (openclaw#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 openclaw#117956.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Nwk2KaB6zL71xa1i3Xwgwi
@Marvinthebored
Marvinthebored requested a review from a team as a code owner August 3, 2026 04:36
@Marvinthebored

Copy link
Copy Markdown
Contributor Author

Reported by @Peetiegonzalez in #117956, who confirmed the metered usage against the provider console and reviewed this fix before filing. Tagging for follow-ups.

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Aug 3, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Aug 3, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Aug 3, 2026
@clawsweeper

clawsweeper Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 3, 2026, 1:17 AM ET / 05:17 UTC.

ClawSweeper review

What this changes

The branch distinguishes declared from ambient provider credentials so an environment-only credential cannot become a fallback behind configured auth profiles, while preserving zero-config API-key use and explicitly ordered profile failover.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

The PR addresses a current-main auth-planning regression: an environment-only direct credential is appended after declared profiles and can therefore receive traffic the operator did not configure. The authorization fact is carried through the runtime planner, route selector, and availability resolver; the remaining blocker is maintainer acceptance of the deliberate beta-only fallback withdrawal before merge.

Priority: P1
Reviewed head: 7a6842276891c0b7a9f4b80c810c664e2b1c807a
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a well-scoped owner-boundary repair with strong focused coverage and credible live proof; merge still needs an auth-owner compatibility decision.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body includes before-and-after prepared-attempt output, a real-gateway Discord exercise, and redacted live runtime observations that directly cover the changed admission behavior.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body includes before-and-after prepared-attempt output, a real-gateway Discord exercise, and redacted live runtime observations that directly cover the changed admission behavior.
Evidence reviewed 8 items Current-main regression: The automatic selector appends any fallback after usable declared profiles and also selects it when profiles are unavailable, so a direct environment credential can become a later runtime attempt.
Canonical repair boundary: The branch makes authorization explicit on direct sources rather than overloading provenance, forcing every direct-source constructor to classify the credential as declared or ambient.
Route-filter safety: When route compatibility narrows the profile list, the branch preserves the original declared-profile count so filtering cannot accidentally treat a configured provider as zero-config and re-admit an ambient credential.
Findings None None.
Security None None.

How this fits together

OpenClaw turns provider configuration, stored auth profiles, and discovered credentials into ordered model-auth attempts. Those attempts feed model-route selection, runtime failover, and status availability, so admission must agree across all three surfaces.

flowchart LR
  A[Provider configuration] --> D[Auth source plan]
  B[Stored auth profiles] --> D
  C[Environment credentials] --> D
  D --> E[Authorization admission]
  E --> F[Route-specific attempts]
  F --> G[Runtime failover]
  E --> H[Status availability]
Loading

Decision needed

Question Recommendation
Should OpenClaw withdraw the implicit ambient environment-key fallback from 2026.7.2 beta configurations before GA, requiring operators to declare an API-key backup profile in auth.order? Merge the declared-only policy: Accept the beta-only compatibility withdrawal so failover can use only credentials the operator explicitly configured.

Why: The implementation is internally consistent and preserves zero-config credentials and declared failover, but it deliberately changes a beta operator fallback path that can affect billing and runtime recovery.

Before merge

  • Resolve merge risk (P2) - Merging intentionally removes the implicit environment-key fallback for beta configurations that combine declared profiles with a bare provider key; affected operators must create and order an explicit API-key profile if they want that fallback.
Agent review details

Security

None.

PR surface

Source +90, Tests +266. Total +356 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 6 98 8 +90
Tests 4 302 36 +266
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 400 44 +356

Review metrics

Metric Value Why it matters
Production versus regression coverage production +98/-8; tests +302/-36 The net production growth establishes one explicit authorization boundary across runtime and status; the larger test delta covers preserved zero-config, ordered-profile, unavailable-profile, and route-filter cases.

Merge-risk options

Maintainer options:

  1. Accept the declared-only beta contract (recommended)
    Merge after the auth owner confirms that operators must declare and order any backup credential they want failover to use.
  2. Pause for compatibility direction
    Keep the PR open if maintainers intend bare environment credentials to remain an implicit fallback behind configured profiles.

Technical review

Best possible solution:

Merge before the 2026.7.2 GA release once the auth owner confirms that explicit profiles, rather than ambient process credentials, are the supported cross-account failover contract.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: current main appends a direct fallback after usable declared profiles and selects it when those profiles are unavailable. The new focused regression constructs that exact declared-profile plus ambient-key shape, although this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. The required authorization fact separates policy from credential provenance, keeps declared environment references valid, preserves zero-config use when no profile exists, and prevents route filtering from reintroducing the ambient fallback.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0fadfc6dae52.

Labels

Label justifications:

  • P1: A declared subscription or profile can currently fall through to an undeclared provider credential, potentially causing unexpected billed usage.
  • merge-risk: 🚨 compatibility: The patch deliberately stops a previously admitted implicit fallback in beta configurations that have both declared profiles and an environment-only credential.
  • merge-risk: 🚨 auth-provider: The patch changes which provider credentials can be selected for runtime attempts and reported as available.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body includes before-and-after prepared-attempt output, a real-gateway Discord exercise, and redacted live runtime observations that directly cover the changed admission behavior.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes before-and-after prepared-attempt output, a real-gateway Discord exercise, and redacted live runtime observations that directly cover the changed admission behavior.

Evidence

What I checked:

Likely related people:

  • steipete: Introduced the effective-route auth-planning feature that created the current source-plan and selector behavior. (role: feature introducer; confidence: high; commits: 1b1cebfe4218, bad37249f5ec; files: src/agents/provider-model-auth-source-plan.ts, src/agents/provider-model-route-auth.ts, src/agents/runtime-plan/prepare-auth.ts)
  • Vincent Koc: Recent auth-plan refactors touched the selector and runtime planner after the original route-auth feature landed. (role: recent area contributor; confidence: medium; commits: e45f2f6ca670, e06b42674b4d; files: src/agents/provider-model-route-auth.ts, src/agents/runtime-plan/prepare-auth.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain auth-owner confirmation that declared profiles are the required migration path for beta operators who previously relied on an ambient backup key.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-03T04:44:02.360Z sha 7a68422 :: needs maintainer review before merge. :: none

@Patrick-Erichsen Patrick-Erichsen self-assigned this Aug 3, 2026
@Patrick-Erichsen
Patrick-Erichsen merged commit 778be6f into openclaw:main Aug 4, 2026
319 of 342 checks passed
vincentkoc added a commit that referenced this pull request Aug 4, 2026
* origin/main: (54 commits)
  test(qa): cover agent session streaming (#119028)
  test(qa): cover sandbox workspace isolation (#119038)
  test(qa): cover progress followthrough evidence (#119039)
  fix(auth): cooldown inline api key billing failures (#88709)
  chore(gateway): cover update and setup RPCs
  test(qa): prove ClawHub catalog discovery (#118934)
  chore(qa): cover plugin testing harness contracts (#118933)
  test(qa): prove failure recovery visibility (#119034)
  test(qa): cover direct tool invocation (#119025)
  test(qa): close external app SDK proof gaps (#118978)
  test(qa): prove container health endpoints (#119012)
  test(qa): claim sessionless heartbeat coverage (#119027)
  fix(gateway): keep plugin model allowlists static (#118854)
  fix(plugins): refresh bundled channel skills (#119020)
  test(qa): cover ClawHub package compatibility (#118985)
  test(qa): cover agent session reconnect dedupe (#119013)
  test(qa): prove gateway chat RPCs (#118988)
  test(ui): cover Control UI auth transports (#118866)
  fix(auth): do not admit ambient environment credentials behind declared profiles (#118458)
  test(ui): cover operator administration flows (#118836)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 4, 2026
…ed profiles (openclaw#118458)

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 e00b05b (openclaw#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 openclaw#117956.


Claude-Session: https://claude.ai/code/session_01Nwk2KaB6zL71xa1i3Xwgwi

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants