From aa85bcb5185fca52ce82a0edeff10d8a97e7eb95 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:43:49 -0600 Subject: [PATCH] feat(plugins): carry a Google sign-in to plugin Runners for Google Antigravity (#22933) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugin environments (for example, an agent computer) run agents as plugin Runner tasks. Core sends each task one typed credential, and gets refreshed sign-ins back through the task's `credentials` snapshot. > - #22930 let a Google Antigravity task carry a Gemini API key. A Google subscription sign-in was still refused with "Google sign-in is not supported." > - The Cloud rollout plan (#22923) needs both routes. This is gaps G3 and G4 and work item 2: deliver the sign-in, and save a rotated refresh token safely, as Codex does. > - This pull request sends the saved, sanitized sign-in as the `antigravity` `provider-env` credential under `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. It saves a refreshed token from the snapshot only after the generation, epoch and Google account checks. > - The benefit is that a plugin (for example, the Cloud agent computer) can run an Antigravity task with a person's Google sign-in, and token refreshes are not lost or saved to the wrong account. The picker, Test and save refusals for plugin targets (item 6) and the qualification flip (item 8) stay out of scope. ## Linked Issues or Issue Description Refs #22923 Refs #22930 **What problem does this solve?** A plugin Runner task cannot use a Google sign-in for Google Antigravity. Core refuses it at run start. There is also no path to save a refresh token that the Runner rotated on the plugin's computer. **Proposed solution** Add the sign-in variable as a second `antigravity` key set in `provider-env`. Core reads the sign-in from the run's private managed home, runs it through `sanitizeAntigravityCredential`, and sends that exact output. Core saves the write-back binding (grant, secret, session epoch, and a SHA-256 of the starting sign-in) on the lease. When the task stops, Core reads the snapshot and saves a new token only if all checks pass. **Alternatives considered** A new credential type for the sign-in. `provider-env` already has the exact-set check, the credential binding contract and the cross-check against the Runner's allowlists. The Cloud plan already describes the Launcher row as "`GEMINI_API_KEY` or the sign-in key". ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: the `antigravity` key sets are now `GEMINI_API_KEY` or `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. A mix of both stays rejected. - `server/src/services/native-runtime/plugin-runner-credentials.ts`: with no Gemini API key, Core reads `antigravity-acp/acp_token.json` from the selected managed home and sends the sanitizer's complete output (client ID, client secret, refresh token, token URI, `scopes`, and `project_id` when present). It never sends an access token or the account email. The task needs write-back authority. A sign-in supplied through the environment is refused. An unreadable or invalid saved sign-in fails with "The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry." No error contains credential text. - `server/src/services/ai-connection-runtime.ts`: a Google subscription run now returns a write-back binding with `google.credentialSha256` of the starting sign-in. - `server/src/services/managed-ai-credential-writeback.ts`: new `syncManagedAntigravityCredential`. It requires an active grant, the same secret reference and session epoch, a Google subscription connection, and a saved sign-in that still hashes to the starting generation. It verifies a changed token with the existing account check (`prepareAntigravityCredentialWriteback`) in a private temporary home, then rechecks all of the above under the account lock before it rotates the secret. It writes `ai_connection.credential_refreshed` on save. For a different account, or a connection with no saved account, it saves nothing, writes `ai_connection.credential_refresh_refused` with a plain reason, and settles as `account_refused`. - `server/src/services/plugin-task-credential-writeback.ts`: a handoff with a Google binding takes the snapshot's `provider-env` `antigravity` sign-in and uses the Google write-back. Codex is unchanged. - `server/src/services/native-runtime/native-session-executor.ts`: a sign-in credential needs a Google write-back binding, and a Codex credential needs a non-Google one. - `server/src/services/native-runtime/antigravity-runner-credentials.ts`: the account mismatch is a typed error. The message is unchanged. - Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and `doc/plugins/PLUGIN_RUNNER_EXECUTION.md` describe the sign-in credential, where the Runner stages it, and the snapshot that the plugin must return. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the changed SDK source. ## Verification - Red first: with the source changes removed, 22 of the new and updated tests failed (the refusal, no write-back binding, no Google write-back). - Green after the change: - `cd server && npx vitest run src/__tests__/antigravity-plugin-task-credential-writeback.test.ts` (11 passed, embedded PostgreSQL): delivery of the exact sanitized sign-in; same-account rotation saved and logged; a second rotation during the account check saved; a different account refused and recorded in plain words; unchanged token with no Google call; reconnect (new generation and epoch) and a revoked grant discard the write-back without an export; a Google outage keeps the handoff pending and the next cleanup saves it; Codex, API-key and invalid snapshots refused. No token, client secret or access token in lease metadata, activity rows or errors. - `cd server && npx vitest run src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/plugin-runner-credential-names.test.ts` (39 passed). The names test checks that the Runner forwards the sign-in variable to the sidecar and keeps it out of the provider process. - `cd packages/plugins/sdk && npx vitest run tests/environment-task-release-resume.test.ts tests/environment-tasks.test.ts` (104 passed) - `cd server && pnpm typecheck` (clean) - `pnpm verify` (see the CI run for broad coverage) - No live run, no Google login and no real token was used. All Google calls are fixtures. ## Risks - Low for current users. Plugin targets still refuse Antigravity in the picker, Test and save (item 6), so no existing agent reaches this path until item 6 merges. - The lease now stores a SHA-256 of the starting sign-in. It is a one-way digest of a high-entropy token, and it is the same kind of generation value that Core already derives for the local route. - If Google rotates the token during the account check and the database save then fails, the cleanup retries from the plugin's snapshot. Google does not normally rotate these refresh tokens, so this matches the local route's exposure without its recovery journal. - The Launcher must return the Runner's `auth-refresh.json` (or `acp_token.json` before lease close) in the snapshot. A Launcher that returns the starting sign-in only records `unchanged`, so no token is lost on the Core side, but a rotation on the computer would not be saved. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, test runs). Standard context window, extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md | 34 ++- doc/plugins/PLUGIN_RUNNER_EXECUTION.md | 11 +- packages/plugins/sdk/src/environment-tasks.ts | 2 +- .../environment-task-release-resume.test.ts | 2 +- ...y-plugin-task-credential-writeback.test.ts | 216 ++++++++++++++++++ .../plugin-runner-credential-names.test.ts | 7 +- server/src/services/ai-connection-runtime.ts | 5 + .../managed-ai-credential-writeback.ts | 93 +++++++- .../antigravity-runner-credentials.ts | 6 +- .../native-runtime/native-session-executor.ts | 5 +- .../plugin-runner-credentials.test.ts | 66 +++++- .../plugin-runner-credentials.ts | 18 +- .../plugin-task-credential-writeback.ts | 12 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 14 files changed, 447 insertions(+), 32 deletions(-) create mode 100644 server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index 69d7cdd7879..8c463eb0fef 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -87,7 +87,7 @@ other variable: | `grok` | `XAI_API_KEY` | | `copilot` | `COPILOT_GITHUB_TOKEN` | | `opencode` | `OPENROUTER_API_KEY`, or `PAPERCLIP_AI_PROVIDER_URL` with `PAPERCLIP_AI_PROVIDER_KEY` | -| `antigravity` | `GEMINI_API_KEY` | +| `antigravity` | `GEMINI_API_KEY`, or `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET` | `ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS` exports this list. A server test checks every set against the names that the Runner forwards to each provider. Every value @@ -109,8 +109,20 @@ binding. For `antigravity`, the Runner also removes every other `GOOGLE_*` and `GEMINI_*` variable before it starts the provider, so a configured variable cannot redirect the key. Core does not send a Grok subscription login. A Grok agent must use an xAI API -key in a plugin environment. Core does not send a Google sign-in yet. A Google -Antigravity agent must use a Gemini API key in a plugin environment. +key in a plugin environment. + +For a Google Antigravity agent bound to a Google sign-in, the +`antigravity` credential carries `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. +Its value is the saved sign-in as a JSON document: the client ID, client +secret, refresh token, token URI, the `scopes` list, and `project_id` when the +account has one. It never contains an access token or the account email. Set it +in the private environment of that task's Runner process only, and name it in +`PAPERCLIP_ACPX_CREDENTIAL_BINDING`. Never put it in a file, a log, a +configured environment, or the environment of another task. The Runner writes +it to `/antigravity-home/antigravity-acp/acp_token.json` (directory +0700, file 0600) and does not pass it to the provider process. When the provider +lease closes, the Runner writes the newest sign-in to `auth-refresh.json` in +the same directory and removes `acp_token.json`. See "Credential writeback". ## Configured environment @@ -494,9 +506,19 @@ cancellation prevented task admission. It must not mean that an export failed. Core saves the account grant, secret reference, and session epoch on the lease. It saves no credential bytes or temporary path in lease metadata. After process -termination, it can recover a Codex refresh even if Core restarted. It uses the -existing account comparison and secret service. A revoked grant, replaced -account, or changed session epoch discards the old refresh. +termination, it can recover a Codex or Google sign-in refresh even if Core +restarted. It uses the existing account comparison and secret service. A +revoked grant, replaced account, or changed session epoch discards the old +refresh. + +For a Google sign-in, `credentials` returns the same `provider-env` type with +`provider: "antigravity"` and only `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`, +set to the contents of the Runner's `auth-refresh.json` (or `acp_token.json` +if the lease has not closed). Core saves it only when the saved connection +still holds the exact sign-in that the task started with, and only after +Google confirms that the refreshed sign-in belongs to the connection's account. +A sign-in for another account is not saved; Core records that in the activity +log. Keep file synchronization and backup outside this API. The provider must retain recoverable credential state until task completion succeeds. diff --git a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md index 36ad51a7ad4..cf84492e020 100644 --- a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md +++ b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md @@ -102,12 +102,15 @@ reconciliation for the same task. ## Credentials and tools -Core can transfer a selected Codex account, a direct Claude credential, or the -API credential of a Grok, Copilot, OpenCode or Google Antigravity connection. See +Core can transfer a selected Codex account, a direct Claude credential, the +API credential of a Grok, Copilot, OpenCode or Google Antigravity connection, +or the Google sign-in of a Google Antigravity connection. See [typed credentials](PLUGIN_ENVIRONMENT_TASKS.md#typed-credentials). +Codex and Google sign-in refreshes come back through the `credentials` +snapshot. See [credential writeback](PLUGIN_ENVIRONMENT_TASKS.md#credential-writeback). Other managed routes fail closed until they have a typed credential contract. -A Grok subscription login, a Google sign-in, Claude provider routing, and an -OpenCode gateway without a key also fail closed. +A Grok subscription login, Claude provider routing, and an OpenCode gateway +without a key also fail closed. Do not put credentials in task metadata, journals, logs, or errors. Assigned MCP tools run through the Core gateway over PRP. diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index 5682dee1658..ebdf0950379 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -60,7 +60,7 @@ export const ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS = { grok: [["XAI_API_KEY"]], copilot: [["COPILOT_GITHUB_TOKEN"]], opencode: [["OPENROUTER_API_KEY"], ["PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_AI_PROVIDER_KEY"]], - antigravity: [["GEMINI_API_KEY"]], + antigravity: [["GEMINI_API_KEY"], ["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]], } as const satisfies Record; export type PluginEnvironmentTaskCredentialProvider = keyof typeof ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS; const providerNames = Object.keys(ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS) as [PluginEnvironmentTaskCredentialProvider, ...PluginEnvironmentTaskCredentialProvider[]]; diff --git a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts index a70ca44cf98..5f8b4610b1b 100644 --- a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts +++ b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts @@ -57,7 +57,7 @@ const credentials: [string, unknown, boolean][] = [ ["an extra provider credential field", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai" }, home: "/home/agent" }, false], ["a Gemini API key for Antigravity", { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }, true], ["an Antigravity sign-in document", { type: "provider-env", provider: "antigravity", - environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture\"}" } }, false], + environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture\"}" } }, true], ["a Gemini API key mixed with a sign-in document", { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture\"}" } }, false], ["a Google API key for Antigravity", { type: "provider-env", provider: "antigravity", environment: { GOOGLE_API_KEY: "fixture-google" } }, false], diff --git a/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts new file mode 100644 index 00000000000..9c59b806358 --- /dev/null +++ b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts @@ -0,0 +1,216 @@ +import { createHash, randomUUID } from "node:crypto"; +import { mkdtemp, realpath, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { and, eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, agents, companies, companyMemberships, connectionGrants, createDb, environmentLeases, environments, heartbeatRuns, plugins, toolConnections, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { aiConnectionService } from "../services/ai-connections.js"; +import { prepareManagedAiRuntime } from "../services/ai-connection-runtime.js"; +import { registerPluginTaskCredentialHandoff } from "../services/plugin-task-credential-writeback.js"; +import { settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js"; +import { secretService } from "../services/secrets.js"; +import { preparePluginRunnerCredentials } from "../services/native-runtime/plugin-runner-credentials.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; + +vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: async () => {} })); +const secretRead = vi.hoisted(() => ({ fail: false })); +vi.mock("../services/ai-connections.js", async importOriginal => { + const actual = await importOriginal(); + return { ...actual, aiConnectionService: (database: Parameters[0]) => { + const service = actual.aiConnectionService(database); + return { ...service, credential: (async (...args: Parameters) => { + if (secretRead.fail) throw new Error("fixture secret store unavailable"); + return service.credential(...args); + }) as typeof service.credential }; + } }; +}); +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; +const SIGN_IN = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"; +const signIn = (token: string, extra: Record = {}) => JSON.stringify({ + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", client_secret: "fixture-client-secret", + refresh_token: token, token_uri: "https://oauth2.googleapis.com/token", + scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], + ...extra, +}); +const google = { email: "alice@example.test", rotate: undefined as string | undefined, fail: false, calls: 0 }; +function stubGoogle() { + vi.stubGlobal("fetch", vi.fn(async (url: string) => { + google.calls++; + if (google.fail) throw new Error("fixture Google outage"); + return Response.json(url.includes("userinfo") ? { email_verified: true, email: google.email } + : { access_token: "fixture-access", token_type: "Bearer", ...(google.rotate ? { refresh_token: google.rotate } : {}) }); + })); +} + +suite("Google sign-in task credential writeback for plugin Runners", () => { + let database: Awaited>, db: ReturnType, home: string; + beforeAll(async () => { + home = await realpath(await mkdtemp(join(tmpdir(), "antigravity-plugin-task-"))); + vi.stubEnv("PAPERCLIP_HOME", home); vi.stubEnv("PAPERCLIP_INSTANCE_ID", "antigravity-plugin-task-fixture"); + database = await startEmbeddedPostgresTestDatabase("antigravity-plugin-task-"); db = createDb(database.connectionString); + }, 90_000); + afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); }); + afterEach(() => { vi.unstubAllGlobals(); secretRead.fail = false; Object.assign(google, { email: "alice@example.test", rotate: undefined, fail: false, calls: 0 }); }); + + async function fixture(saved = signIn("fixture-original", { project_id: "fixture-project" })) { + stubGoogle(); + const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), pluginId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID(); + const owner = `fixture-${randomUUID()}`; + await db.insert(companies).values({ id: companyId, name: "Google task credential fixture", issuePrefix: `G${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", adapterType: "paperclip_runner" }); + await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" }); + const service = aiConnectionService(db); + await service.save(companyId, owner, { provider: "google", method: "subscription", ownership: "personal", name: "Google fixture", + loginSessionId: "fixture", agentIds: [], allAgents: true }, saved, undefined, undefined, undefined, "alice@example.test"); + const managed = await prepareManagedAiRuntime(db, { companyId, agentId, responsibleUserId: owner, adapterType: "paperclip_runner", + binding: { mode: "responsible_user", provider: "google", method: "subscription" }, + config: { provider: "acpx", acpxAgent: "antigravity" } }); + const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: managed.identity, + accountIdentity: managed.sessionIdentity, home: join(managed.home!, "provider"), environment: managed.config.env as NodeJS.ProcessEnv }); + await db.insert(environments).values({ id: environmentId, name: `Fixture ${environmentId}`, driver: "plugin", status: "active", config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } }); + await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "fixture-tasks", version: "1.0.0", status: "ready", manifestJson: { + capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }], + } as never }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" }); + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, provider: `plugin:${pluginId}:tasks`, providerLeaseId: "fixture-task", status: "active", + metadata: { driver: "plugin", pluginId, driverKey: "tasks", runnerTaskLease: true, runnerTaskDispatched: true, runnerTaskExecutionStopped: false } }); + await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!); + await managed.cleanup(); + const calls: string[] = []; + let exported: unknown = { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: signIn("fixture-refreshed", { project_id: "fixture-project" }) } }; + let failExport = false; + const workers = { getWorker: () => ({ supportedMethods: ["environmentTask"] }), + call: async (_plugin: string, _method: string, params: any) => { + calls.push(params.operation.kind); + if (params.operation.kind === "status") return { kind: "status", taskId: "fixture-task", phase: "cancelled", executionStopped: true }; + if (params.operation.kind === "credentials") { + expect(params.operation.accountIdentity).toBe(managed.sessionIdentity); + if (failExport) throw new Error("fixture export unavailable"); + return { kind: "credentials", taskId: "fixture-task", credential: exported }; + } + return { kind: "accepted", taskId: "fixture-task" }; + } } as unknown as PluginWorkerManager; + const lease = () => db.select().from(environmentLeases).where(and(eq(environmentLeases.id, leaseId), eq(environmentLeases.companyId, companyId))).then(rows => rows[0]!); + const activity = () => db.select().from(activityLog).where(eq(activityLog.companyId, companyId)); + const credential = async () => { + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, managed.credentialWriteback!.grantId)); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, grant!.connectionId)); + return service.credential({ connection: connection!, grant: grant! }); + }; + return { companyId, owner, managed, transfer, calls, lease, activity, credential, + exportCredential(value: unknown) { exported = value; }, + failExport(value: boolean) { failExport = value; }, + settle: () => settleDispatchedEnvironmentTask(db, workers, { companyId, id: leaseId }) }; + } + const leaked = (text: string) => ["fixture-original", "fixture-refreshed", "fixture-rotated", "fixture-other", "fixture-client-secret", "fixture-access"] + .filter(secret => text.includes(secret)); + + it("delivers the sanitized saved sign-in and binds writeback to its exact generation", async () => { + const saved = signIn("fixture-original", { project_id: "fixture-project" }); + const f = await fixture(saved); + expect(f.transfer).toMatchObject({ needsWriteback: true, credential: { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: saved } } }); + expect(f.managed.credentialWriteback).toMatchObject({ google: { credentialSha256: createHash("sha256").update(saved).digest("hex") } }); + expect(leaked(JSON.stringify((await f.lease()).metadata))).toEqual([]); + }); + + it("saves a rotated refresh token for the same Google account and records it without the token", async () => { + const f = await fixture(); + expect(await f.settle()).toBe("completed"); + expect(f.calls).toEqual(["stop", "status", "credentials", "complete"]); + expect(await f.credential()).toBe(signIn("fixture-refreshed", { project_id: "fixture-project" })); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "rotated" }); + const activity = await f.activity(); + expect(activity.map(row => row.action)).toContain("ai_connection.credential_refreshed"); + expect(leaked(JSON.stringify(activity))).toEqual([]); + expect(leaked(JSON.stringify((await f.lease()).metadata))).toEqual([]); + }); + + it("saves the newest token when Google rotates it again during the account check", async () => { + const f = await fixture(); + google.rotate = "fixture-rotated"; + expect(await f.settle()).toBe("completed"); + expect(await f.credential()).toBe(signIn("fixture-rotated", { project_id: "fixture-project" })); + }); + + it("refuses a refresh from a different Google account and records why in plain words", async () => { + const f = await fixture(); + google.email = "mallory@example.test"; + f.exportCredential({ type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: signIn("fixture-other") } }); + expect(await f.settle()).toBe("completed"); + expect(await f.credential()).toBe(signIn("fixture-original", { project_id: "fixture-project" })); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "account_refused" }); + const refused = (await f.activity()).find(row => row.action === "ai_connection.credential_refresh_refused"); + expect(refused?.details).toMatchObject({ provider: "google", + reason: "The refreshed Google sign-in belongs to a different Google account than this connection, so it was not saved." }); + expect(leaked(JSON.stringify(await f.activity()))).toEqual([]); + expect(JSON.stringify(await f.activity())).not.toContain("mallory@example.test"); + }); + + it("does not call Google or rotate when the token is unchanged", async () => { + const f = await fixture(); + f.exportCredential({ type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: signIn("fixture-original", { project_id: "fixture-project" }) } }); + expect(await f.settle()).toBe("completed"); + expect(google.calls).toBe(0); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "unchanged" }); + }); + + it("discards a writeback from an older generation after reconnect, without exporting it", async () => { + const f = await fixture(); + await secretService(db).rotate(f.managed.credentialWriteback!.secretId, { value: signIn("fixture-reconnected") }, { userId: f.owner }); + expect(await f.settle()).toBe("completed"); + expect(f.calls).not.toContain("credentials"); + expect(await f.credential()).toBe(signIn("fixture-reconnected")); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "binding_changed" }); + }); + + it("discards a writeback after the connection is revoked", async () => { + const f = await fixture(); + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.managed.credentialWriteback!.grantId)); + expect(await f.settle()).toBe("completed"); + expect(f.calls).not.toContain("credentials"); + expect(google.calls).toBe(0); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "binding_changed" }); + }); + + it("keeps the handoff pending when Google cannot confirm the account, then saves on the next cleanup", async () => { + const f = await fixture(); + google.fail = true; + const failed = await f.settle().catch((error: Error) => error); + expect(failed).toBeInstanceOf(Error); + expect(leaked((failed as Error).message)).toEqual([]); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "pending" }); + expect(await f.credential()).toBe(signIn("fixture-original", { project_id: "fixture-project" })); + google.fail = false; + expect(await f.settle()).toBe("completed"); + expect(await f.credential()).toBe(signIn("fixture-refreshed", { project_id: "fixture-project" })); + }); + + it("keeps the handoff pending when the saved sign-in cannot be read, then saves on the next cleanup", async () => { + const f = await fixture(); + secretRead.fail = true; + const failed = await f.settle().catch((error: Error) => error).finally(() => { secretRead.fail = false; }); + expect(failed).toBeInstanceOf(Error); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "pending" }); + expect(await f.settle()).toBe("completed"); + expect(await f.credential()).toBe(signIn("fixture-refreshed", { project_id: "fixture-project" })); + }); + + it.each([ + ["a Codex credential", { type: "codex-auth-json", authJson: "{\"tokens\":{}}" }], + ["a Gemini API key", { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }], + ["an invalid sign-in", { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: "{\"refresh_token\":\"fixture-refreshed\"}" } }], + ])("refuses %s as a Google sign-in snapshot without saving or echoing it", async (_name, snapshot) => { + const f = await fixture(); + f.exportCredential(snapshot); + const failed = await f.settle().catch((error: Error) => error); + expect(failed).toBeInstanceOf(Error); + expect(leaked(String(failed))).toEqual([]); + expect(await f.credential()).toBe(signIn("fixture-original", { project_id: "fixture-project" })); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "pending" }); + }); +}); diff --git a/server/src/__tests__/plugin-runner-credential-names.test.ts b/server/src/__tests__/plugin-runner-credential-names.test.ts index c295f1eae9f..4248a57722e 100644 --- a/server/src/__tests__/plugin-runner-credential-names.test.ts +++ b/server/src/__tests__/plugin-runner-credential-names.test.ts @@ -23,6 +23,7 @@ describe("plugin Runner provider credential names", () => { expect(rustAcpxCredentialNames("copilot")).toContain("COPILOT_GITHUB_TOKEN"); expect(rustCandidateAgents).toContain("copilot"); expect(rustAcpxCredentialNames("antigravity")).toContain("GEMINI_API_KEY"); + expect(rustAcpxCredentialNames("antigravity")).toContain("PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"); expect(rustCandidateAgents).toContain("antigravity"); expect(rustOpenCodeNames).toContain("OPENROUTER_API_KEY"); }); @@ -47,7 +48,11 @@ describe("plugin Runner provider credential names", () => { expect(ACPX_CREDENTIAL_NAMES[agent], `${name} is an ACPX ${agent} credential`).toContain(name); expect(rustAcpxCredentialNames(agent), `${name} reaches the ACPX sidecar from the Runner process`).toContain(name); expect(host[name], `${name} survives sidecar admission`).toBe(environment[name]); - expect(spawned[name], `${name} reaches the ${agent} process`).toBe(environment[name]); + if (agent === "antigravity" && name === "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET") { + expect(spawned[name], `${name} is staged as a private token file, never the ${agent} process environment`).toBeUndefined(); + } else { + expect(spawned[name], `${name} reaches the ${agent} process`).toBe(environment[name]); + } } }); diff --git a/server/src/services/ai-connection-runtime.ts b/server/src/services/ai-connection-runtime.ts index 2a4c2991b69..00fa82be3bf 100644 --- a/server/src/services/ai-connection-runtime.ts +++ b/server/src/services/ai-connection-runtime.ts @@ -583,6 +583,11 @@ export async function prepareManagedAiRuntime( credentialWriteback: { grantId: selection.grant.id, secretId: credentialRef.secretId, sessionEpoch: freshness.epoch, versionSelector: credentialRef.versionSelector ?? "latest" } satisfies ManagedAiCredentialWritebackBinding, } : {}), + ...(antigravitySubscription && credentialRef && freshness ? { + credentialWriteback: { grantId: selection.grant.id, secretId: credentialRef.secretId, sessionEpoch: freshness.epoch, + versionSelector: credentialRef.versionSelector ?? "latest", + google: { credentialSha256: createHash("sha256").update(originalCredential, "utf8").digest("hex") } } satisfies ManagedAiCredentialWritebackBinding, + } : {}), config: { ...input.config, ...projected?.config, diff --git a/server/src/services/managed-ai-credential-writeback.ts b/server/src/services/managed-ai-credential-writeback.ts index bb6d926b25d..3d1afd3fe23 100644 --- a/server/src/services/managed-ai-credential-writeback.ts +++ b/server/src/services/managed-ai-credential-writeback.ts @@ -2,7 +2,8 @@ import { z } from "zod"; import { aiConnectionMetadataSchema } from "@paperclipai/shared"; import { and, eq } from "drizzle-orm"; import { companySecrets, connectionGrants, toolConnections, type Db } from "@paperclipai/db"; -import { mkdtemp, writeFile, rm, realpath } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, writeFile, rm, realpath } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { decideCodexAuthMerge, readSubscriptionAccountId, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; @@ -10,10 +11,14 @@ import { decideGrokAuthMerge, parseGrokAuthPayload, hasUsableGrokAuthValue } fro import { WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "@paperclipai/adapter-utils/workspace-restore-merge"; import { aiConnectionService } from "./ai-connections.js"; import { secretService } from "./secrets.js"; +import { logActivity } from "./activity-log.js"; +import { sanitizeAntigravityCredential } from "../vendor/paperclip-runner/index.js"; +import { AntigravityAccountMismatchError, prepareAntigravityCredentialWriteback } from "./native-runtime/antigravity-runner-credentials.js"; export const managedAiCredentialWritebackBindingSchema = z.object({ grantId: z.string().uuid(), secretId: z.string().uuid(), sessionEpoch: z.number().int().nonnegative(), versionSelector: z.union([z.literal("latest"), z.number().int().positive()]), + google: z.object({ credentialSha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict().optional(), }).strict(); export type ManagedAiCredentialWritebackBinding = z.infer; @@ -90,3 +95,89 @@ export async function syncManagedAiCredentials( await rm(home, { recursive: true, force: true }); } } + +export function antigravityCredentialSha256(credential: string): string { + return createHash("sha256").update(sanitizeAntigravityCredential(credential), "utf8").digest("hex"); +} + +/** Only the selected Google generation may replace itself, and only with a proven same-account refresh. */ +export async function syncManagedAntigravityCredential( + db: Db, + companyId: string, + binding: ManagedAiCredentialWritebackBinding, + fetchCredential: () => Promise, +) { + const base = managedAiCredentialWritebackBindingSchema.parse(binding).google?.credentialSha256; + if (!base) throw new Error("Managed credential binding is not a Google sign-in"); + const account = async (database: Db) => { + const [grant] = await database.select().from(connectionGrants).where(and( + eq(connectionGrants.companyId, companyId), eq(connectionGrants.id, binding.grantId), + )).for("update"); + if (!grant || grant.status !== "active") return null; + const ref = grant.credentialSecretRefs.find(ref => ref.configPath === "ai.credential"); + if (!ref || ref.secretId !== binding.secretId || (ref.versionSelector ?? "latest") !== binding.versionSelector) return null; + const [secret] = await database.select().from(companySecrets).where(and( + eq(companySecrets.companyId, companyId), eq(companySecrets.id, binding.secretId), + )).for("update"); + if (!secret || secret.aiSessionEpoch !== binding.sessionEpoch) return null; + const [connection] = await database.select().from(toolConnections).where(and( + eq(toolConnections.companyId, companyId), eq(toolConnections.id, grant.connectionId), + )); + const ai = aiConnectionMetadataSchema.safeParse(connection?.config.ai); + if (!connection || !ai.success || ai.data.provider !== "google" || ai.data.method !== "subscription") return null; + const saved = await aiConnectionService(database).credential({ connection, grant }); + let stored: string; + try { stored = sanitizeAntigravityCredential(saved); } + catch { return null; } + if (createHash("sha256").update(stored, "utf8").digest("hex") !== base) return null; + return { connection, grant, stored }; + }; + const mutate = (operation: (database: Db) => Promise) => withAccountHomeSecretMutationLock( + undefined, companyId, () => db.transaction(tx => operation(tx as unknown as Db)), + ); + const current = await mutate(account); + if (!current) return "binding_changed" as const; + const credential = await fetchCredential(); + if (credential === null) return "no_credentials" as const; + let incoming: string; + try { incoming = sanitizeAntigravityCredential(credential); } + catch { throw new Error("Managed credential snapshot invalid"); } + if (incoming === current.stored) return "unchanged" as const; + const accountEmail = current.grant.providerTenant?.name; + const refuse = async (reason: string) => { + await mutate(database => logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh", + action: "ai_connection.credential_refresh_refused", entityType: "tool_connection", entityId: current.connection.id, + details: { provider: "google", grantId: current.grant.id, reason } })); + return "account_refused" as const; + }; + if (!accountEmail) return refuse("This Google connection has no saved account to compare the refreshed sign-in with, so it was not saved. Reconnect the Google account."); + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-google-writeback-"))); + let verified: string; + try { + await mkdir(join(home, "antigravity-acp"), { mode: 0o700 }); + await writeFile(join(home, "antigravity-acp", "acp_token.json"), incoming, { flag: "wx", mode: 0o600 }); + verified = await prepareAntigravityCredentialWriteback({ originalCredential: current.stored, refreshedCredential: incoming, managedHome: home, accountEmail }); + } catch (error) { + if (!(error instanceof AntigravityAccountMismatchError)) throw error; + return refuse("The refreshed Google sign-in belongs to a different Google account than this connection, so it was not saved."); + } finally { + await rm(home, { recursive: true, force: true }); + } + const writeBack = () => mutate(async database => { + const selected = await account(database); + if (!selected || selected.grant.providerTenant?.name?.toLowerCase() !== accountEmail.toLowerCase()) return "binding_changed" as const; + if (verified === selected.stored) return "unchanged" as const; + await secretService(database).rotate(binding.secretId, { value: verified, preserveAiSessionEpoch: true }, { userId: selected.grant.subjectUserId }); + await logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh", + action: "ai_connection.credential_refreshed", entityType: "tool_connection", entityId: selected.connection.id, + details: { provider: "google", grantId: selected.grant.id } }); + return "rotated" as const; + }); + for (let attempt = 0; ; attempt++) { + try { + return await writeBack(); + } catch (error) { + if (attempt >= 2 || (error as NodeJS.ErrnoException)?.code !== WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) throw error; + } + } +} diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.ts b/server/src/services/native-runtime/antigravity-runner-credentials.ts index 33775d56244..81b23ce5ef6 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.ts @@ -94,6 +94,10 @@ export async function prepareAntigravityRunnerCredentials(input: { return { environment, home, credential }; } +export class AntigravityAccountMismatchError extends Error { + constructor() { super("The refreshed Google account does not match the selected connection."); } +} + /** A changed refresh token must prove the same saved Google identity before * the connection owner may apply its generation-checked encrypted writeback. */ export async function prepareAntigravityCredentialWriteback(input: { @@ -109,7 +113,7 @@ export async function prepareAntigravityCredentialWriteback(input: { if (!input.accountEmail) throw new Error("The Google account identity is unavailable for credential refresh. Reconnect the account."); const verified = await verifyAntigravityCredential(input.managedHome); if (verified.accountEmail.toLowerCase() !== input.accountEmail.toLowerCase()) { - throw new Error("The refreshed Google account does not match the selected connection."); + throw new AntigravityAccountMismatchError(); } return verified.credential; } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 70dff79fb69..3d940a64500 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -16994,7 +16994,10 @@ async function createRunnerdBackendWithinSessionClaim( identity: input.managedAiCredentialIdentity, accountIdentity: input.managedAiAccountIdentity, home: input.managedAiCredentialHome, environment: input.runnerEnvironment ?? {}, }); - if (credentials.needsWriteback && !input.managedAiCredentialWriteback) throw new Error("Plugin Runner credential writeback authority unavailable"); + if (credentials.needsWriteback && (!input.managedAiCredentialWriteback + || (credentials.credential?.type === "provider-env") !== Boolean(input.managedAiCredentialWriteback.google))) { + throw new Error("Plugin Runner credential writeback authority unavailable"); + } // Same-lease recovery already has a writeback binding. A portable move creates a new lease. if ((!adopting || input.remoteWarmRecovery?.portableSourceTaskId) && input.managedAiCredentialWriteback && credentials.accountIdentity) { if (!remoteTarget.leaseId) throw new Error("Plugin Runner credential lease unavailable"); diff --git a/server/src/services/native-runtime/plugin-runner-credentials.test.ts b/server/src/services/native-runtime/plugin-runner-credentials.test.ts index 19c68e36b61..819229b7bd0 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.test.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, writeFile, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -41,7 +41,20 @@ describe("plugin Runner selected credentials", () => { }); describe("plugin Runner Google Antigravity credentials", () => { - const signIn = "{\"refresh_token\":\"fixture-refresh\"}"; + const signIn = (extra: Record = {}) => JSON.stringify({ + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", client_secret: "fixture-client-secret", + refresh_token: "fixture-refresh", token_uri: "https://oauth2.googleapis.com/token", + scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], + ...extra, + }); + async function googleHome(contents: string) { + const directory = await mkdtemp(join(tmpdir(), "plugin-runner-google-")); homes.push(directory); + await mkdir(join(directory, "antigravity-acp"), { mode: 0o700 }); + await writeFile(join(directory, "antigravity-acp", "acp_token.json"), contents, { mode: 0o600 }); + return directory; + } + const blankManagedEnvironment = { GEMINI_API_KEY: "", GOOGLE_API_KEY: "", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "", + GEMINI_HOME: "/controller/private/provider", HOME: "/controller/private", OTHER_SECRET: "fixture-unrelated" }; it("transfers only the selected Gemini API key", async () => { const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", accountIdentity: "account", environment: { GEMINI_API_KEY: "fixture-gemini", GOOGLE_API_KEY: "fixture-google", GOOGLE_APPLICATION_CREDENTIALS: "/controller/private/adc.json", @@ -52,15 +65,48 @@ describe("plugin Runner Google Antigravity credentials", () => { expect(transfer.onCredentials).toBeUndefined(); }); it.each([ - ["a Google sign-in", { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: signIn }], - ["a Google sign-in beside a Gemini API key", { GEMINI_API_KEY: "fixture-gemini", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: signIn }], - ["no key", {}], - ["an empty key", { GEMINI_API_KEY: "" }], - ["a blank key", { GEMINI_API_KEY: " " }], - ["only a Google API key", { GOOGLE_API_KEY: "fixture-google" }], - ] as const)("refuses %s because only a Gemini API key can be transferred", async (_name, environment) => { + ["the required scopes", signIn()], + ["the optional project and OpenID scope", signIn({ project_id: "fixture-project", + scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode", "openid"] })], + ])("transfers the saved Google sign-in with %s exactly as the sanitizer outputs it", async (_name, saved) => { + const directory = await googleHome(JSON.stringify({ ...JSON.parse(saved), access_token: "fixture-access", expiry: "2020-01-01T00:00:00Z", email: "alice@example.test" })); + const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", accountIdentity: "account", + home: directory, environment: blankManagedEnvironment }); + expect(transfer).toEqual({ accountIdentity: "account", needsWriteback: true, + credential: { type: "provider-env", provider: "antigravity", environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: saved } } }); + const delivered = transfer.credential!.type === "provider-env" ? transfer.credential!.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET : ""; + expect(delivered).not.toContain("fixture-access"); + expect(delivered).not.toContain("alice@example.test"); + expect(transfer.onCredentials).toBeUndefined(); + }); + it("prefers a selected Gemini API key over a managed home", async () => { + const directory = await googleHome(signIn()); + const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", home: directory, + environment: { ...blankManagedEnvironment, GEMINI_API_KEY: "fixture-gemini" } }); + expect(transfer.credential).toEqual({ type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }); + expect(transfer.needsWriteback).toBeUndefined(); + }); + it.each([ + ["a sign-in supplied through the environment", { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture-refresh\"}" }, "selected credential unavailable"], + ["a sign-in beside a Gemini API key", { GEMINI_API_KEY: "fixture-gemini", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture-refresh\"}" }, "selected credential unavailable"], + ["no key and no saved sign-in", {}, "Gemini API key or a saved Google sign-in"], + ["a blank key and no saved sign-in", { GEMINI_API_KEY: " " }, "Gemini API key or a saved Google sign-in"], + ["only a Google API key", { GOOGLE_API_KEY: "fixture-google" }, "Gemini API key or a saved Google sign-in"], + ] as const)("refuses %s", async (_name, environment, message) => { const result = preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", environment }); - await expect(result).rejects.toThrow("Google Antigravity only with a Gemini API key"); + await expect(result).rejects.toThrow(message); + await result.catch((error: Error) => expect(error.message).not.toContain("fixture")); + }); + it.each([ + ["a missing token file", null], + ["a token for another OAuth client", JSON.stringify({ ...JSON.parse(signIn()), client_id: "fixture-other-client" })], + ["a token without the required scopes", JSON.stringify({ ...JSON.parse(signIn()), scopes: [] })], + ["unreadable JSON", "{fixture-refresh"], + ])("refuses %s in plain words without echoing it", async (_name, contents) => { + const directory = contents === null ? await mkdtemp(join(tmpdir(), "plugin-runner-google-")) : await googleHome(contents); + if (contents === null) homes.push(directory); + const result = preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", home: directory, environment: blankManagedEnvironment }); + await expect(result).rejects.toThrow("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry."); await result.catch((error: Error) => expect(error.message).not.toContain("fixture")); }); it("fails closed for an invalid Gemini API key without echoing it", async () => { diff --git a/server/src/services/native-runtime/plugin-runner-credentials.ts b/server/src/services/native-runtime/plugin-runner-credentials.ts index 5c8b558b682..13e5da840b7 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.ts @@ -6,6 +6,7 @@ import { type PluginEnvironmentTaskCredential, type PluginEnvironmentTaskCredentialProvider, } from "@paperclipai/plugin-sdk"; import { readLocalAiCredentialFile } from "../local-ai-credential-file.js"; +import { sanitizeAntigravityCredential } from "../../vendor/paperclip-runner/index.js"; const ANTIGRAVITY_SIGN_IN_ENV = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"; @@ -59,10 +60,21 @@ export async function preparePluginRunnerCredentials(input: { if (input.environment.XAI_BASE_URL) throw new Error("Plugin Runner does not support the selected provider routing"); if (!input.environment.XAI_API_KEY) throw new Error("Plugin Runner supports Grok only with an xAI API key. Grok subscription login is not supported."); } - if (provider === "antigravity" && (input.environment[ANTIGRAVITY_SIGN_IN_ENV] || !input.environment.GEMINI_API_KEY?.trim())) { - throw new Error("Plugin Runner supports Google Antigravity only with a Gemini API key. Google sign-in is not supported."); + if (provider === "antigravity") { + if (input.environment[ANTIGRAVITY_SIGN_IN_ENV]?.trim()) throw new Error("Plugin Runner selected credential unavailable"); + if (!input.environment.GEMINI_API_KEY?.trim()) { + if (!input.home) throw new Error("Google Antigravity needs a Gemini API key or a saved Google sign-in."); + let authJson: string; + try { + authJson = sanitizeAntigravityCredential(await readLocalAiCredentialFile(join(await realpath(input.home), "antigravity-acp", "acp_token.json"))); + } catch { + throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry."); + } + const credential = environmentTaskCredentialSchema.parse({ type: "provider-env", provider, environment: { [ANTIGRAVITY_SIGN_IN_ENV]: authJson } }); + return { ...github, accountIdentity, credential, needsWriteback: true }; + } } - const names = new Set(ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[provider].flat()); + const names = new Set(provider === "antigravity" ? ["GEMINI_API_KEY"] : ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[provider].flat()); const environment = Object.fromEntries([...names] .flatMap(key => input.environment[key] ? [[key, input.environment[key]]] : [])); const credential = environmentTaskCredentialSchema.safeParse({ type: "provider-env", provider, environment }); diff --git a/server/src/services/plugin-task-credential-writeback.ts b/server/src/services/plugin-task-credential-writeback.ts index a431f307d86..6cae4464f9d 100644 --- a/server/src/services/plugin-task-credential-writeback.ts +++ b/server/src/services/plugin-task-credential-writeback.ts @@ -2,13 +2,13 @@ import { and, eq, sql } from "drizzle-orm"; import { environmentLeases, type Db } from "@paperclipai/db"; import { z, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk"; import { isDeepStrictEqual } from "node:util"; -import { managedAiCredentialWritebackBindingSchema, syncManagedAiCredentials, type ManagedAiCredentialWritebackBinding } from "./managed-ai-credential-writeback.js"; +import { managedAiCredentialWritebackBindingSchema, syncManagedAiCredentials, syncManagedAntigravityCredential, type ManagedAiCredentialWritebackBinding } from "./managed-ai-credential-writeback.js"; const handoffSchema = z.object({ accountIdentity: z.string().min(1), binding: managedAiCredentialWritebackBindingSchema, state: z.enum(["pending", "complete"]), - outcome: z.enum(["rotated", "unchanged", "binding_changed", "not_dispatched", "no_credentials"]).optional(), + outcome: z.enum(["rotated", "unchanged", "binding_changed", "not_dispatched", "no_credentials", "account_refused"]).optional(), }).strict(); const key = "runnerTaskCredentialHandoff"; type Scope = { companyId: string; leaseId: string; expectedTaskId?: string }; @@ -73,6 +73,14 @@ async function writeBackCredentials( handoff: z.infer, fetchCredential: (accountIdentity: string) => Promise, ) { + if (handoff.binding.google) return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => { + const credential = await fetchCredential(handoff.accountIdentity); + if (credential === null) return null; + const value = credential.type === "provider-env" && credential.provider === "antigravity" + ? credential.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET : undefined; + if (!value) throw new Error("Plugin task credential provider mismatch"); + return value; + }); return syncManagedAiCredentials(db, companyId, handoff.binding, "codex", async () => { const credential = await fetchCredential(handoff.accountIdentity); if (credential === null) return null; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 26223cabb39..562cdc0d041 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,7 +13,7 @@ "packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb", "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", - "packages/plugins/sdk/src/environment-tasks.ts": "5682dee1658ad44f61f8480ef22a3a8e80eedf8f", + "packages/plugins/sdk/src/environment-tasks.ts": "ebdf0950379645dda416300acaa65718daf2795e", "packages/plugins/sdk/src/host-client-factory.ts": "e0301c390ea13f2340b669383f07af2455e48c8a", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f",