Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/cli/lint-rules/cli-oxlint-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
27 changes: 22 additions & 5 deletions packages/cli/src/commands/cli/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved

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"]) {
Expand All @@ -818,6 +831,10 @@ export const setupCommand = buildCommand({
printWelcomeMessage(emit, CLI_VERSION, binaryPath);
}

if (afterSetupInstructions) {
emit(afterSetupInstructions);
}

yield new CommandOutput({
messages,
warnings,
Expand All @@ -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;
Expand Down
134 changes: 134 additions & 0 deletions packages/cli/src/lib/agent-handoff.ts
Original file line number Diff line number Diff line change
@@ -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.",
);
}
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved

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;
}
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved

/** Claim a private handoff code from the configured Sentry instance. */
export async function exchangeAgentHandoff(
handoffCode: string,
): Promise<ClaimAgentHandoffResponse> {
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<ClaimAgentHandoffResponse> {
const handoff = await exchangeAgentHandoff(handoffCode);

await bootstrapAuthentication({
code: handoff.setupCode,
clientId: handoff.clientId,
force: true,
url: handoff.sentryUrl,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handoff client ID not persisted

Medium Severity

Handoff authentication exchanges the setup code with handoff.clientId, but that client ID is not stored on the account. Later refresh still calls getClientId(), which is the env/build default. When those IDs differ, refresh is rejected after the access token expires and the headless session dies.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9a607f5. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tracked separately in #2383. We should persist the issuing OAuth client ID with each stored credential and use it for refresh. This can also affect existing logins if SENTRY_CLIENT_ID changes after login.


return handoff;
}
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved
4 changes: 2 additions & 2 deletions packages/cli/src/lib/credential-redaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const INVALID_HEADER_END = /(?<!\\)(\\*["']) is an invalid header value/gi;
// Header validation errors quote the entire value, including invalid newlines.
// The end-of-string alternative also covers messages truncated by the SDK.
const QUOTED_CREDENTIAL =
/(?<!\\)(\\*["'])(Bearer[ \t]+|sntry[suc]_)[\s\S]*?(?:\1|$)/gi;
/(?<!\\)(\\*["'])(Bearer[ \t]+|sntry[hsuc]_)[\s\S]*?(?:\1|$)/gi;
/** Control characters can also appear escaped in serialized diagnostics. */
const ESCAPED_CONTROL = /\\+(?:[nrtbfv]|u00[01][\da-f]|u007f|u202[89])/.source;
const BEARER_PART = String.raw`(?:${ESCAPED_CONTROL}[ \t]*|\\+[^"'\s\\]|[^\s"'\\])`;
Expand All @@ -28,7 +28,7 @@ const BEARER_CREDENTIAL = new RegExp(
"gi",
);
const SENTRY_CREDENTIAL = new RegExp(
String.raw`\bsntry[suc]_[A-Za-z0-9._~+/=-]+(?:(?:\r\n|(?! )[\s\x00-\x1f\x7f-\x9f]|${ESCAPED_CONTROL})[ \t]*[A-Za-z0-9._~+/=-]+)*`,
String.raw`\bsntry[hsuc]_[A-Za-z0-9._~+/=-]+(?:(?:\r\n|(?! )[\s\x00-\x1f\x7f-\x9f]|${ESCAPED_CONTROL})[ \t]*[A-Za-z0-9._~+/=-]+)*`,
"gi",
);
// Onboarding run tokens grant write access to a run's progress. They have no
Expand Down
5 changes: 5 additions & 0 deletions packages/cli/src/lib/env-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [
selfHosted: true,
devGuide: "Sentry OAuth app client ID",
},
{
name: "SENTRY_HANDOFF",
description:
"Private, short-lived agent handoff code. The install and setup flow exchanges it for the intended Sentry account, authenticates that account, and prints its setup instructions.",
},
{
name: "SENTRY_SETUP_CODE",
description:
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/lib/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,7 @@ export async function refreshAccessToken(
export async function exchangeSetupCode(
code: string,
host: string,
clientId: string = getClientId(),
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved
): Promise<TokenResponse> {
const response = await fetchWithConnectionError(
host + "/oauth/token/",
Expand All @@ -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,
}),
},
Expand Down
8 changes: 6 additions & 2 deletions packages/cli/src/lib/setup-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,18 @@
/** 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<BootstrapResult> {
const code = getEnv().SENTRY_SETUP_CODE;
const code = (options.code ?? getEnv().SENTRY_SETUP_CODE)?.trim();

Check warning on line 73 in packages/cli/src/lib/setup-code.ts

View check run for this annotation

@sentry/warden / warden: code-review

Handoff clientId is used only for setup exchange, not later refresh

bootstrapAuthentication accepts a handoff `clientId` for the setup-code token exchange, but nothing stores that client id on the account, and `refreshAccessToken()` always sends `getClientId()`. When `handoff.clientId` differs from `SENTRY_CLIENT_ID`/the build default (as the setup tests already do with `handoff-client`), refresh after expiry uses the wrong client and drops the session.
if (!code) {
throw new ValidationError(
"Set SENTRY_SETUP_CODE to the private code provided by Sentry.",
Expand Down Expand Up @@ -112,7 +116,7 @@
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,
Expand Down
Loading
Loading