Files
PaperClipAI/server/src/__tests__/redact-sensitive.test.ts
T
DottaandPaperclip 57bd302c81 feat(antigravity): add hosted Google loopback-relay sign-in (#22932)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Google Antigravity supports Google account sign-in through Paperclip
Runner's pinned, isolated `agy_acp_server.par` process.
> - On `authenticated + public` deployments (including hosted Cloud
instances), `supportsLocalAiLogin` returns `false`, and the user's
browser cannot directly reach the server's `127.0.0.1:<ephemeral_port>`
loopback callback listener.
> - Because `client_secret` lives only inside `agy_acp_server.par` and
uses PKCE with a one-shot `127.0.0.1` listener, hosted deployments need
an authenticated relay path instead of an anonymous callback route or
extracted secret.
> - This pull request adds an authenticated loopback-relay flow across
Runner, server policy/routes/redaction, and the UI so users on hosted
deployments can sign in with Google, copy the `127.0.0.1` redirect URL
from their address bar, and paste it to complete authentication.
> - The benefit is that Google Antigravity subscription sign-in works on
hosted public deployments while keeping Claude, OpenAI, and Grok
server-host login disabled and preventing SSRF, secret leakage, or
cross-tenant access.

## Linked Issues or Issue Description

Refs #22923

**Subsystem affected**
Cross-cutting (packages/paperclip-runner, packages/shared, server/, ui/)

**Problem or motivation**
Google Antigravity sign-in launches Paperclip's pinned, isolated
`agy_acp_server.par` closure, which opens a one-shot
`127.0.0.1:<ephemeral_port>` OAuth callback listener. On hosted
`authenticated + public` deployments, server-host login routes are
blocked and the user's browser cannot connect to the server's loopback
interface, so users cannot sign in with a Google account on Cloud or
remote instances.

**Proposed solution**
Add an authenticated loopback-relay flow:
1. Runner exposes a single-use `submitRedirect(rawRedirectUrl)` handler
on `AntigravityBrowserLoginState` that validates the pasted URL (length,
printable ASCII, `http://127.0.0.1:<expectedPort>/`, no
credentials/hash, no duplicate `state`/`code`, no `error` param,
`timingSafeEqual` state check, bounded 5-attempt bad-paste cap, SHA-256
reused-code tracking) and issues an SSRF-proof reconstructed `GET` to
`expectedRedirect.origin` with `redirect: "manual"`.
2. Server adds `supportsHostedGoogleAiLogin` (exposed on `/api/health`
as `hostedGoogleAiLoginSupported`), permits Google through the
authenticated `/api/companies/:companyId/ai-connections/local/*` routes
while keeping `anthropic`/`openai`/`xai` blocked on public deployments,
accepts up to 4096-character redirect URLs on `/code` while preserving
Claude's 512-byte limit, runs the loopback relay outside DB
transactions, falls back cleanly when a stack has no active `local`
environment row, and redacts `browserCode`/`redirectUrl` and marks
`/code` secret-sensitive.
3. UI enables Google sign-in for `antigravity_runtime` on non-local
environments when `hostedGoogleAiLoginSupported` is true, renders the
external Google sign-in link plus plain-language `127.0.0.1` copy/paste
instructions with analytics masking/no-capture markers, and triggers an
immediate status check after submission.

**Alternatives considered**
- Adding an anonymous public OAuth callback route on the server:
rejected because it widens the unauthenticated attack surface and cannot
change the loopback `redirect_uri` bound inside `agy_acp_server.par`.
- Extracting Google OAuth `client_secret` out of `agy_acp_server.par`:
rejected by policy; secrets remain owned solely inside the pinned
closure.

## What Changed

- `packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts` &
`packages/paperclip-runner/src/index.ts` &
`server/src/vendor/paperclip-runner/index.ts`: add single-use
`submitRedirect` on `AntigravityBrowserLoginState` with strict
validation, `timingSafeEqual` state verification, 5-attempt cap, bounded
SHA-256 reused-code set, and SSRF-proof loopback relay.
- `packages/shared/src/ai-connections.ts`: add
`LOCAL_AI_LOGIN_CODE_MAX_LENGTH` (4096), `localAiLoginCodeSchema`, and
`submitLocalAiLoginCodeSchema` while preserving Claude's 512-byte
`BROWSER_CODE_MAX_LENGTH` and `browserCodeSchema`.
- `server/src/services/local-ai-login-policy.ts` &
`server/src/routes/health.ts`: add `supportsHostedGoogleAiLogin` and
expose `hostedGoogleAiLoginSupported` on `/api/health`.
- `server/src/services/local-ai-browser-login.ts`,
`server/src/services/local-ai-login.ts`,
`server/src/routes/ai-connections.ts`: permit hosted Google sign-in on
authenticated public deployments while keeping Claude/OpenAI/Grok
blocked; enforce `Cache-Control: no-store`, owner/company/active/expiry
checks, and Claude's 512-byte cap; run Google `submitRedirect` outside
any DB transaction; fall back cleanly to an active environment or
savepoint-wrapped `ensureLocalEnvironment` when no active `local`
environment row exists.
- `server/src/middleware/redact-sensitive.ts`,
`server/src/middleware/http-log-redaction.ts`,
`server/src/middleware/http-log-policy.ts`: redact
`browserCode`/`redirectUrl`/`redirect_url` unconditionally and classify
`/api/companies/:companyId/ai-connections/local/attempts/:sessionId/code`
as secret-sensitive (`local_ai_login_code`).
- `ui/src/api/health.ts`,
`ui/src/components/ai-connections/useLocalAiLogin.ts`,
`ui/src/components/AdapterLoginChrome.tsx`,
`ui/src/components/new-agent/AgentProviderConnection.tsx`,
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`,
`ui/src/components/OnboardingWizard.tsx`: enable hosted Google sign-in
for `antigravity_runtime` on hosted/non-local environments, render the
hosted `127.0.0.1` redirect paste flow with `ANALYTICS_MASK_CLASS` and
`ANALYTICS_NO_CAPTURE_CLASS`, preserve retryable paste errors inline,
and trigger immediate status re-check on submit.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
updated `packages/shared/src/ai-connections.ts` schema.
- Unit, integration, and UI tests across `antigravity-auth.test.ts`,
`local-ai-login-policy.test.ts`, `health.test.ts`,
`health-dev-server-token.test.ts`, `redact-sensitive.test.ts`,
`http-log-policy.test.ts`, `antigravity-local-ai-login.test.ts`,
`ai-connections.test.ts`, `AdapterLoginChrome.test.tsx`,
`useLocalAiLogin.test.tsx`, and `AgentProviderConnection.test.tsx`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter
@paperclipai/paperclip-runner typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/validators/claude-setup-token-session.test.ts` — 15/15 passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-auth-stream-order.test.ts` — 33/33 passed
(including real `127.0.0.1` loopback HTTP relay with fake ACP peer,
bad-paste cap, reused-code rejection, single-use, and non-200 failure).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/local-ai-login-policy.test.ts src/__tests__/health.test.ts
src/__tests__/health-dev-server-token.test.ts
src/__tests__/redact-sensitive.test.ts
src/__tests__/http-log-policy.test.ts
src/__tests__/antigravity-local-ai-login.test.ts` — all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/ai-connections.test.ts` — 167/167 passed against embedded
PostgreSQL (including hosted Google end-to-end route test, redaction of
activity and HTTP logs, and continued blocking of Anthropic/OpenAI/xAI
on hosted public deployments).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/AdapterLoginChrome.test.tsx
src/components/ai-connections/useLocalAiLogin.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` — 30/30
passed.
- `pnpm verify --explain` returned exit 2
(`tests/runner-e2e/source-sdk-public-inputs.json` broad input); required
CI supplies full-repo coverage.
- Note: live end-to-end sign-in against real `agy_acp_server.par` and
Google OAuth on a live Cloud stack was not run in this unit/integration
environment and remains a live-staging verification step.

## Risks

- Low-to-moderate risk. All hosted Google sign-in endpoints stay
authenticated, company-scoped, owner-bound, and `Cache-Control:
no-store`; `localAiLoginSupported` remains `false` on `authenticated +
public` deployments so Claude, OpenAI, and Grok server-host login stay
blocked.
- Loopback relay runs strictly against the validated
`127.0.0.1:<ephemeral_port>` origin printed by `agy_acp_server.par` with
`redirect: "manual"` and a 5-second timeout, outside any database
transaction.
- No database migrations are required.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## 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-11-25 07:36:36 -06:00

307 lines
11 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
collectSensitiveStringValues,
redactSensitive,
redactSensitiveValueOccurrences,
stripSecretBearingUrlParts,
} from "../middleware/redact-sensitive.js";
it("redacts Slack manager grants and sealed OAuth handoffs", () => {
const result = redactSensitive({ managerToken: "manager-canary", refreshToken: "refresh-canary", sealed: { ct: "sealed-canary" }, handoff: { token: "handoff-canary" }, claim_id: "claim-canary" });
expect(JSON.stringify(result)).not.toContain("canary");
});
describe("redactSensitive", () => {
it("redacts a plaintext password field on a sign-in body", () => {
const body = {
email: "user@example.com",
password: "founding6gomez6croaking",
};
const out = redactSensitive(body) as Record<string, unknown>;
expect(out.email).toBe("user@example.com");
expect(out.password).toBe("[REDACTED]");
expect((body as Record<string, unknown>).password).toBe(
"founding6gomez6croaking",
);
});
it("redacts password key regardless of casing", () => {
expect(
(redactSensitive({ Password: "x" }) as Record<string, unknown>).Password,
).toBe("[REDACTED]");
expect(
(redactSensitive({ PASSWORD: "x" }) as Record<string, unknown>).PASSWORD,
).toBe("[REDACTED]");
});
it("redacts known credential-shaped keys", () => {
const out = redactSensitive({
currentPassword: "a",
newPassword: "b",
access_token: "c",
refresh_token: "d",
api_key: "e",
authorization: "Bearer f",
}) as Record<string, string>;
for (const value of Object.values(out)) {
expect(value).toBe("[REDACTED]");
}
});
it("drops provider credential envelopes and redacts provider keys outside them", () => {
const out = redactSensitive({
credentials: {
botToken: "nested-bot-canary",
futureCredential: "nested-future-canary",
},
botToken: "bot-canary",
signing_secret: "signing-canary",
webhookSecret: "webhook-canary",
app_secret: "app-canary",
applicationSecret: "application-canary",
}) as Record<string, unknown>;
expect(out).toEqual({
credentials: "[REDACTED]",
botToken: "[REDACTED]",
signing_secret: "[REDACTED]",
webhookSecret: "[REDACTED]",
app_secret: "[REDACTED]",
applicationSecret: "[REDACTED]",
});
expect(JSON.stringify(out)).not.toContain("canary");
});
it("removes raw, JSON-escaped, and URL-encoded submitted credentials from prose", () => {
const credential = "secret value/with\nnewline";
const submittedValues = collectSensitiveStringValues({
action: "configure",
credentials: { botToken: credential },
});
const out = redactSensitiveValueOccurrences(
{
raw: `Provider rejected ${credential}`,
json: `Provider rejected ${JSON.stringify(credential).slice(1, -1)}`,
url: `Provider rejected ${encodeURIComponent(credential)}`,
form: `Provider rejected ${encodeURIComponent(credential).replaceAll("%20", "+")}`,
scopes: ["chat:write", "reactions:write"],
},
submittedValues,
);
expect(JSON.stringify(out)).not.toContain("secret value");
expect(JSON.stringify(out)).not.toContain("secret%20value");
expect(out).toMatchObject({ scopes: ["chat:write", "reactions:write"] });
});
it("sanitizes malformed UTF-16 credential values without throwing", () => {
const malformedCredential = "\ud800";
expect(() =>
redactSensitiveValueOccurrences(
`Provider rejected ${malformedCredential}`,
[malformedCredential],
),
).not.toThrow();
expect(
redactSensitiveValueOccurrences(
`Provider rejected ${malformedCredential}`,
[malformedCredential],
),
).toBe("Provider rejected [REDACTED]");
});
it("removes a normalized provider echo of a whitespace-padded credential", () => {
expect(
redactSensitiveValueOccurrences("Provider rejected padded-token-canary", [
" padded-token-canary \n",
]),
).toBe("Provider rejected [REDACTED]");
});
it("redacts an OAuth provider's error_description and error_uri from a callback query", () => {
const out = redactSensitive({
state: "paperclip-state",
error: "access_denied",
error_description:
"\u001b[31mPaste your recovery key\u001b[0m sk-live-canary",
error_uri: "https://attacker.example/explain?leak=sk-live-canary",
}) as Record<string, unknown>;
// The `error` code is Paperclip's one allowlisted label, so it stays legible
// in logs; the provider's prose does not.
expect(out.error).toBe("access_denied");
expect(out.state).toBe("paperclip-state");
expect(out.error_description).toBe("[REDACTED]");
expect(out.error_uri).toBe("[REDACTED]");
expect(JSON.stringify(out)).not.toContain("sk-live-canary");
expect(JSON.stringify(out)).not.toContain("\\u001b");
});
it("redacts bare value and token fields recursively", () => {
const out = redactSensitive({
token: "secret-token",
nested: { value: "secret-value" },
entries: [{ value: "array-secret" }],
limit: 20,
}) as Record<string, unknown>;
expect(out.token).toBe("[REDACTED]");
expect((out.nested as Record<string, unknown>).value).toBe("[REDACTED]");
expect((out.entries as Array<Record<string, unknown>>)[0].value).toBe(
"[REDACTED]",
);
expect(out.limit).toBe(20);
expect(JSON.stringify(out)).not.toMatch(
/secret-token|secret-value|array-secret/,
);
});
it("strips secret-bearing query and fragment values from source URLs", () => {
const out = redactSensitive({
source: "https://github.com/acme/private-skill?token=secret#token=secret",
}) as Record<string, unknown>;
expect(out.source).toBe("https://github.com/acme/private-skill");
});
it("recurses into nested objects and arrays", () => {
const out = redactSensitive({
user: { email: "user@example.com", password: "secret-pass" },
tokens: [{ access_token: "t1" }, { access_token: "t2" }],
}) as Record<string, unknown>;
expect((out.user as Record<string, unknown>).email).toBe(
"user@example.com",
);
expect((out.user as Record<string, unknown>).password).toBe("[REDACTED]");
const tokens = out.tokens as Array<Record<string, unknown>>;
expect(tokens[0].access_token).toBe("[REDACTED]");
expect(tokens[1].access_token).toBe("[REDACTED]");
});
it("leaves primitives and non-sensitive keys untouched", () => {
const body = {
email: "a@b.c",
name: "Alice",
count: 7,
active: true,
missing: null,
};
expect(redactSensitive(body)).toEqual(body);
});
it("returns primitives unchanged", () => {
expect(redactSensitive("hello")).toBe("hello");
expect(redactSensitive(42)).toBe(42);
expect(redactSensitive(null)).toBe(null);
expect(redactSensitive(undefined)).toBe(undefined);
});
it("caps recursion depth so cycles do not pin the logger", () => {
const cycle: Record<string, unknown> = { name: "root" };
cycle.self = cycle;
expect(() => redactSensitive(cycle)).not.toThrow();
});
it("omits deeply-nested arrays at the depth cap instead of leaking null entries to JSON", () => {
// Build an object whose array field is reached at MAX_DEPTH. Recursing
// into the array elements would exceed the cap; without the array-level
// guard, `value.map` would produce `[undefined, ...]` which JSON.stringify
// renders as `[null, ...]`. Object properties at the same cap are
// already absent from the JSON output (JSON.stringify skips undefined
// values on objects), so this test pins the array path to the same
// contract: silently absent, not visible as nulls.
let payload: Record<string, unknown> = { values: [1, 2, 3] };
for (let i = 0; i < 5; i++) payload = { nested: payload };
const out = redactSensitive(payload);
const json = JSON.stringify(out);
expect(json).not.toContain("null");
expect(json).not.toContain("[1,2,3]");
});
});
describe("stripSecretBearingUrlParts", () => {
it("redacts the connector credentialValues envelope on an app-connect body", () => {
const out = redactSensitive({
galleryKey: "github",
name: "GitHub",
credentialValues: {
"credentials.authorization": "authorization-canary",
"headers.X-Api-Key": "header-canary",
},
}) as Record<string, unknown>;
// Diagnostics that make the failed connect debuggable must survive.
expect(out.galleryKey).toBe("github");
expect(out.name).toBe("GitHub");
expect(out.credentialValues).toBe("[REDACTED]");
expect(JSON.stringify(out)).not.toContain("canary");
});
it("redacts a credentialValues envelope nested below the top level", () => {
const out = redactSensitive({
connection: {
credentialValues: { "credentials.authorization": "nested-canary" },
},
});
expect(JSON.stringify(out)).not.toContain("nested-canary");
});
it("keeps a request path legible while dropping its complete query and fragment", () => {
expect(
stripSecretBearingUrlParts(
"/api/tools/oauth/callback?code=authorization-code&error_description=provider-prose#fragment",
),
).toBe("/api/tools/oauth/callback");
});
});
it("redacts Grok routine URL and key in setup failure logs", () => {
const payload = { webhookUrl: "https://bot.example/routine/url-canary", webhookKey: "key-canary" };
expect(JSON.stringify(redactSensitive(payload))).not.toContain("canary");
expect(collectSensitiveStringValues(payload)).toContain(payload.webhookUrl);
expect(collectSensitiveStringValues(payload)).toContain(payload.webhookKey);
});
it("redacts hosted Google redirect URLs and browser codes unconditionally", () => {
const payload = {
browserCode: "http://127.0.0.1:41234/?state=state-canary&code=code-canary",
redirectUrl: "http://127.0.0.1:41234/?state=state-canary-2&code=code-canary-2",
redirect_url: "http://127.0.0.1:41234/?state=state-canary-3&code=code-canary-3",
};
const redacted = redactSensitive(payload) as Record<string, unknown>;
expect(redacted).toEqual({
browserCode: "[REDACTED]",
redirectUrl: "[REDACTED]",
redirect_url: "[REDACTED]",
});
expect(JSON.stringify(redacted)).not.toContain("canary");
expect(collectSensitiveStringValues(payload)).toContain(payload.browserCode);
expect(collectSensitiveStringValues(payload)).toContain(payload.redirectUrl);
});
describe("invitation bearer URL paths", () => {
it.each([
["/api/invites/invite-bearer-canary/accept?token=query-canary", "/api/invites/[REDACTED]/accept"],
["/invites/invite-bearer-canary/onboarding.txt", "/invites/[REDACTED]/onboarding.txt"],
["/invite/invite-bearer-canary", "/invite/[REDACTED]"],
["/API/INVITES/encoded%2Fbearer/skills/paperclip", "/API/INVITES/[REDACTED]/skills/paperclip"],
["https://user:password@board.example/api/invites/invite-bearer-canary/accept#fragment", "https://board.example/api/invites/[REDACTED]/accept"],
["/api/invites/invite-record-id/revoke", "/api/invites/invite-record-id/revoke"],
["/invites/invite-record-id/revoke/", "/invites/invite-record-id/revoke/"],
["/invite/invite-bearer-canary/revoke", "/invite/[REDACTED]/revoke"],
["/api/companies/company/invites/invite-record-id", "/api/companies/company/invites/invite-record-id"],
])("sanitizes %s without hiding the route", (input, expected) => {
expect(stripSecretBearingUrlParts(input)).toBe(expected);
});
});