From 6b06a8963c70333ccd9a562e4fe9e4b8ce5a2264 Mon Sep 17 00:00:00 2001 From: Evan Purkhiser Date: Tue, 17 Nov 2026 10:22:52 -0500 Subject: [PATCH] feat(cli): Support Sentry agent handoff Web handoffs need setup to claim the intended account even when another login is already stored. Exchange the short-lived handoff during the existing setup path, replace the applicable account, and reveal the returned instructions only after authentication succeeds. --- packages/cli/lint-rules/cli-oxlint-plugin.js | 2 + packages/cli/src/commands/cli/setup.ts | 27 ++- packages/cli/src/lib/agent-handoff.ts | 134 +++++++++++++ packages/cli/src/lib/credential-redaction.ts | 4 +- packages/cli/src/lib/env-registry.ts | 5 + packages/cli/src/lib/oauth.ts | 3 +- packages/cli/src/lib/setup-code.ts | 8 +- packages/cli/test/commands/cli/setup.test.ts | 183 +++++++++++++++++- packages/cli/test/lib/agent-handoff.test.ts | 159 +++++++++++++++ .../cli/test/lib/install-ps1-script.test.ts | 7 +- packages/cli/test/lib/install-script.test.ts | 7 +- .../test/lib/telemetry-credentials.test.ts | 14 ++ 12 files changed, 539 insertions(+), 14 deletions(-) create mode 100644 packages/cli/src/lib/agent-handoff.ts create mode 100644 packages/cli/test/lib/agent-handoff.test.ts diff --git a/packages/cli/lint-rules/cli-oxlint-plugin.js b/packages/cli/lint-rules/cli-oxlint-plugin.js index 87f85d4d71..9b71b5b070 100644 --- a/packages/cli/lint-rules/cli-oxlint-plugin.js +++ b/packages/cli/lint-rules/cli-oxlint-plugin.js @@ -499,6 +499,8 @@ const MANUAL_API_REQUEST_EXCEPTIONS = new Map([ ], // Unauthenticated transport for the generated shared-issue call on another host. ["lib/api/issues.ts", ["getSharedIssue"]], + // Unauthenticated transport for the generated handoff claim before login exists. + ["lib/agent-handoff.ts", ["exchangeAgentHandoff"]], // Public status page, not the Sentry API. ["lib/api/status-page.ts", true], // CLI binary downloads from release hosts. diff --git a/packages/cli/src/commands/cli/setup.ts b/packages/cli/src/commands/cli/setup.ts index 86f06b8453..ec608732ba 100644 --- a/packages/cli/src/commands/cli/setup.ts +++ b/packages/cli/src/commands/cli/setup.ts @@ -11,6 +11,7 @@ import { chmod, copyFile, mkdir, rename, unlink } from "node:fs/promises"; import { dirname, join } from "node:path"; import { isatty } from "node:tty"; import type { SentryContext } from "../../context.js"; +import { completeAgentHandoff } from "../../lib/agent-handoff.js"; import { installAgentSkills } from "../../lib/agent-skills.js"; import { sentry } from "../../lib/app-identity.js"; import { assertAutoLoginHostTrusted } from "../../lib/auto-auth.js"; @@ -792,12 +793,24 @@ export const setupCommand = buildCommand({ warn, }); - if (getEnv().SENTRY_SETUP_CODE && !hasStoredAuthCredentials()) { + const { SENTRY_HANDOFF, SENTRY_SETUP_CODE } = getEnv(); + const handoffCode = SENTRY_HANDOFF?.trim(); + const setupCode = SENTRY_SETUP_CODE?.trim(); + const shouldUseSetupCode = + !handoffCode && Boolean(setupCode) && !hasStoredAuthCredentials(); + let afterSetupInstructions: string | undefined; + + if (handoffCode) { + const handoff = await completeAgentHandoff(handoffCode); + afterSetupInstructions = handoff.flowInstructions; + emit("Authenticated with Sentry using the agent handoff."); + } else if (shouldUseSetupCode) { await bootstrapAuthentication(); emit("Authenticated with Sentry using the setup code."); - if (!flags["no-completions"]) { - await warmCachesAfterLogin(); - } + } + + if ((handoffCode || shouldUseSetupCode) && !flags["no-completions"]) { + await warmCachesAfterLogin(); } if (flags["ensure-auth-scopes"]) { @@ -818,6 +831,10 @@ export const setupCommand = buildCommand({ printWelcomeMessage(emit, CLI_VERSION, binaryPath); } + if (afterSetupInstructions) { + emit(afterSetupInstructions); + } + yield new CommandOutput({ messages, warnings, @@ -840,7 +857,7 @@ export const setupCommand = buildCommand({ flags.method !== "curl" || flags.quiet || flags["ensure-auth-scopes"] || - Boolean(getEnv().SENTRY_SETUP_CODE) || + Boolean(handoffCode || setupCode) || !(interactivePromptsAllowed() && isatty(0) && isatty(1) && isatty(2)) ) { return; diff --git a/packages/cli/src/lib/agent-handoff.ts b/packages/cli/src/lib/agent-handoff.ts new file mode 100644 index 0000000000..30095a3c83 --- /dev/null +++ b/packages/cli/src/lib/agent-handoff.ts @@ -0,0 +1,134 @@ +import { + claimAgentHandoff, + type ClaimAgentHandoffResponse, + SentryApiError, +} from "@sentry/api"; +import { parseRetryDelayMs } from "@sentry/api/client"; +import { vClaimAgentHandoffResponse } from "@sentry/api/valibot"; +import { looseObject, safeParse, string } from "valibot"; +import { + DEFAULT_SENTRY_URL, + getConfiguredSentryUrl, + isPersistedDefaultUrlInEffect, +} from "./constants.js"; +import { redactCredentialText } from "./credential-redaction.js"; +import { customFetch, warnIfSaasWithEnvCa } from "./custom-ca.js"; +import { applyCustomHeaders } from "./custom-headers.js"; +import { ApiError, HostScopeError, RateLimitError } from "./errors.js"; +import { + buildHostRefusalMessage, + isAutoLoginHostTrusted, +} from "./login-host-guard.js"; +import { normalizeHttpOrigin } from "./sentry-urls.js"; +import { bootstrapAuthentication } from "./setup-code.js"; + +const ErrorResponseSchema = looseObject({ detail: string() }); + +function getExchangeContext(): { + host: string; + customHeadersTrusted: boolean; +} { + const configured = isPersistedDefaultUrlInEffect() + ? undefined + : getConfiguredSentryUrl(); + const host = normalizeHttpOrigin(configured ?? DEFAULT_SENTRY_URL); + + if (!host) { + throw new ApiError( + "Invalid Sentry URL for agent handoff", + 0, + "Set SENTRY_HOST or SENTRY_URL to a credential-free HTTP(S) URL.", + ); + } + + if (!isAutoLoginHostTrusted(host)) { + throw new HostScopeError(buildHostRefusalMessage(host)); + } + + return { host, customHeadersTrusted: configured !== undefined }; +} + +function responseDetail(body: unknown): string | undefined { + if (body instanceof SentryApiError && body.detailMessage) { + return redactCredentialText(body.detailMessage); + } + + const errorBody = body instanceof SentryApiError ? body.body : body; + const parsed = safeParse(ErrorResponseSchema, errorBody); + return parsed.success + ? redactCredentialText(parsed.output.detail) + : undefined; +} + +/** Claim a private handoff code from the configured Sentry instance. */ +export async function exchangeAgentHandoff( + handoffCode: string, +): Promise { + const { host, customHeadersTrusted } = getExchangeContext(); + const headers = new Headers(); + applyCustomHeaders(headers, host, customHeadersTrusted); + warnIfSaasWithEnvCa(host); + + const result = await claimAgentHandoff({ + baseUrl: host, + body: { handoff_code: handoffCode }, + fetch: customFetch, + headers: Object.fromEntries(headers), + redirect: "error", + }); + + if ("error" in result) { + const response = result.response; + if (!response) { + throw new ApiError( + "Sentry agent handoff failed", + 0, + "Check your network connection and try again.", + ); + } + + const detail = responseDetail(result.error); + if (response.status === 429) { + throw new RateLimitError( + response.url, + parseRetryDelayMs(response.status, response.headers), + detail, + ); + } + + throw new ApiError( + "Sentry agent handoff failed", + response.status, + detail ?? "Request a new handoff from Sentry and try again.", + response.url || undefined, + ); + } + + const parsed = safeParse(vClaimAgentHandoffResponse, result.data); + if (!parsed.success) { + throw new ApiError( + "Invalid response from the Sentry agent handoff endpoint", + result.response.status, + "Request a new handoff from Sentry and try again.", + result.response.url || undefined, + ); + } + + return parsed.output; +} + +/** Claim a handoff and authenticate its account before returning instructions. */ +export async function completeAgentHandoff( + handoffCode: string, +): Promise { + const handoff = await exchangeAgentHandoff(handoffCode); + + await bootstrapAuthentication({ + code: handoff.setupCode, + clientId: handoff.clientId, + force: true, + url: handoff.sentryUrl, + }); + + return handoff; +} diff --git a/packages/cli/src/lib/credential-redaction.ts b/packages/cli/src/lib/credential-redaction.ts index 51eceb4fb4..35dd631b67 100644 --- a/packages/cli/src/lib/credential-redaction.ts +++ b/packages/cli/src/lib/credential-redaction.ts @@ -17,7 +17,7 @@ const INVALID_HEADER_END = /(? { const response = await fetchWithConnectionError( host + "/oauth/token/", @@ -630,7 +631,7 @@ export async function exchangeSetupCode( headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "urn:sentry:params:oauth:grant-type:setup_code", - client_id: getClientId(), + client_id: clientId, setup_code: code, }), }, diff --git a/packages/cli/src/lib/setup-code.ts b/packages/cli/src/lib/setup-code.ts index 856f8bf8fd..0cc6238f51 100644 --- a/packages/cli/src/lib/setup-code.ts +++ b/packages/cli/src/lib/setup-code.ts @@ -59,13 +59,17 @@ export function getSetupCodeHost(code: string): string { /** Redeem a private setup code, replacing only the issuing server's selected login. */ export async function bootstrapAuthentication( options: { + /** Private setup credential provided by Sentry. */ + code?: string; /** Explicit consent to replace an existing stored login. */ force?: boolean; /** Explicit issuing instance URL, required for HTTP without a boot-time URL. */ url?: string; + /** OAuth application that issued the setup credential. */ + clientId?: string; } = {}, ): Promise { - const code = getEnv().SENTRY_SETUP_CODE; + const code = (options.code ?? getEnv().SENTRY_SETUP_CODE)?.trim(); if (!code) { throw new ValidationError( @@ -112,7 +116,7 @@ export async function bootstrapAuthentication( inheritEnvTokenHost(env); return await withEnv(env, async () => { - const token = await exchangeSetupCode(code, host); + const token = await exchangeSetupCode(code, host, options.clientId); const accessToken = normalizeAuthToken(token.access_token); setAuthToken(accessToken, token.expires_in, token.refresh_token, { host, diff --git a/packages/cli/test/commands/cli/setup.test.ts b/packages/cli/test/commands/cli/setup.test.ts index 2c17ca5872..1f937631e4 100644 --- a/packages/cli/test/commands/cli/setup.test.ts +++ b/packages/cli/test/commands/cli/setup.test.ts @@ -62,9 +62,16 @@ vi.mock("../../../src/lib/windows-path.js", async (importOriginal) => ({ import { app } from "../../../src/app.js"; import { warmCachesAfterLogin } from "../../../src/lib/completion-warmup.js"; import type { SentryContext } from "../../../src/context.js"; -import { getAccountRow } from "../../../src/lib/db/accounts.js"; +import { + getAccountRow, + listAccountRows, +} from "../../../src/lib/db/accounts.js"; import { EXIT } from "../../../src/lib/errors.js"; -import { getAuthConfig, setAuthToken } from "../../../src/lib/db/auth.js"; +import { + getActiveAccountId, + getAuthConfig, + setAuthToken, +} from "../../../src/lib/db/auth.js"; import { getOnOffPreference, setOnOffPreference, @@ -74,6 +81,7 @@ import { getInstallInfo, } from "../../../src/lib/db/install-info.js"; import { getReleaseChannel } from "../../../src/lib/db/release-channel.js"; +import { setUserInfo } from "../../../src/lib/db/user.js"; import { getProcessInfoFromOS, setProcessInfoProvider, @@ -1033,6 +1041,47 @@ describe("sentry cli setup", () => { }; } + const handoffCode = `sntryh_${"b".repeat(43)}`; + const handoffSetupCode = `sntryc_${Buffer.from( + JSON.stringify({ url: "https://sentry.io", iat: 1 }), + ).toString("base64")}_${"a".repeat(43)}`; + const handoffToken = { + access_token: "handoff-token", + refresh_token: "handoff-refresh-token", + expires_in: 3600, + token_type: "bearer", + user: { + id: "new-user", + name: "New User", + email: "new@example.com", + }, + }; + + function stubHandoffFetch({ + flowInstructions = "Continue the requested setup.", + tokenResponse = Response.json(handoffToken), + }: { + flowInstructions?: string; + tokenResponse?: Response; + } = {}) { + const fetch = vi + .fn() + .mockResolvedValueOnce( + Response.json({ + sentryUrl: "https://sentry.io", + userEmail: "new@example.com", + organizationName: "New Organization", + organizationSlug: "new-org", + clientId: "handoff-client", + setupCode: handoffSetupCode, + flowInstructions, + }), + ) + .mockResolvedValueOnce(tokenResponse); + vi.stubGlobal("fetch", fetch); + return fetch; + } + test.each([true, false])( "redeems a setup code with completions=%s without opening a browser", async (completions) => { @@ -1077,6 +1126,136 @@ describe("sentry cli setup", () => { }, ); + test.each([ + { name: "a first install", existingBinary: false, completions: true }, + { + name: "an existing unauthenticated install", + existingBinary: true, + completions: false, + }, + ])( + "completes an agent handoff during $name", + async ({ existingBinary, completions }) => { + vi.mocked(warmCachesAfterLogin).mockClear(); + const instructions = "First instruction.\n\nSecond instruction."; + const fixture = createInstall({ + existingBinary, + completions, + env: { SENTRY_HANDOFF: handoffCode }, + }); + const fetch = stubHandoffFetch({ flowInstructions: instructions }); + + try { + await fixture.run(); + + expect(fetch).toHaveBeenCalledTimes(2); + const [, tokenInit] = fetch.mock.calls[1]; + expect(tokenInit.body.get("setup_code")).toBe(handoffSetupCode); + expect(tokenInit.body.get("client_id")).toBe("handoff-client"); + expect(getAuthConfig()?.token).toBe("handoff-token"); + expect(warmCachesAfterLogin).toHaveBeenCalledTimes( + completions ? 1 : 0, + ); + expect(fixture.getOutput()).toContain(instructions); + expect(fixture.getOutput()).not.toContain(handoffCode); + expect(fixture.getOutput()).not.toContain(handoffSetupCode); + expect(interactiveLogin.runInteractiveLogin).not.toHaveBeenCalled(); + expect(fixture.context.process.exitCode).toBe(0); + } finally { + vi.unstubAllGlobals(); + } + }, + ); + + test("omits empty handoff instructions from setup output", async () => { + const fixture = createInstall({ + install: false, + flags: ["--json"], + env: { SENTRY_HANDOFF: handoffCode }, + }); + stubHandoffFetch({ flowInstructions: "" }); + + try { + await fixture.run(); + + const { messages } = JSON.parse(fixture.getOutput()); + expect(messages).toContain( + "Authenticated with Sentry using the agent handoff.", + ); + expect(messages).not.toContain(""); + } finally { + vi.unstubAllGlobals(); + } + }); + + test.each([ + { + name: "the intended account", + host: "https://sentry.io", + userId: "new-user", + }, + { + name: "another account on the intended host", + host: "https://sentry.io", + userId: "old-user", + }, + { + name: "an account on another Sentry host", + host: "https://sentry.example.com", + userId: "old-user", + }, + ])("agent handoff supersedes $name", async ({ host, userId }) => { + const fixture = createInstall({ + install: false, + env: { SENTRY_HANDOFF: handoffCode }, + }); + setAuthToken("old-token", 3600, "old-refresh", { host }); + setUserInfo({ userId, email: `${userId}@example.com` }); + stubHandoffFetch(); + + try { + await fixture.run(); + + expect(getAuthConfig()?.token).toBe("handoff-token"); + expect(getAccountRow(getActiveAccountId() ?? "")?.host).toBe( + "https://sentry.io", + ); + if (host === "https://sentry.example.com") { + expect( + listAccountRows().some((row) => row.token === "old-token"), + ).toBe(true); + } + expect(fixture.context.process.exitCode).toBe(0); + } finally { + vi.unstubAllGlobals(); + } + }); + + test("does not print flow instructions when handoff authentication fails", async () => { + const fixture = createInstall({ + install: false, + env: { SENTRY_HANDOFF: handoffCode }, + }); + const instructions = "Do not print these instructions."; + stubHandoffFetch({ + flowInstructions: instructions, + tokenResponse: Response.json( + { error: "invalid_grant" }, + { status: 400 }, + ), + }); + + try { + await fixture.run(); + + expect(fixture.context.process.exitCode).toBeGreaterThan(0); + expect(fixture.getOutput()).not.toContain(instructions); + expect(getAuthConfig()).toBeUndefined(); + } finally { + vi.unstubAllGlobals(); + } + }); + test("finishes installation configuration when setup-code redemption fails", async () => { const claim = Buffer.from( JSON.stringify({ url: "https://sentry.io" }), diff --git a/packages/cli/test/lib/agent-handoff.test.ts b/packages/cli/test/lib/agent-handoff.test.ts new file mode 100644 index 0000000000..ffb2f004c2 --- /dev/null +++ b/packages/cli/test/lib/agent-handoff.test.ts @@ -0,0 +1,159 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { exchangeAgentHandoff } from "../../src/lib/agent-handoff.js"; +import { markPersistedDefaultUrl } from "../../src/lib/constants.js"; +import { formatError } from "../../src/lib/errors.js"; +import { setEnv } from "../../src/lib/env.js"; +import { + registerLoginTrustAnchor, + resetLoginTrustAnchorForTesting, +} from "../../src/lib/token-host.js"; + +const handoffCode = `sntryh_${"a".repeat(43)}`; +const handoffResponse = (sentryUrl: string) => + Response.json({ + sentryUrl, + userEmail: "user@example.com", + organizationName: "Example Organization", + organizationSlug: "example-org", + clientId: "client-id", + setupCode: "private-setup-code", + flowInstructions: "Continue setup.", + }); + +describe("agent handoff exchange", () => { + afterEach(() => { + resetLoginTrustAnchorForTesting(); + vi.unstubAllGlobals(); + setEnv(process.env); + }); + + test("uses a trusted configured custom host", async () => { + const env = { + SENTRY_CUSTOM_HEADERS: "X-IAP-Token: proxy-secret", + SENTRY_HOST: "sentry.example.com", + }; + setEnv(env); + registerLoginTrustAnchor("https://sentry.example.com"); + const fetch = vi + .fn() + .mockResolvedValue(handoffResponse("https://sentry.example.com")); + vi.stubGlobal("fetch", fetch); + + await expect(exchangeAgentHandoff(handoffCode)).resolves.toMatchObject({ + organizationSlug: "example-org", + }); + const request = new Request(...fetch.mock.calls[0]); + expect(request.url).toBe("https://sentry.example.com/api/0/agent-handoff/"); + expect(request.method).toBe("POST"); + expect(request.headers.get("Content-Type")).toBe("application/json"); + expect(request.headers.get("X-IAP-Token")).toBe("proxy-secret"); + await expect(request.json()).resolves.toEqual({ + handoff_code: handoffCode, + }); + }); + + test("refuses an untrusted configured custom host", async () => { + setEnv({ SENTRY_HOST: "sentry.example.com" }); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); + + await expect(exchangeAgentHandoff(handoffCode)).rejects.toThrow( + /Refusing to log in against https:\/\/sentry\.example\.com/, + ); + expect(fetch).not.toHaveBeenCalled(); + }); + + test("ignores another account's persisted host default", async () => { + const env = { + SENTRY_CUSTOM_HEADERS: "X-IAP-Token: proxy-secret", + SENTRY_URL: "https://sentry.example.com", + }; + setEnv(env); + markPersistedDefaultUrl(env.SENTRY_URL); + const fetch = vi + .fn() + .mockResolvedValue(handoffResponse("https://sentry.io")); + vi.stubGlobal("fetch", fetch); + + await exchangeAgentHandoff(handoffCode); + + const request = new Request(...fetch.mock.calls[0]); + expect(request.url).toBe("https://sentry.io/api/0/agent-handoff/"); + expect(request.headers.get("X-IAP-Token")).toBeNull(); + }); + + test.each([ + [400, "Invalid handoff code."], + [403, "The handoff code was claimed from a different network."], + [410, "Handoff code unavailable."], + [429, "Wait 60 seconds, then retry the same handoff code."], + ])("surfaces useful detail for HTTP %i", async (status, detail) => { + setEnv({}); + const response = Response.json({ detail }, { status }); + if (status === 429) { + response.headers.set("Retry-After", "60"); + } + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response)); + + let caught: unknown; + try { + await exchangeAgentHandoff(handoffCode); + } catch (error) { + caught = error; + } + + expect(formatError(caught)).toContain(detail); + expect(formatError(caught)).not.toContain(handoffCode); + }); + + test("surfaces structured error detail from the backend", async () => { + setEnv({}); + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + Response.json( + { + detail: { + code: "agent-handoff-ip-mismatch", + message: + 'Ask the user to turn off "Use IP pinning" and copy a new handoff prompt.', + extra: {}, + }, + }, + { status: 403 }, + ), + ), + ); + + let caught: unknown; + try { + await exchangeAgentHandoff(handoffCode); + } catch (error) { + caught = error; + } + + expect(formatError(caught)).toContain( + 'Ask the user to turn off "Use IP pinning" and copy a new handoff prompt.', + ); + expect(formatError(caught)).not.toContain(handoffCode); + }); + + test("redacts a handoff code from server error detail", async () => { + setEnv({}); + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValue( + Response.json( + { detail: `Rejected handoff_code=${handoffCode}` }, + { status: 400 }, + ), + ), + ); + + await expect(exchangeAgentHandoff(handoffCode)).rejects.not.toThrow( + handoffCode, + ); + }); +}); diff --git a/packages/cli/test/lib/install-ps1-script.test.ts b/packages/cli/test/lib/install-ps1-script.test.ts index b760cf8ef6..56412df8b0 100644 --- a/packages/cli/test/lib/install-ps1-script.test.ts +++ b/packages/cli/test/lib/install-ps1-script.test.ts @@ -38,6 +38,7 @@ set -euo pipefail if [[ "$1" == "cli" && "$2" == "setup" ]]; then printf '%s\\n' "$@" > "$SENTRY_TEST_DIR/setup-args" printf '%s\\n' "$SENTRY_INSTALL_DIR" > "$SENTRY_TEST_DIR/setup-install-dir" + printf '%s\\n' "\${SENTRY_HANDOFF:-}" > "$SENTRY_TEST_DIR/setup-handoff" mkdir -p "$SENTRY_INSTALL_DIR" cp "$0" "$SENTRY_INSTALL_DIR/sentry.exe" exit "\${SENTRY_TEST_SETUP_EXIT:-0}" @@ -184,7 +185,10 @@ describe.skipIf(!hasPwsh)("PowerShell install script", () => { ).toEqual([]); }); - test("hands off PATH handling to setup", () => { + test("passes setup environment and hands off PATH handling", () => { + const handoffCode = `sntryh_${"a".repeat(43)}`; + env.SENTRY_HANDOFF = handoffCode; + const result = run(); expect(result.status, result.stdout + result.stderr).toBe(0); @@ -200,6 +204,7 @@ describe.skipIf(!hasPwsh)("PowerShell install script", () => { "--channel", "stable", ]); + expect(recorded("setup-handoff")).toEqual([handoffCode]); // Setup decides the install directory and edits PATH itself. expect(recorded("setup-install-dir")).toEqual([installDir]); expect(recorded("github-path")).toEqual([]); diff --git a/packages/cli/test/lib/install-script.test.ts b/packages/cli/test/lib/install-script.test.ts index ffa19026ca..6bd9edb4f0 100644 --- a/packages/cli/test/lib/install-script.test.ts +++ b/packages/cli/test/lib/install-script.test.ts @@ -49,6 +49,7 @@ record_tty() { if [[ "$1" == "cli" && "$2" == "setup" ]]; then printf '%s\\n' "$@" > "$SENTRY_TEST_DIR/setup-args" printf '%s\\n' "$0" > "$SENTRY_TEST_DIR/setup-binary" + printf '%s\\n' "\${SENTRY_HANDOFF:-}" > "$SENTRY_TEST_DIR/setup-handoff" record_tty 3> "$SENTRY_TEST_DIR/setup-tty" install_dir="\${SENTRY_INSTALL_DIR:-\${0%/*}}" mkdir -p "$install_dir" @@ -377,7 +378,10 @@ process.exitCode = result.status ?? 1; }); } - test("passes setup flags through and skips login without a terminal", () => { + test("passes setup environment and flags through without a terminal", () => { + const handoffCode = `sntryh_${"a".repeat(43)}`; + env.SENTRY_HANDOFF = handoffCode; + const result = spawnSync( "bash", [ @@ -403,6 +407,7 @@ process.exitCode = result.status ?? 1; "--no-completions", "--no-agent-skills", ]); + expect(recorded("setup-handoff")).toEqual([handoffCode]); expect(recorded("setup-tty").slice(0, 3)).toEqual([ "0:false", "1:false", diff --git a/packages/cli/test/lib/telemetry-credentials.test.ts b/packages/cli/test/lib/telemetry-credentials.test.ts index f308c5d2f3..d250754824 100644 --- a/packages/cli/test/lib/telemetry-credentials.test.ts +++ b/packages/cli/test/lib/telemetry-credentials.test.ts @@ -64,6 +64,20 @@ afterEach(async () => { }); describe("telemetry credential boundaries", () => { + test("scrubs agent handoff codes from the outgoing envelope", async () => { + const capture = captureTelemetry(); + const handoffCode = `sntryh_${"a".repeat(43)}`; + captureEvent({ + message: `Rejected handoff_code=${handoffCode}`, + extra: { handoffCode }, + }); + await capture.client.flush(1000); + + const serialized = capture.serializedEnvelope("event"); + expect(serialized).not.toContain(handoffCode); + expect(serialized).toContain("[REDACTED]"); + }); + test("sanitizes exceptions and related fields in the outgoing envelope", async () => { const capture = captureTelemetry(); const event: ErrorEvent = {