Files
PaperClipAI/server/src/services/native-runtime/plugin-runner-credentials.test.ts
T
DottaandPaperclip cfe5042378 fix(opencode): fix API key env/secret resolution and support Antigravity connector (#23387)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent setup, environment testing, and managed AI connections pass
provider API keys into the OpenCode adapter and Paperclip Runner
> - OpenCode setup failed with `Secret not found` when a user supplied a
direct Gemini API key alongside a stale or auto-selected secret binding,
and the OpenCode runtime reported `GOOGLE_GENERATIVE_AI_API_KEY` missing
because Paperclip only passed `GEMINI_API_KEY` and limited OpenCode to
OpenRouter credentials
> - Users need reliable direct provider API keys and Google/Antigravity
API-key connectors across legacy OpenCode, native Paperclip Runner, and
Plugin Runner environments without exposing raw keys to child tool
shells
> - This pull request strips probe-overridden secret references
(including symmetric Google key aliases) before secret resolution,
prioritizes pasted API keys in setup, routes direct OpenCode provider
credentials through a runner-owned loopback proxy, and enables API-key
AI connections (including the Google / Antigravity connector) for
`opencode_local`
> - The benefit is that OpenCode agents test and run reliably with
direct provider keys or connected Google/Antigravity API keys without
false `Secret not found`, missing `GOOGLE_GENERATIVE_AI_API_KEY` errors,
or raw key leaks into child environments

## Linked Issues or Issue Description

- Fixes: #23359
- Refs #23370 (related community fix by @dev-787 for the initial Gemini
API key issue)

## What Changed

- **Server test-environment secret stripping and inheritance
(`server/src/routes/agents.ts`)**: Strip any credential key supplied in
`testCredentials` (including the symmetric `GEMINI_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` pair and `hermes_gateway` `apiKey`) from
both `adapterConfig` and resolved environment `envVars` before secret
persistence normalization and runtime resolution. Scope `opencode_local`
inheritable credential groups from `@paperclipai/shared`
(`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS`), skip inheritance when the
child supplies any OpenCode credential, and isolate multi-provider
parents to one matching provider group.
- **UI setup credential precedence (`ui/src/lib/provider-credential.ts`,
`ui/src/components/new-agent/NewAgentSetup.tsx`)**: Prefer an explicitly
entered raw API key over an auto-selected organization or personal
secret, and clear stale provider secret bindings and Google alias keys
when switching credentials or providers.
- **OpenCode direct provider keys and Gemini aliasing
(`packages/adapters/opencode-local/`, `packages/adapter-utils/`)**:
Mirror non-empty `GEMINI_API_KEY` into `GOOGLE_GENERATIVE_AI_API_KEY`
during OpenCode runtime config preparation and model discovery while
preserving blank managed isolation. Register `google`, `xai`, `groq`,
and `opencode` API key names in `api-billing-type`.
- **Runner-owned loopback credential proxy and allowlist parity
(`packages/paperclip-runner/`, `packages/plugins/sdk/`,
`packages/shared/`)**: Export canonical
`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS` and
`OPENCODE_CREDENTIAL_ENV_KEYS` from `@paperclipai/shared`. Route direct
OpenCode provider API keys (`google`, `anthropic`, `openai`, `xai`,
`groq`, `opencode`) through a runner-owned loopback proxy
(`packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts`)
with per-session bearer tokens, model-pinned endpoint allowlists, native
upstream auth header injection, request secret redaction, and redirect
refusal so raw keys never enter `opencode serve` child environments or
`opencode.json`. Allow direct provider keys across TypeScript, Rust, and
Plugin SDK allowlists, reserve `GOOGLE_API_KEY` and `GROK_API_KEY` in
TS/Rust configured-environment projections, strip ambient provider keys
(including `OPENROUTER_API_KEY`) from sanitized OpenCode runner
environments unless explicitly supplied, and redact provider keys in
output custody.
- **Antigravity / multi-provider API-key AI connections for OpenCode
(`packages/shared/`, `server/src/services/`,
`ui/src/components/ai-connections/`)**: Enable `api_key` AI connections
for `google` (Antigravity catalog slug), `anthropic`, `openai`, and
`xai` on `opencode_local` (keeping OAuth `subscription` methods
excluded), enforce provider-to-model prefix compatibility, mirror
`GEMINI_API_KEY` to `GOOGLE_GENERATIVE_AI_API_KEY` in
`prepareManagedAiRuntime`, isolate project config with
`OPENCODE_DISABLE_PROJECT_CONFIG=true`, and scope child-auth override
detection in `agent-ai-connection-default.ts` to non-empty OpenCode
credentials (supporting plain values, `secret_ref.secretId`, and
`user_secret_ref.key`).
- **Tests and pinned input registry**: Added unit, route, cross-layer
allowlist parity, and pinned `opencode@1.18.34` `bash`-tool credential
isolation tests across `adapter-utils`, `adapter-opencode-local`,
`paperclip-runner`, `server`, and `ui`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `@paperclipai/adapter-utils`: `src/api-billing-type.test.ts` (17/17
tests), `typecheck`, `build` — passed
- `@paperclipai/adapter-opencode-local`:
`src/server/runtime-config.test.ts`, `src/server/models.test.ts`,
`typecheck`, `build` — passed
- `@paperclipai/shared`: full suite (123/123 files, 1426/1426 tests),
`typecheck`, `build` — passed
- `@paperclipai/paperclip-runner`: `typecheck:typescript`,
`build:typescript`, `check:package-boundaries`,
`opencode-server-driver.test.ts` (101/101 including pinned
`opencode@1.18.34` `bash`-tool test), `output-custody.test.ts` (13/13),
`configured-environment.test.ts` (35/35),
`antigravity-credentials.test.ts` (11/11), and
`durable-prp-control-plane.test.ts` — passed
- `@paperclipai/server`: `typecheck` and targeted suites
(`ai-connections.test.ts` 170/170, `agent-hire-ai-connections.test.ts`
84/84, `agent-test-environment-routes.test.ts` 72/72,
`agent-hire-auth-inheritance-routes.test.ts` 29/29,
`plugin-runner-credentials.test.ts` 43/43,
`plugin-runner-credential-names.test.ts` 6/6 cross-layer TS/Rust parity,
`opencode-local-adapter-environment.test.ts` 4/4,
`ai-auth-failure.test.ts` 32/32, `ai-provider-routing.test.ts` 21/21,
`antigravity-runner-credentials.test.ts`) — passed
- `@paperclipai/ui`: `typecheck`, `provider-credential.test.ts`,
`AiConnectionSelect.test.tsx` (20/20 tests) — passed
- `@paperclipai/plugin-sdk`: `build`, `environment-tasks.test.ts`,
`environment-task-release-resume.test.ts` (104/104) — passed on
`03dc341957`
- `@paperclipai/paperclip-runner`: `provider-traffic.test.ts` &
`provider-traffic-proxy.test.ts` alongside OpenCode/Antigravity/custody
suites (169/169) — passed on `03dc341957`
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
03dc341957 --check` — passed (`changed:
false`, 602 inputs)
- GitHub CI on `03dc341957`: all 95 checks green (`MERGEABLE` / `CLEAN`)
— `ci / verify` ([run
47315344108](https://github.com/paperclipai/paperclip/actions/runs/47315344108)),
`ci / e2e`, `Verify Paperclip Runner` (static checks, Rust, Vitest
package & native server suites), `Runner Windows` ([run
47315343800](https://github.com/paperclipai/paperclip/actions/runs/47315343800)),
`Runner image` (`amd64` + `arm64`, [run
47315343840](https://github.com/paperclipai/paperclip/actions/runs/47315343840)),
`macOS OpenCode SSH runtime` ([run
47315343817](https://github.com/paperclipai/paperclip/actions/runs/47315343817)),
`Verify serialized server suites` (1/9–9/9), `Superagent Security Scan`,
`Greptile Review` (5/5), `Paperclip Review` (5/5), `Socket Security`,
and `security/snyk` passed.
- Local verification gap: `cargo` is not installed in this container;
Rust checks (`typecheck:rust` / `test:rust`) ran and passed in GitHub CI
(`verify_paperclip_runner`).

## Risks

- Low to moderate risk. No database schema or migration changes are
included.
- Touches provider credential allowlists in both TypeScript and Rust
(`codex_provider.rs`, `configured_environment.rs`), the runner-owned
loopback proxy for direct OpenCode providers, and secret-stripping logic
in `POST /companies/:companyId/adapters/:type/test-environment`. Parity
between TypeScript and Rust allowlists is enforced by
`plugin-runner-credential-names.test.ts`, and Rust build/test checks
pass in CI.
- `opencode_local` AI connection compatibility enforces that the
selected model prefix matches the connected provider (for example,
`google/...` for a Google/Antigravity API-key connection). Existing
`openrouter/...` connections remain compatible.

## Model Used

- Google Gemini (Antigravity agent runtime) with reasoning, repository
code navigation, shell execution, and automated test verification.

## 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
- [ ] 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-04 12:20:32 -06:00

218 lines
16 KiB
TypeScript

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";
import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js";
const homes: string[] = [];
afterEach(async () => { await Promise.all(homes.splice(0).map(home => rm(home, { recursive: true, force: true }))); });
async function home(auth: object) {
const directory = await mkdtemp(join(tmpdir(), "plugin-runner-account-")); homes.push(directory);
await writeFile(join(directory, "auth.json"), JSON.stringify(auth), { mode: 0o600 });
return directory;
}
const auth = { tokens: { account_id: "fixture-account", access_token: "fixture-access", refresh_token: "fixture-refresh" }, last_refresh: "2020-01-01T00:00:00Z" };
describe("plugin Runner selected credentials", () => {
it("sends the selected Codex account and preserves a newer refresh for normal secret writeback", async () => {
const directory = await home(auth);
const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} });
expect(transfer.accountIdentity).toBe("account");
expect(transfer.writeback?.mode).toBe("live");
expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify(auth) });
const refreshed = { ...auth, tokens: { ...auth.tokens, refresh_token: "fixture-rotated" }, last_refresh: "2021-01-01T00:00:00Z" };
await transfer.onCredentials!({ type: "auth-file", provider: "codex", content: JSON.stringify(refreshed) });
expect(JSON.parse(await readFile(join(directory, "auth.json"), "utf8"))).toEqual(refreshed);
});
it("transfers a selected API key without requiring refresh authority", async () => {
const directory = await home({ OPENAI_API_KEY: "fixture-key" });
const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} });
expect(transfer.writeback).toBeUndefined();
expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify({ OPENAI_API_KEY: "fixture-key" }) });
});
it("transfers only the selected Claude authentication variable", async () => {
const transfer = await preparePluginRunnerCredentials({ provider: "claude", identity: "revision", environment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-oauth", HOME: "/controller/private", OTHER_SECRET: "fixture-unrelated" } });
expect(transfer.credential).toEqual({ type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-oauth" } });
await expect(preparePluginRunnerCredentials({ provider: "claude", identity: "revision", environment: { ANTHROPIC_API_KEY: "fixture-key", ANTHROPIC_BASE_URL: "https://router.example.test" } })).rejects.toThrow("routing");
});
it("does not read a controller credential when the provider owns the account", async () => {
expect(await preparePluginRunnerCredentials({ provider: "codex", home: "/must/not/read", environment: {} })).toEqual({});
await expect(preparePluginRunnerCredentials({ provider: "cursor", identity: "revision", environment: { CURSOR_API_KEY: "fixture-key" } })).rejects.toThrow("credential provider");
});
});
describe("plugin Runner Google Antigravity credentials", () => {
const signIn = (extra: Record<string, unknown> = {}) => 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",
GOOGLE_GEMINI_BASE_URL: "https://router.example.test", GEMINI_HOME: "/controller/private/gemini", XAI_API_KEY: "fixture-xai",
HOME: "/controller/private", OTHER_SECRET: "fixture-unrelated" } });
expect(transfer).toEqual({ accountIdentity: "account", credential: { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } } });
expect(transfer.writeback).toBeUndefined();
expect(transfer.onCredentials).toBeUndefined();
});
it.each([
["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", writeback: { mode: "live", requiresGoogleGeneration: true },
credential: { type: "auth-file", provider: "antigravity", content: saved } });
const delivered = transfer.credential!.type === "auth-file" ? transfer.credential!.content : "";
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.writeback).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(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 () => {
const result = preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", environment: { GEMINI_API_KEY: "fixture\0gemini" } });
await expect(result).rejects.toThrow("Plugin Runner selected credential unavailable");
await result.catch((error: Error) => expect(error.message).not.toContain("fixture"));
});
});
describe("plugin Runner provider environment credentials", () => {
const blanks = { XAI_API_KEY: "", COPILOT_GITHUB_TOKEN: "", OPENROUTER_API_KEY: "", PAPERCLIP_AI_PROVIDER_URL: "", PAPERCLIP_AI_PROVIDER_KEY: "",
ANTHROPIC_API_KEY: "", HOME: "/controller/private", GROK_HOME: "/controller/private/provider", OTHER_SECRET: "fixture-unrelated" };
it.each([
["grok", { XAI_API_KEY: "fixture-xai" }],
["copilot", { COPILOT_GITHUB_TOKEN: "fixture-copilot" }],
["opencode", { OPENROUTER_API_KEY: "fixture-openrouter" }],
["opencode", { GEMINI_API_KEY: "fixture-gemini" }],
["opencode", { GOOGLE_GENERATIVE_AI_API_KEY: "fixture-google-genai" }],
["opencode", { GEMINI_API_KEY: "fixture-gemini", GOOGLE_GENERATIVE_AI_API_KEY: "fixture-gemini" }],
["opencode", { OPENAI_API_KEY: "fixture-openai" }],
["opencode", { ANTHROPIC_API_KEY: "fixture-anthropic" }],
["opencode", { XAI_API_KEY: "fixture-xai" }],
["opencode", { GROQ_API_KEY: "fixture-groq" }],
["opencode", { OPENCODE_API_KEY: "fixture-opencode" }],
["opencode", { PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" }],
["opencode", { PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1", PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture" }],
] as const)("transfers only the selected %s variables", async (provider, environment) => {
const transfer = await preparePluginRunnerCredentials({ provider, identity: "revision", accountIdentity: "account",
environment: { ...blanks, ...environment, OPENCODE_CONFIG_CONTENT: "{\"provider\":{}}" } });
expect(transfer).toEqual({ accountIdentity: "account", credential: { type: "provider-env", provider, environment } });
expect(transfer.writeback).toBeUndefined();
});
it("uses the credential revision as the account when no account identity is supplied", async () => {
const transfer = await preparePluginRunnerCredentials({ provider: "copilot", identity: "revision", environment: { COPILOT_GITHUB_TOKEN: "fixture-copilot" } });
expect(transfer.accountIdentity).toBe("revision");
});
it("keeps the GitHub broker authority beside the provider credential", async () => {
const transfer = await preparePluginRunnerCredentials({ provider: "grok", identity: "revision", environment: {
XAI_API_KEY: "fixture-xai", PAPERCLIP_GITHUB_BROKER_URL: "https://core.example.test", PAPERCLIP_GITHUB_BROKER_TOKEN: "runtime-capability" } });
expect(transfer.githubBroker).toEqual({ url: "https://core.example.test", token: "runtime-capability" });
expect(transfer.credential).toEqual({ type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai" } });
});
it("sends a Grok subscription as its saved sign-in file and requires the managed writeback", async () => {
const grokAuth = { "https://auth.x.ai::00000000-0000-4000-8000-000000000000": { key: "fixture-key", refresh_token: "fixture-refresh" } };
const directory = await home(grokAuth);
const transfer = await preparePluginRunnerCredentials({ provider: "grok", identity: "revision", accountIdentity: "account",
home: directory, environment: blanks });
expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "live" },
credential: { type: "auth-file", provider: "grok", content: JSON.stringify(grokAuth) } });
});
it("refuses a Grok subscription without a usable sign-in file", async () => {
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision", environment: blanks }))
.rejects.toThrow("credential home unavailable");
const directory = await home({ "https://auth.x.ai::00000000-0000-4000-8000-000000000000": { key: "fixture-key" } });
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision", home: directory, environment: blanks }))
.rejects.toThrow("credential invalid");
});
it("refuses Grok provider routing that would redirect the key", async () => {
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision",
environment: { XAI_API_KEY: "fixture-xai", XAI_BASE_URL: "https://router.example.test" } })).rejects.toThrow("routing");
});
it.each([
["copilot", {}],
["opencode", {}],
["opencode", { PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1" }],
["opencode", { PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" }],
["opencode", { OPENROUTER_API_KEY: "fixture-openrouter", PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" }],
["opencode", { GEMINI_API_KEY: "fixture-gemini", OPENAI_API_KEY: "fixture-openai" }],
["opencode", { PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1" }],
["opencode", { PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture" }],
["opencode", { OPENROUTER_API_KEY: "fixture-openrouter", PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1", PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture" }],
["opencode", { OPENROUTER_API_KEY: "fixture\0value" }],
] as const)("fails closed for an incomplete or ambiguous %s credential", async (provider, environment) => {
const result = preparePluginRunnerCredentials({ provider, identity: "revision", environment: { ...blanks, ...environment } });
await expect(result).rejects.toThrow("Plugin Runner selected credential unavailable");
await result.catch((error: Error) => expect(error.message).not.toContain("fixture"));
});
it("transfers Cloud starter-trial OpenRouter proxy credentials for OpenCode even without a managed AI connection identity", async () => {
const transfer = await preparePluginRunnerCredentials({
provider: "opencode",
environment: {
...blanks,
OPENROUTER_API_KEY: "",
PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1",
PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture_token",
},
});
expect(transfer).toEqual({
accountIdentity: "cloud-trial",
credential: {
type: "provider-env",
provider: "opencode",
environment: {
PAPERCLIP_OPENROUTER_PROXY_URL: "https://stack.example.test/api/internal/cloud-inference/v1",
PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_fixture_token",
},
},
});
expect(transfer.writeback).toBeUndefined();
});
});
it("transfers only broker authority even when the provider owns its AI account", async () => {
const result = await preparePluginRunnerCredentials({provider:"codex",home:"/must/not/read",environment:{
PAPERCLIP_GITHUB_BROKER_URL:"https://core.example.test",PAPERCLIP_GITHUB_BROKER_TOKEN:"runtime-capability",
GH_TOKEN:"ambient-secret",PAPERCLIP_API_KEY:"unrelated-key",HOME:"/controller/private"}});
expect(result).toEqual({githubBroker:{url:"https://core.example.test",token:"runtime-capability"}});
});