Skip to content

Commit 750a64e

Browse files
authored
fix(anthropic): keep Claude CLI authentication native (#129052)
Stop OpenClaw from copying or refreshing Claude CLI OAuth tokens. Claude CLI now owns native login and refresh state; Doctor removes retired copies while preserving CLI routing. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 22fa9f5 commit 750a64e

82 files changed

Lines changed: 1411 additions & 2983 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1712,7 +1712,6 @@ src/agents/auth-profiles/policy.ts 1
17121712
src/agents/auth-profiles/portability.ts 1
17131713
src/agents/auth-profiles/profiles.ts 1
17141714
src/agents/auth-profiles/repair.ts 1
1715-
src/agents/auth-profiles/runtime-external-profile-references.ts 2
17161715
src/agents/auth-profiles/runtime-snapshots.ts 1
17171716
src/agents/auth-profiles/source-check.ts 1
17181717
src/agents/auth-profiles/sqlite.ts 2
@@ -1738,7 +1737,7 @@ src/agents/cache-trace.ts 3
17381737
src/agents/channel-tools.ts 3
17391738
src/agents/cli-auth-epoch.ts 1
17401739
src/agents/cli-backends.ts 1
1741-
src/agents/cli-credentials.ts 15
1740+
src/agents/cli-credentials.ts 10
17421741
src/agents/cli-executable-identity.ts 3
17431742
src/agents/cli-output-records.ts 1
17441743
src/agents/cli-runner.ts 1
@@ -2527,7 +2526,6 @@ src/commands/doctor-agent-memory-schema.ts 1
25272526
src/commands/doctor-auth-flat-profiles.ts 5
25282527
src/commands/doctor-auth-migration-receipts.ts 3
25292528
src/commands/doctor-auth-profile-config.ts 4
2530-
src/commands/doctor-claude-cli.ts 1
25312529
src/commands/doctor-config-analysis.ts 3
25322530
src/commands/doctor-config-flow.ts 3
25332531
src/commands/doctor-config-preflight.cron.ts 4

‎config/max-lines-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,6 @@ src/agents/bash-tools.exec.approval-id.test.ts
323323
src/agents/bash-tools.process.ts
324324
src/agents/btw.test.ts
325325
src/agents/btw.ts
326-
src/agents/cli-auth-epoch.test.ts
327326
src/agents/cli-runner.reliability.test.ts
328327
src/agents/cli-runner.spawn.test.ts
329328
src/agents/cli-runner/execute.supervisor-capture.test.ts

‎docs/gateway/authentication.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,9 @@ claude auth status --text
5656
openclaw models auth login --provider anthropic --method cli --set-default
5757
```
5858

59-
This is two steps: log Claude Code into Anthropic on the host, then tell OpenClaw to route Anthropic model selection through the local `claude-cli` backend and store the matching OpenClaw auth profile.
59+
This is two steps: log Claude Code into Anthropic on the host, then tell OpenClaw to route Anthropic models through the local `claude-cli` backend.
6060

61-
At run time OpenClaw treats a reused Claude CLI login as Claude's own credential: it verifies the host's current `claude` login matches the selected profile's account and then lets the `claude` subprocess authenticate natively, so Claude keeps refreshing its own login during runs. OpenClaw never forwards a copied token for this path. If the host login is missing or belongs to a different account, the run fails before spawn with the exact re-authentication commands. OpenClaw-managed credentials (Anthropic OAuth login profiles, setup tokens, API keys) are still delivered to the subprocess directly and refreshed by OpenClaw where applicable.
61+
OpenClaw never reads, stores, refreshes, or forwards the native login tokens. The installed `claude` process reads and refreshes its own login. `CLAUDE_CONFIG_DIR` selects a separate Claude login when set on the Gateway process. OpenClaw-managed setup tokens and API keys remain separate credentials.
6262

6363
The gateway service must resolve `claude` on `PATH`. If a deployment needs a
6464
nonstandard executable path, register a wrapper through a

‎docs/gateway/cli-backends.md‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -118,10 +118,11 @@ The `openclaw agent` command also has its own request deadline. Its 600-second f
118118

119119
The bundled Anthropic plugin runs the installed Claude Code executable through
120120
Anthropic's official Agent SDK. Claude Code owns its existing local login and
121-
subscription; OpenClaw does not extract that login or send synthesized
122-
Anthropic API requests. Compatible agent turns share one warm SDK query and
123-
Claude Code subprocess. A changed model, system prompt, authenticated identity,
124-
or tool policy starts a new query; persisted Claude session IDs still provide
121+
subscription. OpenClaw uses a non-secret route marker. It never reads, persists,
122+
refreshes, or forwards native tokens, or sends synthesized Anthropic API
123+
requests. Compatible agent turns share one warm SDK query and
124+
Claude Code subprocess. A changed model, system prompt, or tool policy starts a
125+
new query; persisted Claude session IDs still provide
125126
conversation continuity when the gateway or subprocess restarts.
126127

127128
Keep Claude Code updated, especially if the SDK reports an incompatible
@@ -350,12 +351,12 @@ If no MCP servers are enabled, OpenClaw still injects a strict config when a bac
350351

351352
Session-scoped bundled MCP runtimes are cached for reuse within a session, then reaped after 10 minutes of idle time. One-shot embedded runs such as auth probes, slug generation, and active-memory recall request cleanup at run end so stdio children and Streamable HTTP/SSE streams do not outlive the run.
352353

353-
For `claude-cli`, an imported native OAuth profile reuses the matching,
354-
identity-verified Claude Code login without forwarding an extracted access
355-
token. Explicit non-native API-key and token profiles continue to use the
356-
protected, per-invocation credential-forwarding CLI path, keeping selected
357-
per-agent profiles authoritative without placing credential values in command
358-
arguments.
354+
For `claude-cli`, the installed Claude Code process uses its current native
355+
login. OpenClaw uses a non-secret route marker and never reads, persists,
356+
refreshes, selects, or forwards the native tokens.
357+
Set `CLAUDE_CONFIG_DIR` on the Gateway process to use a separate Claude configuration directory.
358+
Explicit OpenClaw-managed API-key and token profiles continue to use the
359+
protected, per-invocation credential-forwarding CLI path.
359360

360361
## Reseed history cap
361362

‎docs/providers/anthropic.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,16 @@ Anthropic builds the **Claude** model family. OpenClaw supports two auth routes:
1515

1616
OpenClaw detects the available Anthropic credential and selects the matching usage surface:
1717

18-
- Claude subscription/setup credentials show quota windows and optional extra-usage budget.
18+
- OpenClaw-managed subscription/setup credentials show quota windows and optional extra-usage budget.
19+
- Native Claude CLI logins stay under Claude's exclusive refresh control, so OpenClaw does not poll their quota endpoint.
1920
- `ANTHROPIC_ADMIN_KEY` or `ANTHROPIC_ADMIN_API_KEY` shows 30 days of provider-reported organization cost and Messages API usage in Control UI **Usage**, including daily spend, token/cache totals, top models, and cost categories.
2021
- An `sk-ant-admin...` credential stored in the Anthropic provider profile is detected as an Admin API key automatically.
2122

2223
Admin API cost history comes from Anthropic's [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api). It is actual provider billing, separate from OpenClaw's session-derived estimated cost.
2324

2425
<Warning>
25-
Claude Code owns its existing login and subscription; OpenClaw does not extract
26-
that login or synthesize Anthropic API requests. Agent SDK and `claude -p`
26+
Claude Code owns its existing login and subscription; OpenClaw does not persist
27+
or refresh that login. Agent SDK and `claude -p`
2728
usage currently draw from the signed-in subscription's limits. API-key auth
2829
uses separate pay-as-you-go billing and is preferable for shared automation or
2930
predictable production spend.
@@ -89,6 +90,13 @@ OpenClaw release:
8990

9091
```bash
9192
claude --version
93+
claude auth status --text
94+
```
95+
96+
If Claude is not logged in, authenticate once as the Gateway user:
97+
98+
```bash
99+
claude auth login
92100
```
93101

94102
If the installed build is incompatible, update Claude Code and restart
@@ -104,15 +112,15 @@ OpenClaw release:
104112
# choose: Claude CLI
105113
```
106114

107-
OpenClaw detects the existing Claude CLI login. Normal agent turns use
108-
the official Agent SDK with the installed, authenticated Claude Code
109-
executable, including native-tool turns whose approvals remain under
110-
OpenClaw control. Schema-valid native calls pass through OpenClaw's
111-
canonical tool policy before native approval. Imported native OAuth
112-
profiles reuse the verified Claude Code login; explicitly selected
113-
API-key or token credentials still use protected file-descriptor
114-
forwarding. Isolated side-question
115-
completions and paired-node execution retain the supervised CLI path.
115+
Normal agent turns use the official Agent SDK with the installed,
116+
authenticated Claude Code executable. OpenClaw uses a non-secret route
117+
marker and never reads, persists, refreshes, selects, or forwards the
118+
native login tokens. Claude owns the login and token refresh lifecycle.
119+
Explicitly selected API-key or token credentials still use protected
120+
file-descriptor forwarding. Native-tool approvals remain under OpenClaw
121+
control. Schema-valid native calls pass through OpenClaw's canonical
122+
tool policy before native approval. Isolated side-question completions
123+
and paired-node execution retain the supervised CLI path.
116124

117125
Consecutive agent turns reuse the same warm Agent SDK query and Claude
118126
Code subprocess when their authenticated session and execution policy

‎extensions/anthropic/agent-sdk.runtime.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ function createContext(
5353
cwd: "/tmp/openclaw-workspace",
5454
env: {
5555
HOME: "/tmp/claude-login-home",
56+
CLAUDE_CONFIG_DIR: "/tmp/claude-login-home/custom-config",
5657
PATH: "/usr/local/bin:/usr/bin",
5758
OPENCLAW_MCP_TOKEN: "test-grant-not-a-real-secret",
5859
},
Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,34 @@
11
import { beforeEach, expect, it, vi } from "vitest";
22

3-
const { readClaudeCliCredentialsCached } = vi.hoisted(() => ({
4-
readClaudeCliCredentialsCached: vi.fn(),
3+
const { spawnSync } = vi.hoisted(() => ({
4+
spawnSync: vi.fn(),
55
}));
66

7-
vi.mock("openclaw/plugin-sdk/provider-auth", () => ({
8-
readClaudeCliCredentialsCached,
9-
}));
7+
vi.mock("node:child_process", () => ({ spawnSync }));
108

11-
const { readClaudeCliCredentialsForRuntime, readClaudeCliCredentialsForSetupNonInteractive } =
12-
await import("./cli-auth-seam.js");
9+
const { probeClaudeCliAuthStatus } = await import("./cli-auth-seam.js");
1310

1411
beforeEach(() => {
15-
readClaudeCliCredentialsCached.mockReset();
12+
spawnSync.mockReset();
1613
});
1714

18-
it("keeps runtime Claude credential reads on the non-prompting path", () => {
19-
readClaudeCliCredentialsForRuntime();
15+
it("asks Claude CLI to verify its own login", () => {
16+
spawnSync.mockReturnValue({
17+
status: 0,
18+
stdout: JSON.stringify({ loggedIn: true, authMethod: "claude.ai" }),
19+
});
20+
21+
expect(probeClaudeCliAuthStatus()).toEqual({ status: "available" });
2022

21-
expect(readClaudeCliCredentialsCached).toHaveBeenCalledWith({ allowKeychainPrompt: false });
23+
expect(spawnSync).toHaveBeenCalledWith(
24+
"claude",
25+
["auth", "status", "--json"],
26+
expect.objectContaining({ timeout: 3_000 }),
27+
);
2228
});
2329

24-
it("uses the bounded credential inspector only for non-interactive setup", () => {
25-
readClaudeCliCredentialsForSetupNonInteractive();
30+
it("does not inspect Claude token storage when the CLI reports logout", () => {
31+
spawnSync.mockReturnValue({ status: 1, stdout: "" });
2632

27-
expect(readClaudeCliCredentialsCached).toHaveBeenCalledWith(
28-
expect.objectContaining({
29-
allowKeychainPrompt: false,
30-
tryKeychainWithoutPrompt: true,
31-
ttlMs: 0,
32-
onStoredCredentialUnreadable: expect.any(Function),
33-
}),
34-
);
33+
expect(probeClaudeCliAuthStatus()).toEqual({ status: "missing" });
3534
});
Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,33 @@
1-
/**
2-
* Claude CLI auth seam. Setup may prompt for keychain-backed credentials while
3-
* runtime paths stay non-interactive.
4-
*/
5-
import { readClaudeCliCredentialsCached } from "openclaw/plugin-sdk/provider-auth";
1+
import { spawnSync } from "node:child_process";
2+
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
63

7-
/** Read Claude CLI credentials for interactive setup paths. */
8-
export function readClaudeCliCredentialsForSetup() {
9-
return readClaudeCliCredentialsCached();
10-
}
4+
type ClaudeCliAuthStatus = { status: "available" } | { status: "missing" | "unreadable" };
115

12-
/** Read Claude CLI credentials for setup checks that must not prompt. */
13-
export function readClaudeCliCredentialsForSetupNonInteractive() {
14-
let unreadable = false;
15-
const credential = readClaudeCliCredentialsCached({
16-
allowKeychainPrompt: false,
17-
tryKeychainWithoutPrompt: true,
18-
ttlMs: 0,
19-
onStoredCredentialUnreadable: () => {
20-
unreadable = true;
21-
},
6+
/** Ask Claude CLI whether its own login is usable without reading token material. */
7+
export function probeClaudeCliAuthStatus(params?: {
8+
command?: string;
9+
env?: NodeJS.ProcessEnv;
10+
}): ClaudeCliAuthStatus {
11+
const result = spawnSync(params?.command ?? "claude", ["auth", "status", "--json"], {
12+
encoding: "utf8",
13+
env: params?.env ?? process.env,
14+
maxBuffer: 64 * 1024,
15+
timeout: 3_000,
16+
windowsHide: true,
2217
});
23-
return credential
24-
? ({ status: "available", credential } as const)
25-
: ({ status: unreadable ? "unreadable" : "missing" } as const);
26-
}
27-
28-
/** Read Claude CLI credentials for runtime without keychain prompts. */
29-
export function readClaudeCliCredentialsForRuntime() {
30-
return readClaudeCliCredentialsCached({ allowKeychainPrompt: false });
18+
if (result.error || result.status === null) {
19+
return { status: "unreadable" };
20+
}
21+
if (result.status !== 0) {
22+
return { status: "missing" };
23+
}
24+
try {
25+
const parsed: unknown = JSON.parse(result.stdout);
26+
if (!isRecord(parsed) || parsed.loggedIn !== true) {
27+
return { status: "missing" };
28+
}
29+
return { status: "available" };
30+
} catch {
31+
return { status: "unreadable" };
32+
}
3133
}

‎extensions/anthropic/cli-backend.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,9 @@ function resolveClaudeCliAuthInput(
9393
credential: ClaudeCliAuthCredential | undefined,
9494
): ClaudeCliPreparedExecution | undefined {
9595
// Forwarded OAuth here is OpenClaw-managed material (its refresh path is
96-
// OpenClaw-owned). Imported native `claude` logins are never forwarded —
97-
// core runs those as identity-verified passthrough — so an expired token
98-
// reaching this point is a real fault worth failing loudly, not refreshable
99-
// state this plugin could repair.
96+
// OpenClaw-owned). Native `claude` logins are never forwarded; the current
97+
// Claude process reads its own config directory. An expired token here is
98+
// therefore OpenClaw-managed state that must fail loudly.
10099
if (credential?.type === "oauth" && "access" in credential) {
101100
const expires = "expires" in credential ? credential.expires : undefined;
102101
if (typeof expires !== "number" || !Number.isFinite(expires) || expires <= Date.now()) {

‎extensions/anthropic/cli-constants.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@
44
*/
55
/** Synthetic provider/backend id for Claude Code CLI-backed Anthropic models. */
66
export const CLAUDE_CLI_BACKEND_ID = "claude-cli";
7-
/** Non-secret marker for Claude Code settings.json apiKeyHelper auth. */
8-
export const CLAUDE_CLI_API_KEY_HELPER_AUTH_MARKER = ["openclaw", "claude-cli-api-key-helper"].join(
9-
":",
10-
);
7+
/** Non-secret marker telling OpenClaw that the installed Claude CLI owns auth. */
8+
export const CLAUDE_CLI_NATIVE_AUTH_MARKER = ["openclaw", "claude-cli-native-auth"].join(":");
119
/** Default Claude CLI model ref for agent defaults and live tests. */
1210
export const CLAUDE_CLI_DEFAULT_MODEL_REF = `${CLAUDE_CLI_BACKEND_ID}/claude-opus-5`;
1311
/** Provider-relative model id for Anthropic runtime-policy resolution. */

0 commit comments

Comments
 (0)