feat(runner): seed ACPX file credentials from a host file (#22843)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner runs ACPX agents, such as Codex and Grok, in an
isolated provider home for each session
> - The Runner seeds that home only from an inline credential secret, so
a host that keeps the login in a file it owns must copy it into a
variable for every session
> - The credential observer now writes refreshes back to a named host
file (#23340), so a session should also start from that file
> - This pull request seeds the isolated home from
`PAPERCLIP_ACPX_AUTH_JSON_FILE` and documents the host contract
> - The benefit is that a host can keep one login file per account
across sessions without giving the provider access to the host's
directory

## Linked Issues or Issue Description

**Subsystem affected**

Paperclip Runner ACPX credential staging, the Runner environment
boundary (runnerd and the Rust sidecar transport), and Core's server
environment handling.

**Problem or motivation**

An ACPX Codex or Grok session always stages its `auth.json` into the
Runner's isolated home from
`PAPERCLIP_ACPX_{CODEX,GROK}_AUTH_JSON_SECRET`. A host that keeps the
credential in its own file must copy the file into a variable before
each session.

**Proposed solution**

`PAPERCLIP_ACPX_AUTH_JSON_FILE` names an absolute host file. The Runner
validates the file and seeds the isolated home from it; the credential
observer writes refreshes back to it. The provider never sees the host
path.

**Alternatives considered**

Point `GROK_HOME` at the host directory, as
`PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME` does for Claude. Rejected: the
Runner writes its permission policy into `GROK_HOME` for every session,
and a shared home would share session history between sessions.

**Roadmap alignment**

None in `ROADMAP.md`; this extends the Runner's existing ACPX credential
staging.

**Additional context**

Builds on #23339 (write-back rules) and #23340 (observer write-back).

## What Changed

- New variable `PAPERCLIP_ACPX_AUTH_JSON_FILE` for ACPX sessions whose
agent uses a file credential (Codex, Grok). Any other agent, a relative
path, or a combination with the inline secret or the provider API key
fails admission.
- Seeding reads the host file with the existing source reader (a regular
file that is not a symlink, owned by the Runner user, with no group or
other access, at most 256 KiB) and checks the Codex or Grok format on
the exact bytes it stages. Seeding copies the file and never writes it.
- The inline-secret and API-key conflicts are checked at both launch
boundaries, runnerd and the Rust sidecar transport, before the
environment is filtered, so a secret the allowlist drops still
conflicts.
- The variable crosses the sidecar boundary only for Codex and Grok and
never reaches the provider. Core's server removes it from Runner
environments and refuses it as an environment binding, so only the
execution host can name a file.
- With a host file, the lease keeps the final `auth.json` as
`auth-refresh.json` when the provider stops, even when admission fails,
and the next lease leaves that file in place. A warm `run.attach` or
idle restart therefore cannot discard a refresh made during shutdown
before the observer writes it back.
- `managedCodexCredentialSourcePath` becomes
`managedCredentialSourcePath` and covers Grok.
- The Runner README documents the contract in a "Host credential file"
section, and the protocol README notes write-back.
- No code comments are added, per CONTRIBUTING.md.

## Verification

- Runner vitest: `credential-file`, `grok-credentials`, `runtime-host`,
`codex-credentials`, `codex-acpx-driver`, `runnerd-codex-transport`,
`durable-prp-control-plane` (830 passed). They cover seeding Codex and
Grok homes from a host file without exposing its path or changing the
host copy; a startup refresh kept for write-back across the next start;
ambiguous, relative and malformed files failing admission; the format
validators; the runnerd boundary's agent and conflict checks; and the
spawn-boundary allowlist.
- Server vitest: `native-session-executor` and `heartbeat-project-env`
(1609 passed, 7 skipped), covering the variable removed from Runner
environments and refused as a binding.
- `cargo test -p paperclip-runner-core --test acpx_sidecar_transport`
for the sidecar boundary (Codex and Grok receive the path, Claude and a
conflicting secret fail closed).
- Runner and server typecheck; `cargo fmt -p paperclip-runner-core --
--check`.
- Tests trimmed while splitting: the runtime host's unsafe-permission
and linked-source cases (the shared reader's own tests cover both) and
its Claude case (runnerd and the sidecar refuse Claude first, with their
own tests).
- Not run locally: clippy, the full Runner workspace tests, and the
release and eviction integration suites. CI runs them.

## Risks

- Both providers rotate refresh tokens, and a rotated token stops
working. Each provider's own coordination stays inside the session's
isolated home, and the Runner does not lock the host file. Copies of one
sign-in share its refresh token wherever they live, so when two copies
refresh separately the later refresh can fail that command or turn, or
the provider can revoke the sign-in and the user signs in again. The
README describes this and leaves the choice of how many sessions share a
sign-in to the host.
- The host directory must let the Runner user create and rename files
beside the host file.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, cargo and vitest runs) and extended thinking.

## 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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 15:55:38 +00:00
1 parent 8607b27e39
commit 36c2ad39c8
24 files changed
+439 -31

No files matched your search

+83
View File
@@ -1050,6 +1050,89 @@ with the current launch settings. History remains in the account directory.
Task control files remain in the session runtime directory. Separate directories
under one OS user are not a credential isolation boundary.
## Host credential file
An execution environment can supply the login for an ACPX agent whose
credential is one `auth.json` document, currently `codex` and `grok`, through
`PAPERCLIP_ACPX_AUTH_JSON_FILE`. The value is the absolute path of the host's
credential file in the agent's own format. The provider keeps running in its
Runner-owned isolated home: Runner copies the credential in at admission and
copies fresher refreshes back. It never points the provider at the host file or
its directory. The host sets the variable on the Runner process. Core's server
never sets it and removes it from the environment it hands to the Runner, so
configuration bindings cannot supply it.
Admission fails closed when:
- the session's agent is not ACPX `codex` or `grok`;
- the path is relative or names the isolated home's own `auth.json`;
- the variable is combined with the inline credential
(`PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET`, `PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET`)
or the provider API key (`OPENAI_API_KEY`/`CODEX_API_KEY`, `XAI_API_KEY`);
- the file is a symlink, is not a regular file, is empty or larger than
256 KiB, is not owned by the Runner user, or grants group or other access;
- the document does not match the agent's format. A Codex document carries
either `OPENAI_API_KEY` or `tokens.account_id` with token material. A Grok
document has exactly one `<issuer>::<uuid>` key whose value has a non-empty
`key` and `refresh_token`.
Seeding reads the file once and stages those exact bytes into the isolated
home through the same crash-safe staging, cleanup and provider lifetime lease
as the inline credential. The variable crosses the Runner to the ACPX sidecar
only; the provider process never receives it.
Write-back runs during the session, not only at close. Runner watches the
isolated `auth.json` (and the final `auth-refresh.json` snapshot at close).
When the provider refreshes it, Runner replaces the host file only if the
refreshed credential is strictly fresher for the same identity:
- Codex: the same `tokens.account_id` and a later `last_refresh` (RFC 3339)
that is no more than five minutes past the Runner clock. API-key documents
are never written back.
- Grok: the same `<issuer>::<uuid>` key and a later `expires_at` (ISO 8601
string, epoch seconds below 10^12, or epoch milliseconds) that is no more
than 400 days past the Runner clock. Both expiries must be present and
readable.
Runner never replaces a newer host file, never writes a different account, and
never creates a missing host file. The replacement is a synced temporary file
in the host file's directory, renamed over the host file and followed by a
directory sync. It keeps the host file's mode and, where the Runner user may
set it, its group. If the host file changed while the replacement was prepared,
Runner discards it, reads the host file again and decides at once, up to three
times. Any other failure to settle a refresh against the host file, or a host
file that keeps changing, fails the command or turn that observed it: a rotated
refresh token must never be lost quietly. When the consumer opted in to credential observation, the
`auth.credentials.updated` event follows the write-back as before.
The host directory must allow the Runner user to create and rename files.
Both providers rotate the refresh token when they refresh, and a rotated token
stops working:
- Codex saves the new refresh token that a refresh returns. A rotated token is
refused with `refresh_token_reused`, and the user must sign in again
([Codex CI/CD authentication](https://learn.chatgpt.com/docs/auth/ci-cd-auth)).
Codex refreshes when `last_refresh` is older than about eight days, or after
a request is refused.
- Grok Build expects xAI's identity provider to accept a rotated refresh token
for about a minute at most, then to refuse it (`invalid_grant`). Presenting a
rotated token can also make the identity provider revoke the newer token that
another holder received.
Each provider coordinates its own processes through its home: Codex re-reads
`auth.json` before it refreshes after a refused request, and Grok Build
serializes refreshes with `auth.json.lock`. Each session's provider runs in its
own isolated home, so that coordination never reaches the host file or another
session, and Runner does not lock the host file either.
Every copy of one sign-in holds the same refresh token, whichever host file or
session it is in. When two copies refresh separately, the later refresh
presents a token the earlier one already rotated. The provider can refuse it,
which fails the command or turn that refreshed. It can also revoke the
sign-in, and the user then signs in again. Sessions on separate sign-ins do not
affect each other.
## Preconfigured home
Set `homeMode: "preconfigured"` in a `paperclip_runner` agent's adapter config
@@ -72,6 +72,9 @@ Account identity changes also emit updates, even when token values stay the
same, and establish the baseline for later refreshes on the new account.
Hosts must evaluate the current credential through their private credential
channel and account checks; the event does not authorize an account switch.
When the execution host supplies `PAPERCLIP_ACPX_AUTH_JSON_FILE` (see the
Runner README), the observer also writes fresher same-account refreshes back
to that file before the event, and does so even without the opt-in.
Metadata-only changes, partial writes, and deletion do not emit updates.
Unsupported harnesses and refreshes retained only in memory need
their own observer or native-hook integration; adding this event does not make
@@ -6,6 +6,7 @@ use std::time::{Duration, Instant};
use serde::Deserialize;
use serde_json::{json, Value};
use crate::credential_write_back::ACPX_AUTH_JSON_FILE_ENV;
use crate::generated_acpx_sidecar_contract::{
GeneratedAcpxSidecarCommand, GeneratedAcpxSidecarEventType,
GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
@@ -400,6 +401,30 @@ impl AcpxSidecarTransport {
{
keys.push("PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME");
}
if std::env::var_os(ACPX_AUTH_JSON_FILE_ENV).is_some_and(|value| !value.is_empty()) {
let conflicting: &[&str] = match agent {
"codex" => &[
"PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET",
"OPENAI_API_KEY",
"CODEX_API_KEY",
],
"grok" => &["PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "XAI_API_KEY"],
_ => {
return Err(LocalRunnerError::invalid(
"Managed credential files require the Codex or Grok ACPX profile",
))
}
};
if conflicting
.iter()
.any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
{
return Err(LocalRunnerError::invalid(
"Managed credential file source is ambiguous",
));
}
keys.push(ACPX_AUTH_JSON_FILE_ENV);
}
keys.extend_from_slice(credential_keys);
// Pi owns a native distribution copy, including a pending refresh at
// suspension. Allow its bounded cleanup to settle before group KILL;
@@ -759,3 +759,80 @@ fn managed_claude_broker_transport_reaches_the_sidecar_without_host_credentials(
}
transport.shutdown().unwrap();
}
#[test]
#[cfg(unix)]
fn host_credential_file_reaches_only_file_credential_sidecars() {
const CHILD: &str = "PAPERCLIP_TEST_CREDENTIAL_FILE_CHILD";
const CONFLICT: &str = "PAPERCLIP_TEST_CREDENTIAL_FILE_CONFLICT";
if std::env::var_os(CHILD).is_none() {
for (agent, conflict) in [
("codex", None),
("grok", None),
("claude", None),
("codex", Some("PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET")),
("grok", Some("XAI_API_KEY")),
] {
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
command
.args([
"--exact",
"host_credential_file_reaches_only_file_credential_sidecars",
])
.env_clear()
.env(CHILD, agent)
.env("PATH", "/usr/bin:/bin")
.env(
"PAPERCLIP_ACPX_AUTH_JSON_FILE",
"/host/credentials/auth.json",
);
if let Some(name) = conflict {
command.env(CONFLICT, name).env(name, "conflicting-canary");
}
let output = command.output().unwrap();
assert!(
output.status.success(),
"agent={agent}, conflict={conflict:?}: {} {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
return;
}
let agent = std::env::var(CHILD).unwrap();
let response = json!({
"protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
"id": 1, "ok": true, "result": { "environment": "%s" },
});
let config = AcpxSidecarTransportConfig {
command: PathBuf::from("/bin/sh"),
args: vec![
"-c".into(),
format!(
"IFS= read -r request; printf '{response}\\n' \"$PAPERCLIP_ACPX_AUTH_JSON_FILE\"; IFS= read -r next"
),
],
verified_launch: None,
request_timeout: Duration::from_secs(1),
shutdown_grace: Duration::from_millis(100),
};
let started = AcpxSidecarTransport::start_for_agent(&config, &agent);
if std::env::var_os(CONFLICT).is_some() {
let error = started
.err()
.expect("a second credential source fails closed");
assert!(error.to_string().contains("ambiguous"), "{error}");
return;
}
if !matches!(agent.as_str(), "codex" | "grok") {
let error = started.err().expect("other agents fail closed");
assert!(error.to_string().contains("Codex or Grok ACPX"), "{error}");
return;
}
let mut transport = started.unwrap();
let response = transport
.request(GeneratedAcpxSidecarCommand::Initialize, json!({}))
.expect("sidecar should report its launch environment");
assert_eq!(response["environment"], "/host/credentials/auth.json");
transport.shutdown().unwrap();
}
@@ -38,7 +38,7 @@ export interface NativeBackendFactoryOptions extends Omit<
}) => CodexAppServerTransport;
acpxRuntimeDirectory?: string;
acpxEnvironment?: NodeJS.ProcessEnv;
acpxManagedCodexCredentialSourcePath?: string;
acpxManagedCredentialSourcePath?: string;
acpxDynamicToolHandler?: AcpxNativeSessionBackendOptions["dynamicToolHandler"];
opencodeRuntimeDirectory?: string;
opencodeEnvironment?: NodeJS.ProcessEnv;
@@ -104,10 +104,10 @@ export function createNativeSessionBackend(
return createAcpxNativeSessionBackend(input, {
runtimeDirectory: options.acpxRuntimeDirectory,
environment: options.acpxEnvironment,
...(input.provider.agent === "codex"
...(input.provider.agent === "codex" || input.provider.agent === "grok"
? {
managedCodexCredentialSourcePath:
options.acpxManagedCodexCredentialSourcePath,
managedCredentialSourcePath:
options.acpxManagedCredentialSourcePath,
}
: {}),
dynamicTools: options.dynamicTools,
@@ -21,6 +21,7 @@ import { resolveCompletionContinuation } from "../drivers/completion-continuatio
import { createInterface } from "node:readline";
import { deliverAcpxResponse, requireAcpxResponseDelivery } from "../drivers/acpx/response-delivery.js";
import { createAcpxSidecarHostEnvironment } from "../drivers/acpx/environment.js";
import { acpxCredentialFileSourcePath } from "../drivers/acpx/credential-file.js";
import type {
AcpElicitationContext,
@@ -379,6 +380,7 @@ async function dispatch(
MCP_TOOL_TIMEOUT: String(60 * 60 * 1_000),
} : createAcpxSidecarHostEnvironment(process.env, params.agent, params.normalizedSessionId),
expectedIdentity: params.expectedIdentity,
managedCredentialSourcePath: acpxCredentialFileSourcePath(process.env),
assignedMcpTransport: "prp",
semanticTools: {
tools: params.tools,
@@ -2777,6 +2777,7 @@ it("preserves an explicit OpenCode permission mode at the runner spawn boundary"
PAPERCLIP_OPENCODE_RUNTIME_DIR: "/runner/opencode",
PAPERCLIP_NATIVE_MCP_STDIO: "[]",
PAPERCLIP_NATIVE_MCP_PROXY: "/runner/paperclip-runnerd",
PAPERCLIP_ACPX_AUTH_JSON_FILE: "/host/auth.json",
DATABASE_URL: "must-not-reach-runnerd",
PAPERCLIP_API_KEY: "must-not-reach-runnerd",
NODE_OPTIONS: "--require=/untrusted/bootstrap.cjs",
@@ -2814,6 +2815,7 @@ it("preserves an explicit OpenCode permission mode at the runner spawn boundary"
PAPERCLIP_OPENCODE_RUNTIME_DIR: "/runner/opencode",
PAPERCLIP_NATIVE_MCP_STDIO: "[]",
PAPERCLIP_NATIVE_MCP_PROXY: "/runner/paperclip-runnerd",
PAPERCLIP_ACPX_AUTH_JSON_FILE: "/host/auth.json",
});
expect(launches[0]!.environment.DATABASE_URL).toBeUndefined();
expect(launches[0]!.environment.PAPERCLIP_API_KEY).toBeUndefined();
@@ -4932,6 +4932,7 @@ const runnerExplicitProviderEnvironmentKeys = [
"CODEX_API_KEY",
"PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET",
"PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET",
"PAPERCLIP_ACPX_AUTH_JSON_FILE",
"PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET",
"XAI_API_KEY",
"AWS_REGION",
@@ -509,7 +509,7 @@ describe("Codex ACPX harness driver", () => {
model: "claude-sonnet-5",
});
expect(
fixture.hostOptions?.managedCodexCredentialSourcePath,
fixture.hostOptions?.managedCredentialSourcePath,
).toBeUndefined();
await session.close({ reason: "qualified Claude driver verified" });
});
@@ -167,7 +167,7 @@ export interface CodexAcpxDriverOptions {
runtimeContext?: OpenAcpxRuntimeHostOptions["runtimeContext"];
systemInstructions?: string;
environment?: NodeJS.ProcessEnv;
managedCodexCredentialSourcePath?: string;
managedCredentialSourcePath?: string;
dynamicTools?: readonly Readonly<Record<string, unknown>>[];
dynamicToolHandler?: (call: CodexAcpxDynamicToolCall) => Promise<unknown>;
/** Server-owned task completion validation, shared with Codex tool calls. */
@@ -485,8 +485,8 @@ export class CodexAcpxDriver implements HarnessDriver {
runtimeContext: this.#options.runtimeContext,
systemInstructions: this.#options.systemInstructions,
environment: this.#options.environment,
managedCodexCredentialSourcePath:
this.#options.managedCodexCredentialSourcePath,
managedCredentialSourcePath:
this.#options.managedCredentialSourcePath,
...(assertWorkspaceHeld === undefined ? {} : { assertWorkspaceHeld }),
...(snapshot?.providerIdentity?.kind === "acpx"
? { expectedIdentity: snapshot.providerIdentity }
@@ -180,6 +180,7 @@ export async function stageManagedCodexCredential(input: {
agentHomeDirectory: string;
environment?: NodeJS.ProcessEnv;
sourcePath?: string;
validateDocument?: (bytes: Buffer) => void;
}): Promise<ManagedCodexCredentialLease> {
const home = await resolvePrivateAgentHome(input.agentHomeDirectory);
// Join an older failed close before claiming the next generation. This
@@ -229,6 +230,7 @@ async function stageClaimedManagedCodexCredential(
input: {
environment?: NodeJS.ProcessEnv;
sourcePath?: string;
validateDocument?: (bytes: Buffer) => void;
},
home: string,
ownerGeneration: CredentialLeaseGeneration,
@@ -303,6 +305,7 @@ async function stageClaimedManagedCodexCredential(
: await readManagedCredential(input.sourcePath!);
try {
validateCredentialDocument(credential);
input.validateDocument?.(credential);
// As with API-key mode, an intent-publication failure occurs before any
// credential mutation and therefore needs no process-only quarantine.
await createCredentialCleanupIntent(intentPath, home);
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { validateCodexAuthDocument, validateGrokAuthDocument } from "./credential-file.js";
const identity = "https://accounts.x.ai::11111111-1111-4111-8111-111111111111";
const json = (value: unknown) => Buffer.from(JSON.stringify(value));
describe("ACPX host credential file formats", () => {
it.each([
["Codex subscription", validateCodexAuthDocument, json({ tokens: { account_id: "account-1", refresh_token: "refresh" } }), true],
["Codex API key", validateCodexAuthDocument, json({ OPENAI_API_KEY: "key" }), true],
["Codex without account", validateCodexAuthDocument, json({ tokens: { access_token: "no-account" } }), false],
["Codex without tokens", validateCodexAuthDocument, json({ tokens: { account_id: "account-1" } }), false],
["Codex blank API key", validateCodexAuthDocument, json({ OPENAI_API_KEY: " " }), false],
["Codex invalid UTF-8", validateCodexAuthDocument, Buffer.from([0x7b, 0xff, 0x7d]), false],
["Grok login", validateGrokAuthDocument, json({ [identity]: { key: "key", refresh_token: "refresh" } }), true],
["Grok without refresh token", validateGrokAuthDocument, json({ [identity]: { key: "key" } }), false],
["Grok with two identities", validateGrokAuthDocument, json({ [identity]: { key: "key", refresh_token: "refresh" }, other: {} }), false],
["Grok invalid identity", validateGrokAuthDocument, json({ "issuer::not-a-uuid": { key: "key", refresh_token: "refresh" } }), false],
["Grok not JSON", validateGrokAuthDocument, Buffer.from("not-json"), false],
] as const)("validates a %s document", (_name, validate, document, valid) => {
if (valid) expect(() => validate(document)).not.toThrow();
else expect(() => validate(document)).toThrow(/credential is malformed/);
});
});
@@ -0,0 +1,75 @@
import type { QualifiedAcpxAgent } from "./qualified-profiles.js";
export const ACPX_AUTH_JSON_FILE_ENV = "PAPERCLIP_ACPX_AUTH_JSON_FILE";
export const ACPX_CREDENTIAL_FILE_AGENTS: readonly QualifiedAcpxAgent[] = ["codex", "grok"];
export function supportsAcpxCredentialFile(agent: QualifiedAcpxAgent): boolean {
return ACPX_CREDENTIAL_FILE_AGENTS.includes(agent);
}
const CONFLICTING_CREDENTIAL_SOURCES: Readonly<Partial<Record<QualifiedAcpxAgent, readonly string[]>>> = {
codex: ["PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET", "OPENAI_API_KEY", "CODEX_API_KEY"],
grok: ["PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "XAI_API_KEY"],
};
export function assertAcpxCredentialFileAdmissible(
environment: NodeJS.ProcessEnv | undefined,
agent: QualifiedAcpxAgent,
): string | undefined {
const file = acpxCredentialFileSourcePath(environment);
if (file === undefined) return undefined;
if (!supportsAcpxCredentialFile(agent)) {
throw new Error("Managed credential files require the Codex or Grok ACPX profile");
}
if ((CONFLICTING_CREDENTIAL_SOURCES[agent] ?? []).some(name => Boolean(environment?.[name]))) {
throw new Error("Managed credential file source is ambiguous");
}
return file;
}
export function acpxCredentialFileSourcePath(environment: NodeJS.ProcessEnv | undefined): string | undefined {
const value = environment?.[ACPX_AUTH_JSON_FILE_ENV];
return typeof value === "string" && value.length > 0 ? value : undefined;
}
const GROK_IDENTITY_KEY = /^.+::[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function parseJsonObject(bytes: Buffer, label: string): Record<string, unknown> {
let value: unknown;
try {
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
} catch {
throw new Error(`${label} credential is malformed`);
}
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} credential is malformed`);
}
return value as Record<string, unknown>;
}
const nonEmpty = (value: unknown): boolean => typeof value === "string" && value.trim().length > 0;
export function validateGrokAuthDocument(bytes: Buffer): void {
const entries = Object.entries(parseJsonObject(bytes, "Grok"));
const [identity, auth] = entries[0] ?? [];
if (entries.length !== 1 || !GROK_IDENTITY_KEY.test(identity ?? "") ||
auth === null || typeof auth !== "object" || Array.isArray(auth) ||
!nonEmpty((auth as Record<string, unknown>).key) ||
!nonEmpty((auth as Record<string, unknown>).refresh_token)) {
throw new Error("Grok credential is malformed");
}
}
export function validateCodexAuthDocument(bytes: Buffer): void {
const value = parseJsonObject(bytes, "Codex");
if (nonEmpty(value.OPENAI_API_KEY)) return;
const tokens = value.tokens;
if (tokens === null || typeof tokens !== "object" || Array.isArray(tokens)) {
throw new Error("Codex credential is malformed");
}
const record = tokens as Record<string, unknown>;
if (!nonEmpty(record.account_id) || !["id_token", "access_token", "refresh_token"].some(key => nonEmpty(record[key]))) {
throw new Error("Codex credential is malformed");
}
}
@@ -8,11 +8,12 @@ export async function retainAcpxCredentialRefresh(input: {
lease: AcpxProviderLifetimeLease;
agentHomeDirectory: string;
retainRefresh: () => boolean;
keepPreviousRefresh?: boolean;
beforeClose?: () => Promise<void>;
}): Promise<AcpxProviderLifetimeLease> {
const { lease } = input;
const refresh = join(input.agentHomeDirectory, "auth-refresh.json");
await rm(refresh, { force: true }).catch(async (error) => { await lease.close(); throw error; });
if (!input.keepPreviousRefresh) await rm(refresh, { force: true }).catch(async (error) => { await lease.close(); throw error; });
let prepared = false;
let closed = false;
let closing: Promise<void> | null = null;
@@ -89,6 +89,18 @@ describe("Grok isolated credentials", () => {
expect(await readFile(join(directory, "auth-refresh.json"), "utf8")).toBe(credential);
expect(await readFile(join(directory, "auth.json"), "utf8")).toBe(successor);
});
it("stages a host credential file and retains its refresh for write-back", async () => {
const directory = await home();
const source = join(await home(), "auth.json");
await writeFile(source, credential, { mode: 0o600 });
const lease = await stageManagedGrokCredential({ agentHomeDirectory: directory, sourcePath: source });
expect(await readFile(join(directory, "auth.json"), "utf8")).toBe(credential);
const refreshed = credential.replace("test-token", "refreshed-token");
await writeFile(join(directory, "auth.json"), refreshed, { mode: 0o600 });
await lease.close();
expect(await readFile(join(directory, "auth-refresh.json"), "utf8")).toBe(refreshed);
expect(await readFile(source, "utf8")).toBe(credential);
});
it("never passes other providers, host homes or the inline credential to Grok", () => {
const result = createSanitizedAcpxSpawnInput({ XAI_API_KEY: "selected", HOME: "/host", GROK_HOME: "/host/.grok", OPENAI_API_KEY: "other", PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET: credential }, "grok");
expect(result.env).toEqual({ XAI_API_KEY: "selected" });
@@ -1,6 +1,7 @@
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { stageManagedCodexCredential, type AcpxProviderLifetimeLease } from "./codex-credentials.js";
import { validateGrokAuthDocument } from "./credential-file.js";
import { retainAcpxCredentialRefresh } from "./credential-refresh.js";
@@ -13,34 +14,31 @@ export const GROK_AUTH_REFRESH_FILE = "auth-refresh.json";
export async function stageManagedGrokCredential(input: {
agentHomeDirectory: string;
environment?: NodeJS.ProcessEnv;
sourcePath?: string;
retainRefresh?: () => boolean;
}): Promise<AcpxProviderLifetimeLease> {
const source = input.environment ?? {};
const inline = source.PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET;
const apiKey = source.XAI_API_KEY;
if (inline && apiKey) throw new Error("Grok credential source is ambiguous");
if (!inline && !apiKey) throw new Error("Grok login or explicit XAI_API_KEY is required");
const file = typeof input.sourcePath === "string" && input.sourcePath.length > 0 ? input.sourcePath : undefined;
const sources = [inline, apiKey, file].filter(Boolean).length;
if (sources > 1) throw new Error("Grok credential source is ambiguous");
if (sources === 0) throw new Error("Grok login or explicit XAI_API_KEY is required");
if (inline) {
if (Buffer.byteLength(inline) > 256 * 1024) throw new Error("Grok credential exceeds its bound");
let value: unknown;
try { value = JSON.parse(inline); } catch { throw new Error("Grok credential is malformed"); }
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Grok credential is malformed");
const entries = Object.entries(value);
// Keep aligned with grok-local's parseGrokAuthPayload / hasUsableGrokAuthValue.
const [identity, auth] = entries[0] ?? [];
if (entries.length !== 1 || !/^.+::[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(identity ?? "") ||
!auth || typeof auth.key !== "string" || !auth.key.trim() ||
typeof auth.refresh_token !== "string" || !auth.refresh_token.trim()) {
throw new Error("Grok credential is malformed");
}
validateGrokAuthDocument(Buffer.from(inline, "utf8"));
}
const lease = await stageManagedCodexCredential({
agentHomeDirectory: input.agentHomeDirectory,
environment: inline ? { PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET: inline } : { OPENAI_API_KEY: apiKey },
...(file
? { sourcePath: file, validateDocument: validateGrokAuthDocument }
: { environment: inline ? { PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET: inline } : { OPENAI_API_KEY: apiKey } }),
});
const subscription = Boolean(inline || file);
return retainAcpxCredentialRefresh({
lease, agentHomeDirectory: input.agentHomeDirectory,
retainRefresh: () => Boolean(inline) && (input.retainRefresh?.() ?? true),
retainRefresh: () => subscription && (input.retainRefresh?.() ?? true),
keepPreviousRefresh: file !== undefined,
// Diagnostics may contain auth fields; session history remains resumable.
beforeClose: () => rm(join(input.agentHomeDirectory, "logs"), { recursive: true, force: true }),
});
@@ -1518,6 +1518,75 @@ describe("ACPX runtime host", () => {
expect(fixture.commandClose).toHaveBeenCalledOnce();
});
const hostCredentialFiles = {
codex: { model: "gpt-5.6-sol", permissionMode: "approve-all" as const, home: "CODEX_HOME",
document: JSON.stringify({ tokens: { account_id: "account-1", access_token: "host-access", refresh_token: "host-refresh" }, last_refresh: "2026-01-01T00:00:00Z" }),
refreshed: JSON.stringify({ tokens: { account_id: "account-1", access_token: "startup-access", refresh_token: "startup-refresh" }, last_refresh: "2026-01-02T00:00:00Z" }),
inline: "PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET", apiKey: "OPENAI_API_KEY",
malformed: JSON.stringify({ tokens: { access_token: "no-account" } }) },
grok: { model: "grok-4.7", permissionMode: "approve-reads" as const, home: "GROK_HOME",
document: JSON.stringify({ "https://accounts.x.ai::11111111-1111-4111-8111-111111111111": { key: "host-access", refresh_token: "host-refresh", expires_at: 1_767_225_600 } }),
refreshed: JSON.stringify({ "https://accounts.x.ai::11111111-1111-4111-8111-111111111111": { key: "startup-access", refresh_token: "startup-refresh", expires_at: 1_767_312_000 } }),
inline: "PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", apiKey: "XAI_API_KEY",
malformed: JSON.stringify({ "https://accounts.x.ai::11111111-1111-4111-8111-111111111111": { key: "host-access" } }) },
} as const;
it.each(["codex", "grok"] as const)("seeds the isolated %s home from a host credential file without exposing its path, and keeps a startup refresh for write-back across the next start", async agent => {
const fixture = await hostFixture();
const profile = hostCredentialFiles[agent];
const source = join(fixture.root, "host-auth.json");
await writeFile(source, profile.document, { mode: 0o600 });
let home = "";
await expect(AcpxRuntimeHost.open({
...fixture.options, agent, model: profile.model, permissionMode: profile.permissionMode,
environment: { PAPERCLIP_ACPX_AUTH_JSON_FILE: source }, managedCredentialSourcePath: source,
}, fixture.dependencies({ openRuntime: async options => {
home = options.launchEnvironment[profile.home]!;
expect(await readFile(join(home, "auth.json"), "utf8")).toBe(profile.document);
expect((await stat(join(home, "auth.json"))).mode & 0o777).toBe(0o600);
expect(options.launchEnvironment).not.toHaveProperty("PAPERCLIP_ACPX_AUTH_JSON_FILE");
expect(JSON.stringify(options.launchEnvironment)).not.toContain(source);
await writeFile(join(home, "auth.json"), profile.refreshed, { mode: 0o600 });
throw new Error("provider stopped after seeding");
} }))).rejects.toThrow("provider stopped after seeding");
await expect(readFile(join(home, "auth.json"))).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(join(home, "auth-refresh.json"), "utf8")).toBe(profile.refreshed);
expect(await readFile(source, "utf8")).toBe(profile.document);
await expect(AcpxRuntimeHost.open({
...fixture.options, agent, model: profile.model, permissionMode: profile.permissionMode,
environment: { PAPERCLIP_ACPX_AUTH_JSON_FILE: source }, managedCredentialSourcePath: source,
}, fixture.dependencies({ openRuntime: async options => {
const next = options.launchEnvironment[profile.home]!;
expect(next).toBe(home);
expect(await readFile(join(next, "auth.json"), "utf8")).toBe(profile.document);
expect(await readFile(join(next, "auth-refresh.json"), "utf8")).toBe(profile.refreshed);
throw new Error("successor stopped after seeding");
} }))).rejects.toThrow("successor stopped after seeding");
});
it.each(["codex", "grok"] as const)("fails %s admission for an ambiguous, relative or malformed host credential file", async agent => {
const profile = hostCredentialFiles[agent];
const fixture = await hostFixture();
const source = join(fixture.root, "host-auth.json");
const malformed = join(fixture.root, "malformed-auth.json");
await writeFile(source, profile.document, { mode: 0o600 });
await writeFile(malformed, profile.malformed, { mode: 0o600 });
const cases: [string, NodeJS.ProcessEnv, RegExp][] = [
[source, { [profile.inline]: profile.document }, /ambiguous/],
[source, { [profile.apiKey]: "test-key" }, /ambiguous/],
["relative/auth.json", {}, /external absolute path/],
[malformed, {}, /malformed/],
];
for (const [path, environment, error] of cases) {
const openRuntime = vi.fn();
await expect(AcpxRuntimeHost.open({
...fixture.options, agent, model: profile.model, permissionMode: profile.permissionMode,
environment, managedCredentialSourcePath: path,
}, fixture.dependencies({ openRuntime }))).rejects.toThrow(error);
expect(openRuntime).not.toHaveBeenCalled();
}
});
it.each(["subscription", "api_key"])("retains only the final subscription snapshot after Codex exits: %s", async mode => {
const fixture = await hostFixture();
let home = "";
@@ -20,6 +20,7 @@ import { bindAcpxAgentFiles } from "./agent-files-binding.js";
import { assertAcpxProfileEnvironment, assertAcpxProfileWorkspace, classifyAcpxProfileError, verifyAcpxProfileInstallation } from "./profile-installation.js";
import { createAcpxRuntimeSkillLease } from "./runtime-skill-lease.js";
import { stageManagedGrokCredential } from "./grok-credentials.js";
import { supportsAcpxCredentialFile, validateCodexAuthDocument } from "./credential-file.js";
import { stageManagedAntigravityCredential } from "./antigravity-credentials.js";
import { claudeNativeSkillPrompt } from "./native-skill-prompt.js";
import { prepareStdioMcpBindings } from "../stdio-mcp.js";
@@ -304,7 +305,7 @@ export interface OpenAcpxRuntimeHostOptions {
systemInstructions?: string;
runtimeContext?: NativeRuntimeContextSnapshot | null;
environment?: NodeJS.ProcessEnv;
managedCodexCredentialSourcePath?: string;
managedCredentialSourcePath?: string;
expectedIdentity?: AcpxExpectedSessionIdentity;
/** Revalidate a pinned recovery workspace through provider admission. */
assertWorkspaceHeld?: () => void;
@@ -450,11 +451,11 @@ export class AcpxRuntimeHost {
}
options.assertWorkspaceHeld?.();
if (
options.agent !== "codex" &&
options.managedCodexCredentialSourcePath !== undefined
options.managedCredentialSourcePath !== undefined &&
!supportsAcpxCredentialFile(options.agent)
) {
throw new Error(
"Managed Codex credentials require the Codex ACPX profile",
"Managed credential files require the Codex or Grok ACPX profile",
);
}
@@ -556,11 +557,15 @@ export class AcpxRuntimeHost {
const lease = await (dependencies.stageCredential ?? stageManagedCodexCredential)({
agentHomeDirectory: sandbox.agentHomeDirectory,
environment: options.environment,
sourcePath: options.managedCodexCredentialSourcePath,
...(options.managedCredentialSourcePath === undefined ? {} : {
sourcePath: options.managedCredentialSourcePath,
validateDocument: validateCodexAuthDocument,
}),
});
return retainAcpxCredentialRefresh({
lease, agentHomeDirectory: sandbox.agentHomeDirectory,
retainRefresh: () => admissionSucceeded && lease.mode !== "api_key",
retainRefresh: () => (admissionSucceeded || options.managedCredentialSourcePath !== undefined) && lease.mode !== "api_key",
keepPreviousRefresh: options.managedCredentialSourcePath !== undefined,
});
},
resource: "credential",
@@ -579,7 +584,9 @@ export class AcpxRuntimeHost {
} else if (options.agent === "grok") {
credential = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => stageManagedGrokCredential({ agentHomeDirectory: sandbox.agentHomeDirectory, environment: options.environment, retainRefresh: () => admissionSucceeded }),
acquire: () => stageManagedGrokCredential({ agentHomeDirectory: sandbox.agentHomeDirectory, environment: options.environment,
sourcePath: options.managedCredentialSourcePath,
retainRefresh: () => admissionSucceeded || options.managedCredentialSourcePath !== undefined }),
resource: "credential", releaseLate: (lease) => lease.close(),
reportFailure: (failure) => dependencies.reportRetainedCleanupFailure(failure),
});
@@ -3253,6 +3253,24 @@ it.each([
},
);
it.each([
["codex", undefined, null], ["grok", undefined, null], ["claude", undefined, "require the Codex or Grok ACPX profile"],
["codex", "PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET", "ambiguous"], ["codex", "OPENAI_API_KEY", "ambiguous"],
["codex", "CODEX_API_KEY", "ambiguous"], ["grok", "PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "ambiguous"], ["grok", "XAI_API_KEY", "ambiguous"],
] as const)("checks a %s host credential file beside %s before filtering", (agent, conflicting, error) => {
const prepare = () => createCapabilityRunnerdProviderEnvironment({
provider: "acpx",
options: { provider: "acpx", acpxAgent: agent, environment: {
PATH: "/bin", PAPERCLIP_ACPX_AUTH_JSON_FILE: "/host/auth.json", ...(conflicting ? { [conflicting]: "conflicting-canary" } : {}),
} },
identity: { runnerInstanceId: "runner-1", environmentLeaseId: "lease-1", runId: "run-1", normalizedSessionId: "session-1", turnId: "turn-1", itemId: "item-1" },
codexHome: "/isolated/codex-home", runtimeContextPath: "/isolated/runtime-context.json", hasRuntimeContext: false,
acpxSidecarPath: "/verified/provider-pack/dist/cli/acpx-runtime-sidecar.cjs",
});
if (error) expect(prepare).toThrow(error);
else expect(prepare().PAPERCLIP_ACPX_AUTH_JSON_FILE).toBe("/host/auth.json");
});
it("does not bind ambient candidate credentials from an inherited or caller-supplied marker", () => {
const forged = createAcpxCredentialBinding({ CURSOR_API_KEY: "ambient-secret" }, "cursor", "session-1")!;
vi.stubEnv("CURSOR_API_KEY", "ambient-secret");
@@ -94,6 +94,7 @@ import {
type QualifiedAcpxAgent,
} from "../drivers/acpx/qualified-profiles.js";
import { ACPX_CREDENTIAL_BINDING_ENV, createAcpxCredentialBinding, createSanitizedAcpxSpawnInput } from "../drivers/acpx/environment.js";
import { ACPX_AUTH_JSON_FILE_ENV, assertAcpxCredentialFileAdmissible } from "../drivers/acpx/credential-file.js";
import {
createSanitizedAwsAgentCoreEnvironment,
createSanitizedClaudeManagedEnvironment,
@@ -3956,6 +3957,7 @@ function createCapabilityRunnerdProviderEnvironmentBase(input: {
const credentialBinding = createAcpxCredentialBinding(
input.options.environment, input.options.acpxAgent ?? "codex", input.identity.normalizedSessionId,
);
const credentialFile = assertAcpxCredentialFileAdmissible(input.options.environment, input.options.acpxAgent ?? "codex");
return {
...createSanitizedAcpxSpawnInput(
input.options.environment,
@@ -3964,6 +3966,7 @@ function createCapabilityRunnerdProviderEnvironmentBase(input: {
...(credentialBinding === undefined ? {} : { [ACPX_CREDENTIAL_BINDING_ENV]: credentialBinding }),
...(input.options.acpxAgent === "grok" && input.options.environment?.PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET
? { PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET: input.options.environment.PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET } : {}),
...(credentialFile === undefined ? {} : { [ACPX_AUTH_JSON_FILE_ENV]: credentialFile }),
...(input.options.acpxAgent === "antigravity" && input.options.environment?.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET
? { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: input.options.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET } : {}),
...commonIdentity,
@@ -255,6 +255,7 @@ describe("resolveExecutionRunAdapterConfig", () => {
PAPERCLIP_API_KEY: { type: "secret_ref", secretId: "secret-api-key", version: "latest" },
PAPERCLIP_CLOUD_PROVIDER_TOKEN_AGENT: "agent-cloud",
PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME: "/agent/claude",
PAPERCLIP_ACPX_AUTH_JSON_FILE: "/agent/auth.json",
AGENT_ONLY: "agent-only",
},
},
@@ -245,6 +245,7 @@ const FORBIDDEN_ENV_BINDING_KEYS = new Set([
"PAPERCLIP_RUNNER_NETWORK_ACCESS",
"PAPERCLIP_RUNNER_NETWORK_ROOTS",
"PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME",
"PAPERCLIP_ACPX_AUTH_JSON_FILE",
"PAPERCLIP_API_KEY",
"PAPERCLIP_GITHUB_AUTH_MODE",
"PAPERCLIP_GITHUB_HOST_HOME",
@@ -21391,6 +21391,7 @@ describe("runnerd provider runtime wiring", () => {
PAPERCLIP_WORKSPACE_CWD: "/untrusted/configured-workspace",
PAPERCLIP_RUNNER_EXTERNAL_SANDBOX: "1",
PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME: "/untrusted/claude",
PAPERCLIP_ACPX_AUTH_JSON_FILE: "/untrusted/auth.json",
},
});
@@ -21411,6 +21412,7 @@ describe("runnerd provider runtime wiring", () => {
localTransportOptions.environment.PAPERCLIP_RUNNER_EXTERNAL_SANDBOX,
).toBeUndefined();
expect(localTransportOptions.environment.PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME).toBeUndefined();
expect(localTransportOptions.environment.PAPERCLIP_ACPX_AUTH_JSON_FILE).toBeUndefined();
});
it("atomically migrates legacy unscoped state only for its exact durable run identity", async () => {
@@ -18877,6 +18877,7 @@ async function createRunnerdBackendWithinSessionClaim(
delete effectiveRunnerEnvironmentBase.PAPERCLIP_RUNNER_EXTERNAL_SANDBOX;
delete effectiveRunnerEnvironmentBase.PAPERCLIP_RUNNER_HOME_MODE;
delete effectiveRunnerEnvironmentBase.PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME;
delete effectiveRunnerEnvironmentBase.PAPERCLIP_ACPX_AUTH_JSON_FILE;
if (preconfiguredHome) {
if (remoteCommandRunner) {
const home = await readRemoteUserHome(remoteCommandRunner);