Skip to content

Commit d4ad866

Browse files
fuller-stack-devJason Sy
andauthored
fix(github-copilot): protect device-login tokens (#133033)
Co-authored-by: Jason Sy <[email protected]>
1 parent 312f016 commit d4ad866

15 files changed

Lines changed: 630 additions & 40 deletions

‎docs/plugins/sdk-provider-plugins.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,32 @@ catalog, API-key auth, and dynamic model resolution.
206206
`openclaw onboard --acme-ai-api-key <key>` and select
207207
`acme-ai/acme-large` as their model.
208208

209+
A custom interactive auth method that mints a static token or API key can
210+
request protected persistence on its returned profile:
211+
212+
```typescript
213+
return {
214+
profiles: [
215+
{
216+
profileId: "acme-ai:device",
217+
credential: { type: "token", provider: "acme-ai", token },
218+
secretStorage: {
219+
kind: "store",
220+
namePrefix: "ACME_AI_TOKEN",
221+
},
222+
},
223+
],
224+
};
225+
```
226+
227+
OpenClaw keeps the inline value only while staged validation runs. At the
228+
final persistence boundary it writes the value to the protected local store
229+
and saves a `tokenRef` or `keyRef` in the auth profile. `namePrefix` must be
230+
an uppercase environment-style name. OpenClaw adds a stable suffix derived
231+
from the provider and final profile id so multiple profiles remain separate.
232+
Use this only for provider-minted static credentials, not rotating OAuth
233+
credentials or values already supplied as SecretRefs.
234+
209235
### Live model discovery
210236

211237
If your provider exposes an OpenAI-compatible `/models` API, opt the

‎docs/providers/github-copilot.md‎

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ provider or agent runtime in three different ways.
1515

1616
<Tabs>
1717
<Tab title="Built-in provider (github-copilot)">
18-
Use the native device-login flow to obtain and store a GitHub token. When
19-
OpenClaw runs, it validates Copilot access and resolves the account-specific
20-
Copilot API endpoint. This is the **default** and simplest path because it does
21-
not require VS Code.
18+
Use the native device-login flow to obtain a GitHub token. By default,
19+
OpenClaw puts the token in its protected local secret store and saves only a
20+
`tokenRef` in the auth profile. When OpenClaw runs, it validates Copilot access
21+
and resolves the account-specific Copilot API endpoint. This is the **default**
22+
and simplest path because it does not require VS Code.
2223

2324
<Steps>
2425
<Step title="Run the login command">
@@ -322,16 +323,28 @@ configured default model is never replaced.
322323
| 3 | `GITHUB_TOKEN` | Standard GitHub token (lowest) |
323324

324325
When multiple variables are set, OpenClaw uses the highest-priority one.
325-
The device-login flow (`openclaw models auth login-github-copilot`) stores
326-
its token in the auth profile store and takes precedence over all environment
327-
variables.
326+
The device-login flow (`openclaw models auth login-github-copilot`) stores a
327+
protected-store `tokenRef` in the auth profile and takes precedence over all
328+
environment variables.
328329

329330
</Accordion>
330331

331332
<Accordion title="Token storage">
332-
The login stores a GitHub token in the auth profile store (profile id
333-
`github-copilot:github`). At runtime, OpenClaw validates Copilot access,
334-
resolves the account-specific API endpoint, and uses the stored GitHub token
333+
By default, device login stores the GitHub token in OpenClaw's protected local
334+
secret store and writes only a `tokenRef` to the auth profile (profile id
335+
`github-copilot:github`). The built-in store does not require a configured
336+
external secret provider. If OpenClaw cannot write the store, login stops
337+
before replacing the auth profile and reports that the state-directory or
338+
database permissions need repair.
339+
340+
Interactive onboarding honors an explicit `--secret-input-mode plaintext`
341+
choice for compatibility. That mode stores the token inline, reports the
342+
choice, and remains visible to `openclaw secrets audit --check`.
343+
344+
The protected store is write-only through OpenClaw's user-facing secret APIs,
345+
but it is not encrypted at rest; its SQLite file relies on state-directory
346+
permissions. At runtime, OpenClaw resolves the reference, validates Copilot
347+
access, resolves the account-specific API endpoint, and uses the GitHub token
335348
for Copilot requests. You do not need to manage runtime authentication
336349
manually.
337350

‎extensions/github-copilot/index.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1397,6 +1397,10 @@ describe("github-copilot plugin", () => {
13971397
provider: "github-copilot",
13981398
token: "refreshed-token",
13991399
});
1400+
expect(result.profiles[0]?.secretStorage).toBeUndefined();
1401+
expect(result.notes).toContain(
1402+
"Plaintext secret input mode was selected, so the GitHub Copilot token will remain inline in the auth profile and openclaw secrets audit --check will report it.",
1403+
);
14001404
} finally {
14011405
vi.unstubAllGlobals();
14021406
if (isTtyDescriptor) {
@@ -1488,7 +1492,6 @@ describe("github-copilot plugin", () => {
14881492
prompter,
14891493
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
14901494
opts: {},
1491-
secretInputMode: "plaintext",
14921495
allowSecretRefPrompt: false,
14931496
isRemote: false,
14941497
openUrl,
@@ -1507,6 +1510,10 @@ describe("github-copilot plugin", () => {
15071510
provider: "github-copilot",
15081511
token: "public-fresh-token",
15091512
});
1513+
expect(result.profiles[0]?.secretStorage).toEqual({
1514+
kind: "store",
1515+
namePrefix: "GITHUB_COPILOT_TOKEN",
1516+
});
15101517
const params = (
15111518
result.configPatch as {
15121519
models?: { providers?: Record<string, { params?: Record<string, unknown> }> };
@@ -1544,7 +1551,6 @@ describe("github-copilot plugin", () => {
15441551
prompter,
15451552
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
15461553
opts: {},
1547-
secretInputMode: "plaintext",
15481554
allowSecretRefPrompt: false,
15491555
isRemote: false,
15501556
openUrl,
@@ -1562,6 +1568,10 @@ describe("github-copilot plugin", () => {
15621568
provider: "github-copilot",
15631569
token: "tenant-fresh-token",
15641570
});
1571+
expect(result.profiles[0]?.secretStorage).toEqual({
1572+
kind: "store",
1573+
namePrefix: "GITHUB_COPILOT_TOKEN",
1574+
});
15651575
const params = (
15661576
result.configPatch as {
15671577
models?: { providers?: Record<string, { params?: Record<string, unknown> }> };

‎extensions/github-copilot/index.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ const COPILOT_ENV_VARS: [string, string, string] = [
4949
"GITHUB_TOKEN",
5050
];
5151
const DEFAULT_COPILOT_PROFILE_ID = "github-copilot:github";
52+
const COPILOT_SECRET_STORE_NAME_PREFIX = "GITHUB_COPILOT_TOKEN";
5253

5354
type GithubCopilotPluginConfig = {
5455
discovery?: {
@@ -605,6 +606,15 @@ export default definePluginEntry({
605606
githubToken: result.accessToken,
606607
githubDomain: normalizedDomain,
607608
});
609+
const persistInline = ctx.secretInputMode === "plaintext";
610+
const notes = [
611+
...(starter.notes ?? []),
612+
...(persistInline
613+
? [
614+
"Plaintext secret input mode was selected, so the GitHub Copilot token will remain inline in the auth profile and openclaw secrets audit --check will report it.",
615+
]
616+
: []),
617+
];
608618
return {
609619
profiles: [
610620
{
@@ -614,9 +624,18 @@ export default definePluginEntry({
614624
provider: PROVIDER_ID,
615625
token: result.accessToken,
616626
},
627+
...(!persistInline
628+
? {
629+
secretStorage: {
630+
kind: "store" as const,
631+
namePrefix: COPILOT_SECRET_STORE_NAME_PREFIX,
632+
},
633+
}
634+
: {}),
617635
},
618636
],
619-
...starter,
637+
...(starter.defaultModel ? { defaultModel: starter.defaultModel } : {}),
638+
...(notes.length > 0 ? { notes } : {}),
620639
...(configPatch ? { configPatch } : {}),
621640
};
622641
}

‎src/commands/agents.commands.add.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import {
1717
import {
1818
buildPortableAuthProfileStoreForAgentCopy,
1919
ensureAuthProfileStore,
20-
persistAuthProfileBatch,
2120
type AuthProfileStore,
2221
} from "../agents/auth-profiles.js";
2322
import { AuthProfileStoreUnreadableError } from "../agents/auth-profiles/legacy-source-diagnostic.js";
@@ -38,6 +37,8 @@ import {
3837
transformConfigWithPendingPluginInstalls,
3938
} from "../plugins/install-record-commit.js";
4039
import { withPluginLifecycleLease } from "../plugins/plugin-lifecycle-lease.js";
40+
import { persistProviderAuthProfileBatch } from "../plugins/provider-auth-persistence.js";
41+
import type { ProviderAuthProfile } from "../plugins/types.js";
4142
import { normalizeAgentId } from "../routing/session-key.js";
4243
import { defaultRuntime, type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
4344
import { resolveUserPath, shortenHomePath } from "../utils.js";
@@ -285,9 +286,7 @@ export async function agentsAddCommand(
285286
workspace: workspaceDir,
286287
agentDir,
287288
});
288-
const stagedAuthProfiles: Array<
289-
Parameters<typeof persistAuthProfileBatch>[0]["profiles"][number]
290-
> = [];
289+
const stagedAuthProfiles: Array<ProviderAuthProfile & { replaceExisting?: boolean }> = [];
291290
let stagedAuthOrder: AuthProfileStore["order"];
292291
let reportPortableAuthCopy: (() => Promise<void>) | undefined;
293292

@@ -484,6 +483,7 @@ export async function agentsAddCommand(
484483
profiles: stagedAuthProfiles,
485484
...(stagedAuthOrder ? { order: stagedAuthOrder } : {}),
486485
agentDir,
486+
config: nextConfig,
487487
}
488488
: undefined;
489489

@@ -495,7 +495,7 @@ export async function agentsAddCommand(
495495
skipOptionalBootstrapFiles: nextConfig.agents?.defaults?.skipOptionalBootstrapFiles,
496496
});
497497
const authPersistence = stagedAuthBatch
498-
? await persistAuthProfileBatch(stagedAuthBatch)
498+
? await persistProviderAuthProfileBatch(stagedAuthBatch)
499499
: undefined;
500500
try {
501501
nextConfig = await channelSetup.commit(nextConfig, async (configToCommit) => {
@@ -528,7 +528,7 @@ export async function agentsAddCommand(
528528
...(stagedAuthBatch
529529
? {
530530
prepareConfigCommit: async () =>
531-
(await persistAuthProfileBatch(stagedAuthBatch)).rollback,
531+
(await persistProviderAuthProfileBatch(stagedAuthBatch)).rollback,
532532
}
533533
: {}),
534534
});

‎src/commands/models/auth.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ type UpsertAuthProfileCall = {
2525
agentDir?: string;
2626
credential?: {
2727
provider?: string;
28+
token?: string;
29+
tokenRef?: unknown;
2830
type?: string;
2931
};
3032
profileId?: string;
@@ -66,6 +68,18 @@ const mocks = vi.hoisted(() => ({
6668
callGateway: vi.fn(),
6769
resolvePluginSetupProviderCore: vi.fn(),
6870
resolvePluginSetupRegistry: vi.fn(),
71+
readSecretStoreValue: vi.fn(() => ({
72+
ok: false as const,
73+
error: { code: "SECRET_STORE_NOT_FOUND", message: "missing" },
74+
})),
75+
writeSecretStoreEntry: vi.fn(),
76+
deleteSecretStoreEntry: vi.fn(),
77+
}));
78+
79+
vi.mock("../../secrets/store/secret-store.js", () => ({
80+
readSecretStoreValue: mocks.readSecretStoreValue,
81+
writeSecretStoreEntry: mocks.writeSecretStoreEntry,
82+
deleteSecretStoreEntry: mocks.deleteSecretStoreEntry,
6983
}));
7084

7185
vi.mock("../../agents/auth-profiles/profiles.js", () => ({
@@ -484,6 +498,85 @@ describe("modelsAuthLoginCommand", () => {
484498
});
485499
});
486500

501+
it("persists a provider-minted Copilot token through the protected store", async () => {
502+
const runtime = createRuntime();
503+
runProviderAuth.mockResolvedValueOnce({
504+
profiles: [
505+
{
506+
profileId: "github-copilot:github",
507+
credential: {
508+
type: "token",
509+
provider: "github-copilot",
510+
token: "synthetic-device-token",
511+
},
512+
secretStorage: {
513+
kind: "store",
514+
namePrefix: "GITHUB_COPILOT_TOKEN",
515+
},
516+
},
517+
],
518+
});
519+
mocks.resolvePluginProvidersCore.mockReturnValue([
520+
createProvider({
521+
id: "github-copilot",
522+
label: "GitHub Copilot",
523+
run: runProviderAuth as ProviderPlugin["auth"][number]["run"],
524+
}),
525+
]);
526+
527+
await modelsAuthLoginCommand({ provider: "github-copilot" }, runtime);
528+
529+
expect(mocks.writeSecretStoreEntry).toHaveBeenCalledWith(
530+
expect.objectContaining({ value: "synthetic-device-token" }),
531+
);
532+
const upsertCall = readMockCallArg(
533+
mocks.upsertAuthProfileAfterLoginWithLock,
534+
) as UpsertAuthProfileCall;
535+
expect(upsertCall.credential).not.toHaveProperty("token");
536+
expect(upsertCall.credential?.tokenRef).toEqual({
537+
source: "store",
538+
provider: "default",
539+
id: expect.stringMatching(/^GITHUB_COPILOT_TOKEN_[A-F0-9]{24}$/),
540+
});
541+
});
542+
543+
it("keeps the prior auth profile when protected storage is unavailable", async () => {
544+
const runtime = createRuntime();
545+
runProviderAuth.mockResolvedValueOnce({
546+
profiles: [
547+
{
548+
profileId: "github-copilot:github",
549+
credential: {
550+
type: "token",
551+
provider: "github-copilot",
552+
token: "synthetic-device-token",
553+
},
554+
secretStorage: {
555+
kind: "store",
556+
namePrefix: "GITHUB_COPILOT_TOKEN",
557+
},
558+
},
559+
],
560+
});
561+
mocks.resolvePluginProvidersCore.mockReturnValue([
562+
createProvider({
563+
id: "github-copilot",
564+
label: "GitHub Copilot",
565+
run: runProviderAuth as ProviderPlugin["auth"][number]["run"],
566+
}),
567+
]);
568+
mocks.writeSecretStoreEntry.mockImplementationOnce(() => {
569+
throw new Error("read-only database");
570+
});
571+
572+
await expect(modelsAuthLoginCommand({ provider: "github-copilot" }, runtime)).rejects.toThrow(
573+
"Could not write the protected secret store",
574+
);
575+
576+
expect(mocks.upsertAuthProfileAfterLoginWithLock).not.toHaveBeenCalled();
577+
expect(mocks.promoteAuthProfileInOrder).not.toHaveBeenCalled();
578+
});
579+
487580
it("keeps login successful when the running gateway cannot refresh auth state", async () => {
488581
const runtime = createRuntime();
489582
mocks.callGateway.mockRejectedValueOnce(new Error("gateway unavailable"));

0 commit comments

Comments
 (0)