Files
PaperClipAI/server/src/services/native-runtime/antigravity-runner-credentials.ts
T
Nicky LeachandPaperclip 9092b0c667 Support live Antigravity credential writeback for both token stores (#23397)
## Thinking Path

> - Paperclip manages the connections agents use to work.
> - A run can outlive the Google refresh token that started it.
> - Antigravity writes a rotated token to a private file. Its two
runtimes use different paths and JSON layouts.
> - The task already records which connection supplied its sign-in.
> - Runner reports a rotation on PRP. Core saves it to that connection
if the saved generation still matches.
> - The next run can start with the rotated token.

## Linked Issues or Issue Description

Refs #23395. Refs #23168.

This PR targets `master` and includes the capability-based handler from
#23395. Merging this PR lands the handler and Antigravity writeback
together.

**Current behavior**

A managed Antigravity sign-in reaches the plugin as an environment
credential. Core waits for task retirement to collect a refresh.

**Proposed behavior**

Seed a private auth-file. Observe refresh-token changes for the ordinary
ACP server and the unified CLI. Use the existing credential update event
to save them during execution.

**Reason and benefit**

A long-running task can keep its source connection current across
successive rotations.

## What Changed

- Dispatch PRP credential updates to the live writeback capability
declared for the bound harness and execution target.
- Send Antigravity subscriptions as auth-file credentials to environment
task providers. Keep Gemini API keys and previously admitted environment
credentials on their existing paths.
- Watch the ACP token file and the unified CLI token file. Compare the
refresh token, copy it to the bound file, and emit the existing
secret-free event.
- Bind writeback to the original grant, secret, session epoch, and
credential generation. Save the next generation in the same transaction.

## Verification

- Reproduced the failed final Google save hanging on the next session
close. After commit `2b3e7897cd`, both focused cleanup suites passed (43
tests). The regression covers two overlapping close retries after the
credential home is released and checks that the saved credential is
removed only after persistence succeeds.
- All 21 Rust observer tests passed on both builds. They cover
interruption between the host file and event journal writes, a further
rotation before restart, and a reconnect that supersedes the task.
- On the legacy build, 422 Runner TypeScript tests passed. With the
merged unified CLI on this branch, all 126 tests in the auth, credential
staging, and runtime host suites passed.
- The two plugin writeback database suites passed (39 tests). A refresh
that starts before task stop cannot overwrite the final token after
stop.
- One run timed out in an unrelated process-retirement test. All three
suites passed together on repeat. All OAuth documents in these tests are
fixtures. No live Google sign-in was exercised.

## Risks

- The agent and any process it starts are trusted not to substitute
another account’s refresh token in the harness credential file. Core
accepts the file’s refresh token for the original connection only while
the grant, secret, session epoch, and expected credential generation
still match. Substitution within that boundary is an accepted risk.
[Review
finding](https://github.com/paperclipai/paperclip/pull/23397#discussion_r4759261984)
- Deploy with a plugin and Launcher that support the new auth-file
provider. This branch includes the unified CLI from #23168 and still
observes the legacy token format.

> 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

OpenAI GPT-6 in Codex, with local code execution and GitHub CLI.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 01:49:46 +00:00

425 lines
22 KiB
TypeScript

import { constants } from "node:fs";
import { createHash, randomUUID } from "node:crypto";
import { mkdir, mkdtemp, realpath, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
GENERATED_ANTIGRAVITY_SWARM_CHANNELS, GENERATED_ANTIGRAVITY_SWARM_CREDENTIAL_FACTS_FIELD, GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL,
readGeneratedAntigravitySwarmCredentialFacts, sanitizeAntigravityCredential, verifyAntigravityCredential,
type GeneratedAntigravitySwarmChannel,
} from "../../vendor/paperclip-runner/index.js";
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
import { reconcileRetainedGoogleCleanupForHome, retainGoogleCredentialCleanupForHome, retainGoogleCredentialCleanup, type RetainedGoogleCleanupScope } from "../retained-google-credential-cleanup.js";
import { withDirectoryMergeLock } from "@paperclipai/adapter-utils/workspace-restore-merge";
import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
import { openRunnerWorkspaceFile } from "./runner-api-files.js";
import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js";
import { bindManagedNativeCredentialTurn } from "./managed-native-credentials.js";
import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js";
import { antigravityReleasePending } from "./antigravity-release.js";
const AUTH_SECRET = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET";
const TOKEN_FILE = "acp_token.json";
const REFRESH_FILE = "auth-refresh.json";
const retirementProofs = new WeakMap<object, () => Promise<void>>();
type RunnerdTransport = ReturnType<typeof createRunnerdCodexTransport>;
/** Preserve the exact process owner's proof without changing a failed native
* session's durable settlement error or making that session reusable. */
export function bindAntigravityTransportRetirement(bundle: RunnerdTransport): RunnerdTransport["transport"] {
const close = bundle.transport.close.bind(bundle.transport);
bundle.transport.close = async reason => {
try { await close(reason); }
catch (error) {
if (error && typeof error === "object" && bundle.retireProbeResources) {
retirementProofs.set(error, () => bundle.retireProbeResources!());
}
throw error;
}
};
return bundle.transport;
}
/**
* The Google channel a trusted /swarm's Antigravity CLI talks to, owned by the
* deployment: `provider_default` (the default; Google's daily channel, which
* Google's own app and CLI use and which can change with less notice) or
* `stable` (Google's stable endpoint, which may offer fewer models).
*/
export const ANTIGRAVITY_SWARM_CHANNEL_ENV = "PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL";
export function antigravitySwarmChannel(env: NodeJS.ProcessEnv = process.env): GeneratedAntigravitySwarmChannel {
const value = env[ANTIGRAVITY_SWARM_CHANNEL_ENV]?.trim().toLowerCase();
return (GENERATED_ANTIGRAVITY_SWARM_CHANNELS as readonly string[]).includes(value ?? "")
? value as GeneratedAntigravitySwarmChannel : GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL;
}
/** Same digest as the Runner's antigravityAccountDigest: a one-way, non-identifying account comparison. */
export function antigravityAccountDigest(email: string): string {
return createHash("sha256").update(`paperclip.antigravity-account.v1:${email.trim().toLowerCase()}`, "utf8").digest("hex");
}
/** Only explicit run credentials may enter Antigravity's isolated runtime. */
export async function prepareAntigravityRunnerCredentials(input: {
environment: NodeJS.ProcessEnv;
remote: boolean;
managedHome?: string;
lifecycleMode?: "per_turn" | "warm";
/** The connection's Google account; only its digest reaches the Runner. */
accountEmail?: string;
}): Promise<{ environment: NodeJS.ProcessEnv; home: string | null; credential?: string }> {
const environment = { ...input.environment };
const apiKey = Boolean(environment.GEMINI_API_KEY?.trim());
for (const key of Object.keys(environment)) {
if (key === AUTH_SECRET || key.startsWith("GOOGLE_") || (key.startsWith("GEMINI_") && !(apiKey && key === "GEMINI_API_KEY"))) {
delete environment[key];
}
}
const releasePending = antigravityReleasePending();
// Save and Test refuse these choices first; this is the run-time defense.
// While pending, assertAntigravityExecutionAdmissible enforces the operator's
// cloud grant separately; remote sign-in remains refused until released.
const refusal = antigravityConnectionRefusal({
apiKey,
remote: input.remote,
lifecycleMode: input.lifecycleMode,
releasePending,
remoteCandidateAdmitted: releasePending && input.remote,
});
if (refusal) throw new AntigravityConnectionConfigurationError(refusal);
if (apiKey) return { environment, home: null };
const home = input.managedHome?.trim();
if (!home) throw new Error("Google Antigravity requires a selected managed Google account or Google API key.");
await reconcileRetainedGoogleCleanupForHome(home);
let credential: string;
try {
credential = sanitizeAntigravityCredential(await readLocalAiCredentialFile(join(home, "antigravity-acp", TOKEN_FILE)));
} catch {
throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry.");
}
if (input.remote) {
environment[AUTH_SECRET] = credential;
return { environment, home, credential };
}
// Run facts bound to this credential for the swarm route (channel, account
// digest). The Runner's credential sanitizer drops them before any write, so
// the staged token and its writeback comparison are unchanged.
// Facts follow the declared sidecar schema (antigravitySwarmCredentialFacts); the reader proves the shape.
const facts = readGeneratedAntigravitySwarmCredentialFacts({ swarmChannel: antigravitySwarmChannel(),
...(input.accountEmail ? { accountSha256: antigravityAccountDigest(input.accountEmail) } : {}) });
if (!facts) throw new Error("Antigravity swarm credential facts do not match the sidecar contract");
environment[AUTH_SECRET] = JSON.stringify({ ...JSON.parse(credential) as Record<string, unknown>, [GENERATED_ANTIGRAVITY_SWARM_CREDENTIAL_FACTS_FIELD]: facts });
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: {
originalCredential: string;
refreshedCredential: string;
managedHome: string;
accountEmail?: string;
}): Promise<string> {
const original = JSON.parse(sanitizeAntigravityCredential(input.originalCredential));
const refreshed = sanitizeAntigravityCredential(input.refreshedCredential);
const candidate = JSON.parse(refreshed);
if (candidate.refresh_token === original.refresh_token && candidate.client_secret === original.client_secret) return refreshed;
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 AntigravityAccountMismatchError();
}
return verified.credential;
}
/** Recover only an encrypted refresh from an owner that already retired. A
* disposable verification home cannot inherit any provider process lifetime. */
export async function prepareAntigravityCredentialRecovery(input: {
originalCredential: string; refreshedCredential: string; accountEmail: string;
scope: RetainedGoogleCleanupScope;
persistVerified: (credential: string) => Promise<void>;
}): Promise<string> {
const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-google-recovery-")));
const directory = join(home, "antigravity-acp");
try {
await mkdir(directory, { mode: 0o700 });
await writeFile(join(directory, TOKEN_FILE), sanitizeAntigravityCredential(input.refreshedCredential), { flag: "wx", mode: 0o600 });
} catch (error) {
await rm(home, { recursive: true, force: true });
throw error;
}
let verified: string | undefined;
let persisted = false;
const cleanup = () => withAccountHomeSecretMutationLock(undefined, input.scope.companyId, async () => {
// A failed verification may itself have rotated the token. Retry the
// private home's current generation, never the earlier journal value.
if (!persisted) {
const refreshedCredential = await readLocalAiCredentialFile(join(directory, TOKEN_FILE));
verified = await prepareAntigravityCredentialWriteback({ ...input, refreshedCredential, managedHome: home });
await input.persistVerified(verified);
persisted = true;
}
await rm(home, { recursive: true, force: true });
});
try {
await cleanup();
return verified!;
} catch (error) {
retainGoogleCredentialCleanup({ scope: input.scope, cleanup, home });
throw error;
}
}
/** Lifecycle callbacks copy into this invocation's home, never a shared login. */
export function antigravityCredentialTurn(input: {
managedHome: string;
runtimeHome: string;
credential: string;
saveRotation?: () => Promise<void>;
/** Remote Core sandbox runs export and scrub rotated tokens over the sandbox runner. */
runtimeStore?: { read: () => Promise<string>; remove: () => Promise<void> };
}) {
const runtimeDirectory = join(input.runtimeHome, "antigravity-acp");
const destination = join(input.managedHome, "antigravity-acp", TOKEN_FILE);
let pendingStage: { path: string; directoryDev: number; directoryIno: number; dev?: number; ino?: number } | undefined;
return {
copyBack: async () => {
let serialized: string;
try {
if (input.runtimeStore) {
serialized = await input.runtimeStore.read();
} else {
try { serialized = await readLocalAiCredentialFile(join(runtimeDirectory, TOKEN_FILE)); }
catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
serialized = await readLocalAiCredentialFile(join(runtimeDirectory, REFRESH_FILE));
}
}
} catch (error) {
// A provider that never started has no refresh to preserve.
if ((error as NodeJS.ErrnoException).code === "ENOENT" && !pendingStage) return;
throw new Error("Google Antigravity credential refresh handoff is invalid.");
}
const refreshed = sanitizeAntigravityCredential(serialized);
if (refreshed === input.credential) {
if (pendingStage) throw new Error("Google Antigravity credential refresh handoff is invalid.");
return;
}
const destinationDirectory = join(input.managedHome, "antigravity-acp");
await withDirectoryMergeLock(destinationDirectory, async () => {
const directory = await openRunnerWorkspaceFile(destinationDirectory, constants.O_RDONLY | constants.O_DIRECTORY);
let staged: Awaited<ReturnType<typeof openRunnerWorkspaceFile>> | undefined;
let stagedOwned = false;
const stagedPath = join(destinationDirectory, `.acp_token.copyback-${randomUUID()}.tmp`);
let cleanupStage: (() => Promise<void>) | undefined;
try {
const owner = await directory.stat();
if (!owner.isDirectory() || owner.uid !== process.getuid?.() || (owner.mode & 0o077) !== 0) {
throw new Error("Google Antigravity credential destination is invalid.");
}
const assertDirectoryOwner = async () => {
const current = await openRunnerWorkspaceFile(destinationDirectory, constants.O_RDONLY | constants.O_DIRECTORY);
try {
const metadata = await current.stat();
if (metadata.dev !== owner.dev || metadata.ino !== owner.ino || metadata.uid !== owner.uid || (metadata.mode & 0o077) !== 0) {
throw new Error("Google Antigravity credential destination changed during execution.");
}
} finally { await current.close(); }
};
cleanupStage = async () => {
if (!pendingStage) return;
if (pendingStage.directoryDev !== owner.dev || pendingStage.directoryIno !== owner.ino) {
throw new Error("Google Antigravity credential staging ownership changed.");
}
if (pendingStage.dev === undefined || pendingStage.ino === undefined) {
if (!staged) throw new Error("Google Antigravity credential staging ownership is unavailable.");
const created = await staged.stat();
pendingStage.dev = created.dev; pendingStage.ino = created.ino;
}
const previous = await openRunnerWorkspaceFile(pendingStage.path, constants.O_RDONLY)
.catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; });
if (previous) {
try {
const metadata = await previous.stat();
if (!metadata.isFile() || metadata.dev !== pendingStage.dev || metadata.ino !== pendingStage.ino
|| metadata.nlink !== 1 || metadata.uid !== owner.uid || (metadata.mode & 0o777) !== 0o600) {
throw new Error("Google Antigravity credential staging ownership changed.");
}
} finally { await previous.close(); }
}
await rm(pendingStage.path, { force: true });
pendingStage = undefined;
};
// A failed removal remains this owner's obligation on the next retry.
await cleanupStage();
const readDestination = async (sync = false) => {
const file = await openRunnerWorkspaceFile(destination, constants.O_RDONLY);
const bytes = Buffer.alloc(65_537);
try {
const metadata = await file.stat();
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.uid !== process.getuid?.() || (metadata.mode & 0o777) !== 0o600 || metadata.size > 65_536) {
throw new Error("Google Antigravity credential destination is invalid.");
}
let size = 0;
while (size < bytes.length) {
const result = await file.read(bytes, size, bytes.length - size, size);
if (!result.bytesRead) break;
size += result.bytesRead;
}
if (size > 65_536) throw new Error("Google Antigravity credential destination changed during execution.");
const current = sanitizeAntigravityCredential(bytes.subarray(0, size).toString("utf8"));
if (current !== input.credential && current !== refreshed) {
throw new Error("Google Antigravity credential destination changed during execution.");
}
if (sync) await file.sync();
return { metadata, current };
} finally { bytes.fill(0); await file.close(); }
};
const original = await readDestination();
if (original.current === refreshed) {
// A previous rename may have committed before its directory fsync
// or close failed. Confirm exactly that generation before cleanup.
const synced = await readDestination(true);
await directory.sync();
await assertDirectoryOwner();
const confirmed = await readDestination();
if (synced.current !== refreshed || confirmed.current !== refreshed || confirmed.metadata.dev !== original.metadata.dev
|| confirmed.metadata.ino !== original.metadata.ino || confirmed.metadata.mtimeMs !== original.metadata.mtimeMs
|| confirmed.metadata.ctimeMs !== original.metadata.ctimeMs) {
throw new Error("Google Antigravity credential destination changed during execution.");
}
return;
}
staged = await openRunnerWorkspaceFile(stagedPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
stagedOwned = true;
pendingStage = { path: stagedPath, directoryDev: owner.dev, directoryIno: owner.ino };
const created = await staged.stat();
pendingStage.dev = created.dev; pendingStage.ino = created.ino;
const replacement = Buffer.from(refreshed);
let stagedMetadata;
try {
let written = 0;
while (written < replacement.length) {
const result = await staged.write(replacement, written, replacement.length - written, written);
if (!result.bytesWritten) throw new Error("Google Antigravity credential copy-back failed.");
written += result.bytesWritten;
}
await staged.sync();
stagedMetadata = await staged.stat();
if (!stagedMetadata.isFile() || stagedMetadata.nlink !== 1 || stagedMetadata.uid !== owner.uid
|| (stagedMetadata.mode & 0o777) !== 0o600 || stagedMetadata.size !== replacement.length) {
throw new Error("Google Antigravity credential staging file is invalid.");
}
} finally { replacement.fill(0); }
await staged.close();
staged = undefined;
await assertDirectoryOwner();
const current = await readDestination();
if (current.current !== original.current || current.metadata.dev !== original.metadata.dev || current.metadata.ino !== original.metadata.ino
|| current.metadata.mtimeMs !== original.metadata.mtimeMs || current.metadata.ctimeMs !== original.metadata.ctimeMs) {
throw new Error("Google Antigravity credential destination changed during execution.");
}
// Never truncate the selected token. Publish only the fully synced
// private same-directory file, then make its directory entry durable.
await rename(stagedPath, destination);
await directory.sync();
await assertDirectoryOwner();
const published = await readDestination();
if (published.current !== refreshed || published.metadata.dev !== stagedMetadata.dev || published.metadata.ino !== stagedMetadata.ino) {
throw new Error("Google Antigravity credential destination changed during execution.");
}
} finally {
try {
if (stagedOwned) await cleanupStage?.();
} finally {
try { await staged?.close(); } finally { await directory.close(); }
}
}
});
},
remove: async () => {
if (input.runtimeStore) {
await input.runtimeStore.remove();
return;
}
const directory = await openRunnerWorkspaceFile(runtimeDirectory, constants.O_RDONLY | constants.O_DIRECTORY)
.catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; });
if (!directory) return;
try {
const metadata = await directory.stat();
if (!metadata.isDirectory() || metadata.uid !== process.getuid?.()) throw new Error("Google Antigravity credential cleanup home is invalid.");
} finally { await directory.close(); }
await Promise.all([TOKEN_FILE, REFRESH_FILE, `${REFRESH_FILE}.tmp`].map(name => rm(join(runtimeDirectory, name), { force: true })));
},
};
}
/** Google identity verification can itself rotate a refresh token. Retire the
* native process before exporting its final token so no live in-memory client
* can retain an older generation while the connection owner verifies/saves it. */
export function bindAntigravityCredentialTurn(session: NativeSession, input: Parameters<typeof antigravityCredentialTurn>[0]): NativeSession {
const callbacks = antigravityCredentialTurn(input);
const close = session.close.bind(session);
const detach = session.detachControllerForRestart?.bind(session);
let retirement: Promise<void> | undefined;
let retired = false;
let detached = false;
let copied = false;
let removed = false;
let handoffRunning: Promise<void> | undefined;
let proveRetirement: (() => Promise<void>) | undefined;
const retryRetirement = async () => {
if (retired) return;
if (!proveRetirement) throw new Error("Google Antigravity runtime retirement remains unconfirmed.");
await proveRetirement();
retired = true;
};
let retryHandoff: (() => Promise<void>) | undefined;
const retain = () => retryHandoff ??= retainGoogleCredentialCleanupForHome(input.managedHome, {
cleanup: handoff, ...(retired ? {} : { retired: retirement, ...(proveRetirement ? { retryRetirement } : {}) }),
});
const retire: NativeSession["close"] = options => retirement ??= Promise.resolve().then(() => close(options)).catch(error => {
if (error && typeof error === "object") proveRetirement = retirementProofs.get(error);
// close() may be called before the turn-completion callback. It still
// owns the same private credential and must keep that account fenced.
retain();
throw error;
});
session.close = retire;
if (detach) session.detachControllerForRestart = async () => { detached = true; await detach(); };
const handoff = (): Promise<void> => handoffRunning ??= (async () => {
if (detached) return;
try {
if (!retired) {
await retire({ reason: "Google Antigravity subscription credential handoff" });
retired = true;
}
if (!copied) { await (input.saveRotation ?? callbacks.copyBack)(); copied = true; }
if (!removed) { await callbacks.remove(); removed = true; }
} catch (error) {
// Until copy-back succeeds, this private runtime can hold the only valid
// rotated token. The same account must settle this owner before launch.
retain();
throw error;
}
})().finally(() => { handoffRunning = undefined; });
bindManagedNativeCredentialTurn(session, {
copyBack: handoff,
remove: async () => {
if (copied && !removed) { await callbacks.remove(); removed = true; }
},
});
const managedClose = session.close.bind(session);
session.close = async options => {
if (detached) return;
await managedClose(options);
// The shared turn manager settles a failed turn once. Google retains its
// failed handoff, so a later close also retries the original private files.
if (!removed) await (retryHandoff ?? handoff)();
};
return session;
}