Files
PaperClipAI/server/src/services/managed-ai-credential-writeback.ts
T
DottaandClaude Opus 5.5 aa85bcb518 feat(plugins): carry a Google sign-in to plugin Runners for Google Antigravity (#22933)
## 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 <noreply@anthropic.com>
2026-11-25 07:43:49 -06:00

184 lines
11 KiB
TypeScript

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 { 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";
import { decideGrokAuthMerge, parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server";
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<typeof managedAiCredentialWritebackBindingSchema>;
/** Credential ownership survives the invocation home; reconnects and revocations win. */
export async function syncManagedAiCredentials(
db: Db,
companyId: string,
binding: ManagedAiCredentialWritebackBinding,
provider: "codex" | "grok",
fetchCredential: () => Promise<string | null>,
) {
managedAiCredentialWritebackBindingSchema.parse(binding);
const home = await mkdtemp(join(await realpath(tmpdir()), "paperclip-ai-credential-"));
try {
// Revocation or an explicit account replacement intentionally discards an old refresh.
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 !== (provider === "codex" ? "openai" : "xai") || ai.data.method !== "subscription") return null;
return { connection, grant };
};
const mutate = <T>(operation: (database: Db) => Promise<T>) => withAccountHomeSecretMutationLock(
undefined, companyId, () => db.transaction(tx => operation(tx as unknown as Db)),
);
const current = await mutate(account);
if (!current) return "binding_changed" as const;
// Do not hold database or account locks while the provider exports its credential.
const credential = await fetchCredential();
if (credential === null) return "no_credentials" as const;
// A partial provider write must replay, not be acknowledged as unchanged.
let usable = false;
if (provider === "codex") usable = readSubscriptionAccountId(Buffer.from(credential)) !== null;
else {
try {
const parsed = parseGrokAuthPayload(JSON.parse(credential));
usable = parsed !== null && hasUsableGrokAuthValue(parsed.value);
} catch { /* Do not expose credential bytes through JSON parser errors. */ }
}
if (!usable) throw new Error("Managed credential snapshot invalid");
const incoming = join(home, "incoming.json"), destination = join(home, "current.json");
await writeFile(incoming, credential, { mode: 0o600 });
const writeBack = () => mutate(async database => {
const selected = await account(database);
if (!selected) return "binding_changed" as const;
const value = await aiConnectionService(database).credential(selected);
await writeFile(destination, value, { mode: 0o600 });
if (await (provider === "codex" ? decideCodexAuthMerge : decideGrokAuthMerge)(incoming, destination, { errorLabel: "AI account refresh" }) !== 10) return "unchanged" as const;
await secretService(database).rotate(binding.secretId, {
value: credential, preserveAiSessionEpoch: true,
}, { userId: selected.grant.subjectUserId });
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;
}
}
} finally {
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<string | null>,
) {
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 = <T>(operation: (database: Db) => Promise<T>) => 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;
}
}
}