Skip to content

Commit 95be517

Browse files
committed
fix(agents): preserve native GitHub CLI auth
1 parent 34dee10 commit 95be517

9 files changed

Lines changed: 106 additions & 62 deletions

‎docs/gateway/config-tools.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ Controls elevated exec access outside the sandbox:
213213

214214
### `tools.github`
215215

216-
GitHub CLI identity is native by default. When `tools.github` is omitted, local agent tools and the Codex harness use the Gateway runtime user's existing `gh` keyring/config and Git author without changing them. Ambient `GH_TOKEN` and `GITHUB_TOKEN` service values are not restored into agent shells. Agent Settings clears those variables while probing the effective `gh` account and reads the Git author from the selected agent's workspace.
216+
GitHub CLI identity is native by default. When `tools.github` is omitted, local agent tools, the Codex harness, and Agent Settings follow normal `gh` resolution: `GH_TOKEN` or `GITHUB_TOKEN` from the Gateway process takes precedence, followed by the runtime user's `gh` keyring/config. The Git author comes from the selected agent's workspace.
217217

218218
Use **Agents → Tools → GitHub CLI Identity** to configure a managed fine-grained personal access token. The browser places the pasted token in the secret store as a one-use handoff. The Gateway hard-deletes that handoff before passing its value to `gh auth login` on stdin, verifies the account, publishes an account-owned managed `gh` profile, and stores only this secret-free config:
219219

@@ -250,7 +250,7 @@ The profile is not forwarded to node hosts, OpenClaw sandboxes, remote-exec plac
250250

251251
Verification proves which account answered the GitHub API request. Status distinguishes missing or invalid managed credentials, unverified transport failures, and GitHub rate limiting without returning `gh` diagnostics. It does not claim that fine-grained write permissions or Git transport access were remotely verified. GitHub App and brokered publication support remain future work.
252252

253-
Control UI repository previews and project discovery use the separate optional `gateway.controlUi.github.token` service credential. They never consume an agent tool identity.
253+
Control UI repository previews and project discovery use the separate optional `gateway.controlUi.github.token` service credential. They never consume an agent tool identity. When this SecretRef is explicit, OpenClaw excludes its exact environment or store name from agent execution. A custom name does not clear unrelated `GH_TOKEN` or `GITHUB_TOKEN` values used by native identity; a ref named `GH_TOKEN` or `GITHUB_TOKEN` excludes that exact variable.
254254

255255
### `tools.exec`
256256

‎docs/gateway/configuration-reference.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,7 @@ Gateway or node host and check `openclaw nodes pending` again.
824824
run `openclaw config set gateway.tailscale.mode funnel`, followed by
825825
`openclaw config unset gateway.tailscale.preserveFunnel`. Default `false`.
826826
- `controlUi.allowedOrigins`: explicit browser-origin allowlist for Gateway WebSocket connects. Required for public non-loopback browser origins. Private same-origin LAN/Tailnet UI loads from loopback, RFC1918/link-local, `.local`, `.ts.net`, or Tailscale CGNAT hosts are accepted without enabling Host-header fallback.
827-
- `controlUi.github.token`: optional SecretRef-backed service credential for Control UI GitHub previews and project discovery. Prefer this explicit setting when the Gateway should own GitHub service access independently of its shared process environment. When omitted, the shipped `GH_TOKEN` then `GITHUB_TOKEN` process-environment fallback remains active. An explicitly configured but unavailable credential fails closed instead of using that fallback. This credential is separate from `tools.github` agent identities and does not create an OS-user security boundary.
827+
- `controlUi.github.token`: optional SecretRef-backed service credential for Control UI GitHub previews and project discovery. Prefer this explicit setting when the Gateway should own GitHub service access independently of its shared process environment. When omitted, the shipped `GH_TOKEN` then `GITHUB_TOKEN` process-environment fallback remains active. An explicitly configured but unavailable credential fails closed instead of using that fallback. Its exact environment or store name is excluded from agent execution; a custom name does not clear unrelated native `GH_TOKEN` or `GITHUB_TOKEN` values. This credential is separate from `tools.github` agent identities and does not create an OS-user security boundary.
828828
- `controlUi.toolTitles`: opt in to AI-generated purpose titles for tool calls in Control UI chat. Default: `false` (tool rendering stays fully deterministic with no background model calls). When enabled, the `chat.toolTitles` method labels complex calls through standard utility-model routing — the agent's `utilityModel` (an operator decision that may send bounded tool arguments to the chosen provider, like every utility task), or the session provider's declared small-model default (OpenAI → `gpt-5.6-luna`, Anthropic → `claude-haiku-4-5`) — and caches results in the per-agent state database so repeat views never re-bill. `utilityModel: \"\"` disables titles like every other utility task; titles never fall back to the primary model.
829829
- `controlUi.dangerouslyAllowHostHeaderOriginFallback`: dangerous mode that enables Host-header origin fallback for deployments that intentionally rely on Host-header origin policy.
830830
- `cliAgents.enabled`: opt in to the experimental **CLI agents** group in the Control UI new-session model picker. Default: `false`. The group appears only when the Gateway advertises `sessions.catalog.list`, and it includes only catalog providers that support creating sessions. Selecting one opens the same catalog-target new-session flow used by the sidebar catalog action.

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ The **+** in the sidebar session-list header opens a full-page draft at `/new`:
240240

241241
**Projects.** The Place picker lists configured agent workspaces and repositories recorded with `projects.register`. Read-only connections receive project names and IDs; checkout paths and origin URLs are included only at `operator.write`. An admin can browse to a Git checkout and choose **Register as project**; write-only operators see a hint directing them to that flow. Choosing a project sends its ID through `sessions.create`, so it can run directly or supply the source for optional Worktree isolation without submitting a raw path. If its checkout was moved or removed, re-register it or run `openclaw doctor --fix` before starting another session there.
242242

243-
**Projects from GitHub.** Search the same picker or paste a GitHub HTTPS or `[email protected]` repository URL to clone it into the Gateway-managed projects area and select it. Public repository search and cloning work anonymously. For affiliated and private repositories, prefer the explicit `gateway.controlUi.github.token` SecretRef so this service access has a clear runtime owner. When it is omitted, the Gateway still uses its shipped `GH_TOKEN` then `GITHUB_TOKEN` fallback from the shared process environment. Search requires `operator.read`, cloning requires `operator.write`, and deleting a Gateway-managed cloned checkout requires `operator.admin`. Clone deletion refuses while a live session or managed worktree still references the checkout. SecretRef ownership is not an OS-user security boundary; use a sandbox, dedicated host, or dedicated OS user when same-account processes are not trusted.
243+
**Projects from GitHub.** Search the same picker or paste a GitHub HTTPS or `[email protected]` repository URL to clone it into the Gateway-managed projects area and select it. Public repository search and cloning work anonymously. For affiliated and private repositories, prefer the explicit `gateway.controlUi.github.token` SecretRef so this service access has a clear runtime owner. When it is omitted, the Gateway still uses its shipped `GH_TOKEN` then `GITHUB_TOKEN` fallback from the shared process environment. When it is explicit, its exact environment or store name is excluded from agent execution without clearing unrelated native GitHub CLI variables. Search requires `operator.read`, cloning requires `operator.write`, and deleting a Gateway-managed cloned checkout requires `operator.admin`. Clone deletion refuses while a live session or managed worktree still references the checkout. SecretRef ownership is not an OS-user security boundary; use a sandbox, dedicated host, or dedicated OS user when same-account processes are not trusted.
244244

245245
For agent GitHub CLI identity and Git author setup, see [`tools.github`](/gateway/config-tools#tools-github).
246246

‎extensions/codex/src/app-server/run-attempt-connection.test.ts‎

Lines changed: 1 addition & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -22,32 +22,7 @@ import {
2222
setupRunAttemptTestHooks();
2323

2424
describe("prepareCodexAttemptConnection", () => {
25-
it("clears ambient GitHub service tokens for a native local profile", async () => {
26-
const sessionFile = path.join(tempDir, "native-local-process-env.jsonl");
27-
const workspaceDir = path.join(tempDir, "workspace-native-local-process-env");
28-
const params = createParams(sessionFile, workspaceDir);
29-
params.hostCapabilities = Object.freeze({
30-
...params.hostCapabilities,
31-
preparedEnvironment: () =>
32-
Object.freeze({
33-
credentialScrubEnv: Object.freeze({ GH_TOKEN: "", GITHUB_TOKEN: "" }),
34-
localIdentityEnv: Object.freeze({}),
35-
managedLocalIdentity: false,
36-
}),
37-
});
38-
registerCodexTestSessionIdentity(sessionFile, params.sessionId, params.sessionKey);
39-
40-
const connection = await prepareCodexAttemptConnection({
41-
params,
42-
options: { bindingStore: testCodexAppServerBindingStore },
43-
});
44-
45-
expect(connection.appServer.start.env).toMatchObject({ GH_TOKEN: "", GITHUB_TOKEN: "" });
46-
expect(connection.shellEnvironment).toEqual({ GH_TOKEN: "", GITHUB_TOKEN: "" });
47-
expect(connection.disableLoginShell).toBe(true);
48-
});
49-
50-
it("preserves native login-shell behavior when no credential overlay exists", async () => {
25+
it("preserves native process environment and login-shell behavior for an empty overlay", async () => {
5126
const sessionFile = path.join(tempDir, "native-local-no-overlay.jsonl");
5227
const workspaceDir = path.join(tempDir, "workspace-native-local-no-overlay");
5328
const params = createParams(sessionFile, workspaceDir);

‎src/agents/bash-tools.exec-request-preparation.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,7 @@ export function resolvePreparedExecEnvironment(params: {
371371
secretEgressEnv?: Record<string, string>;
372372
credentialScrubEnv?: Readonly<Record<string, string>>;
373373
localIdentityEnv?: Readonly<Record<string, string>>;
374+
managedLocalIdentity?: boolean;
374375
warnings: string[];
375376
}): { env: Record<string, string>; requestedEnv?: Record<string, string> } {
376377
const inheritedBaseEnv = coerceEnv(process.env);
@@ -495,6 +496,16 @@ export function resolvePreparedExecEnvironment(params: {
495496
applyPathPrepend(env, params.defaultPathPrepend);
496497
}
497498

499+
if (params.host === "gateway" && params.managedLocalIdentity === false) {
500+
// Native GitHub identity is the explicit exception to the generic host-secret filter.
501+
// Exact service-owner scrubs below still win; non-local hosts receive neither value.
502+
for (const name of ["GH_TOKEN", "GITHUB_TOKEN"] as const) {
503+
const value = process.env[name];
504+
if (typeof value === "string") {
505+
env[name] = value;
506+
}
507+
}
508+
}
498509
if (params.storeSecretEnv) {
499510
// Secret-kind entries are authenticated ciphertext, not active credentials.
500511
// Inject them after ordinary env filtering so names such as GH_TOKEN remain usable.

‎src/agents/bash-tools.github-identity.test.ts‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ function prepare(
2323
prepared?: {
2424
credentialScrubEnv: Readonly<Record<string, string>>;
2525
localIdentityEnv: Readonly<Record<string, string>>;
26+
managedLocalIdentity?: boolean;
2627
},
28+
includeStoreSecrets = true,
2729
) {
2830
return resolvePreparedExecEnvironment({
2931
execParams: { command: "gh api user" },
@@ -38,20 +40,24 @@ function prepare(
3840
}
3941
: {}),
4042
defaultPathPrepend: [],
41-
storeSecretEnv: { GH_TOKEN: "store-sentinel", GITHUB_TOKEN: "store-sentinel" },
43+
storeSecretEnv: includeStoreSecrets
44+
? { GH_TOKEN: "store-sentinel", GITHUB_TOKEN: "store-sentinel" }
45+
: undefined,
4246
credentialScrubEnv: prepared?.credentialScrubEnv,
4347
localIdentityEnv: prepared?.localIdentityEnv,
48+
managedLocalIdentity: prepared?.managedLocalIdentity,
4449
warnings: [],
4550
});
4651
}
4752

4853
describe("exec GitHub identity", () => {
49-
it("does not restore ambient service tokens and applies managed identity only to local gateway exec", () => {
54+
it("blanks ambient service tokens and applies managed identity only to local gateway exec", () => {
5055
setTestEnvValue("GH_TOKEN", "ambient-token");
5156
setTestEnvValue("GITHUB_TOKEN", "ambient-fallback");
5257
const prepared = {
5358
credentialScrubEnv: { GH_TOKEN: "", GITHUB_TOKEN: "" },
5459
localIdentityEnv: { GH_CONFIG_DIR: "/private/managed-gh", GIT_AUTHOR_NAME: "Managed" },
60+
managedLocalIdentity: true,
5561
};
5662
for (const host of ["gateway", "node", "sandbox"] as const) {
5763
const result = prepare(host, prepared);
@@ -71,6 +77,50 @@ describe("exec GitHub identity", () => {
7177
}
7278
});
7379

80+
it("preserves ambient service tokens for unconfigured local gateway exec", () => {
81+
setTestEnvValue("GH_TOKEN", "ambient-token");
82+
setTestEnvValue("GITHUB_TOKEN", "ambient-fallback");
83+
const prepared = prepareGitHubToolEnvironment({ config: {}, agentId: "main" });
84+
85+
for (const host of ["gateway", "node", "sandbox"] as const) {
86+
const result = prepare(host, prepared, false);
87+
expect(result.env.GH_TOKEN).toBe(host === "gateway" ? "ambient-token" : undefined);
88+
expect(result.env.GITHUB_TOKEN).toBe(host === "gateway" ? "ambient-fallback" : undefined);
89+
expect(result.requestedEnv).toBeUndefined();
90+
}
91+
});
92+
93+
it.each([
94+
{ previewName: "GH_TOKEN", otherName: "GITHUB_TOKEN" },
95+
{ previewName: "GITHUB_TOKEN", otherName: "GH_TOKEN" },
96+
] as const)(
97+
"scrubs only an explicitly owned $previewName preview variable",
98+
({ previewName, otherName }) => {
99+
setTestEnvValue("GH_TOKEN", "ambient-token");
100+
setTestEnvValue("GITHUB_TOKEN", "ambient-fallback");
101+
const prepared = prepareGitHubToolEnvironment({
102+
config: {},
103+
sourceConfig: {
104+
gateway: {
105+
controlUi: {
106+
github: {
107+
token: { source: "env", provider: "default", id: previewName },
108+
},
109+
},
110+
},
111+
},
112+
agentId: "main",
113+
});
114+
115+
const result = prepare("gateway", prepared, false);
116+
117+
expect(result.env[previewName]).toBe("");
118+
expect(result.env[otherName]).toBe(
119+
otherName === "GH_TOKEN" ? "ambient-token" : "ambient-fallback",
120+
);
121+
},
122+
);
123+
74124
it.each([
75125
{ identity: "native", managed: false },
76126
{ identity: "managed", managed: true },
@@ -98,6 +148,8 @@ describe("exec GitHub identity", () => {
98148
const result = prepare(host, prepared);
99149
expect(result.env.PREVIEW_SERVICE_TOKEN).toBe("");
100150
expect(result.requestedEnv?.PREVIEW_SERVICE_TOKEN).toBe("");
151+
expect(result.env.GH_TOKEN).toBe(managed ? "" : "store-sentinel");
152+
expect(result.env.GITHUB_TOKEN).toBe(managed ? "" : "store-sentinel");
101153
}
102154
});
103155

‎src/agents/github-tool-identity.test.ts‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ describe("GitHub tool identity", () => {
3434
processMocks.runCommandBuffered.mockResolvedValue(commandResult());
3535
});
3636

37-
it("clears native service tokens and gives an agent override complete precedence", async () => {
37+
it("gives a managed agent override complete precedence", async () => {
3838
const stateDir = tempDirs.make("openclaw-github-state-");
3939
const config = {
4040
tools: {
@@ -121,8 +121,7 @@ describe("GitHub tool identity", () => {
121121
agentId: "main",
122122
});
123123
expect(envScrub.credentialScrubEnv).toEqual({
124-
GH_TOKEN: "",
125-
GITHUB_TOKEN: "",
124+
...(managed ? { GH_TOKEN: "", GITHUB_TOKEN: "" } : {}),
126125
PREVIEW_SERVICE_TOKEN: "",
127126
});
128127
expect(Object.keys(envScrub.localIdentityEnv).length).toBe(managed ? 1 : 0);
@@ -148,7 +147,7 @@ describe("GitHub tool identity", () => {
148147
expect(storeScrub.excludedStoreNames).toEqual(["PREVIEW_STORE_TOKEN"]);
149148
});
150149

151-
it("scrubs ambient credentials without treating native identity as managed", () => {
150+
it("preserves ambient credentials for native identity", () => {
152151
const native = prepareGitHubToolEnvironment({
153152
config: {},
154153
agentId: "main",
@@ -162,27 +161,37 @@ describe("GitHub tool identity", () => {
162161
const ambient = prepareGitHubToolEnvironment({
163162
config: {},
164163
agentId: "main",
165-
env: { GH_TOKEN: "test-token" },
164+
env: { GH_TOKEN: "test-token", GITHUB_TOKEN: "fallback-token" },
166165
});
167166
expect(ambient).toMatchObject({
168-
credentialScrubEnv: { GH_TOKEN: "", GITHUB_TOKEN: "" },
167+
credentialScrubEnv: {},
169168
managedLocalIdentity: false,
170169
});
170+
});
171171

172-
const previewEnvRef = prepareGitHubToolEnvironment({
173-
config: {
172+
it.each([
173+
{ source: "env", id: "PREVIEW_SERVICE_TOKEN", expected: { PREVIEW_SERVICE_TOKEN: "" } },
174+
{ source: "env", id: "GH_TOKEN", expected: { GH_TOKEN: "" } },
175+
{ source: "env", id: "GITHUB_TOKEN", expected: { GITHUB_TOKEN: "" } },
176+
{ source: "store", id: "GH_TOKEN", expected: { GH_TOKEN: "" } },
177+
{ source: "store", id: "GITHUB_TOKEN", expected: { GITHUB_TOKEN: "" } },
178+
] as const)("scrubs only the explicit $source preview ref $id", ({ source, id, expected }) => {
179+
const prepared = prepareGitHubToolEnvironment({
180+
config: {},
181+
sourceConfig: {
174182
gateway: {
175183
controlUi: {
176184
github: {
177-
token: { source: "env", provider: "default", id: "PREVIEW_SERVICE_TOKEN" },
185+
token: { source, provider: "default", id },
178186
},
179187
},
180188
},
181189
},
182190
agentId: "main",
183-
env: {},
191+
env: { GH_TOKEN: "test-token", GITHUB_TOKEN: "fallback-token" },
184192
});
185-
expect(previewEnvRef.credentialScrubEnv.PREVIEW_SERVICE_TOKEN).toBe("");
193+
expect(prepared.credentialScrubEnv).toEqual(expected);
194+
expect(prepared.excludedStoreNames).toEqual(source === "store" ? [id] : []);
186195
});
187196

188197
it("fails closed when a configured managed profile is absent", async () => {
@@ -230,7 +239,7 @@ describe("GitHub tool identity", () => {
230239
expect(JSON.stringify(status)).not.toContain("stderr");
231240
});
232241

233-
it("probes native gh without ambient tokens and reads Git author in the selected workspace", async () => {
242+
it("probes native gh with ambient token precedence and reads Git author in the workspace", async () => {
234243
const workspace = tempDirs.make("openclaw-github-workspace-");
235244
processMocks.runCommandBuffered.mockImplementation(async (argv: string[]) =>
236245
argv[0] === "gh"
@@ -241,11 +250,15 @@ describe("GitHub tool identity", () => {
241250
await resolveGitHubToolIdentityStatus({
242251
config: { agents: { defaults: { workspace } } },
243252
agentId: "main",
253+
env: { GH_TOKEN: "native-primary", GITHUB_TOKEN: "native-fallback" },
244254
});
245255

246256
const ghCall = processMocks.runCommandBuffered.mock.calls.find(([argv]) => argv[0] === "gh");
247257
const gitCall = processMocks.runCommandBuffered.mock.calls.find(([argv]) => argv[0] === "git");
248-
expect(ghCall?.[1]?.env).toMatchObject({ GH_TOKEN: undefined, GITHUB_TOKEN: undefined });
258+
expect(ghCall?.[1]?.env).toMatchObject({
259+
GH_TOKEN: "native-primary",
260+
GITHUB_TOKEN: "native-fallback",
261+
});
249262
expect(gitCall?.[1]).toMatchObject({ cwd: workspace });
250263
});
251264

0 commit comments

Comments
 (0)