From 1bf095abb3e5996b89c30fd6374d390b6dca68a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Beteg=C3=B3n?= Date: Thu, 30 Jul 2026 14:36:49 +0200 Subject: [PATCH] fix(auth): clarify access token expiry wording OAuth login showed the access token lifetime without explaining that the CLI refreshes it automatically, making successful sessions look short-lived. Report refresh capability at login and reserve expiry wording for access-token diagnostics. Closes #1312 --- docs/src/content/docs/getting-started.mdx | 9 ++++- docs/src/fragments/commands/auth.md | 29 +++++++++++----- plugins/sentry-cli/skills/sentry-cli/SKILL.md | 2 +- .../skills/sentry-cli/references/auth.md | 4 +-- src/commands/auth/index.ts | 2 +- src/commands/auth/login.ts | 17 +++++++--- src/commands/auth/refresh.ts | 33 ++++++++++++------- src/lib/formatters/human.ts | 28 +++++++++++++--- src/lib/interactive-login.ts | 3 ++ test/commands/auth/login.test.ts | 22 ++++++++++++- test/commands/auth/refresh.test.ts | 26 +++++++++++++-- test/commands/auth/status.test.ts | 20 ++++++----- 12 files changed, 149 insertions(+), 46 deletions(-) diff --git a/docs/src/content/docs/getting-started.mdx b/docs/src/content/docs/getting-started.mdx index a6e3fcc07f..d3d9e8cbb9 100644 --- a/docs/src/content/docs/getting-started.mdx +++ b/docs/src/content/docs/getting-started.mdx @@ -109,7 +109,11 @@ The easiest way to authenticate is via OAuth device flow: sentry auth login ``` -You'll be given a URL and a code to enter. Once you authorize the application in your browser, the CLI will automatically receive your token. +You'll be given a URL and a code to enter. Once you authorize the application +in your browser, the CLI stores the OAuth credentials. When the server provides +a refresh token, the CLI refreshes the access token automatically. Persist the +Sentry CLI configuration directory (`~/.sentry/` by default, overridable with +`SENTRY_CONFIG_DIR`) across runs to keep automatic refresh working. ### API Token @@ -121,6 +125,9 @@ sentry auth login --token YOUR_SENTRY_API_TOKEN You can create API tokens in your [Sentry account settings](https://sentry.io/settings/account/api/auth-tokens/). +API tokens are also useful for ephemeral CI jobs and sandboxes that cannot +persist the CLI configuration directory. + ### Check Auth Status Verify your authentication status: diff --git a/docs/src/fragments/commands/auth.md b/docs/src/fragments/commands/auth.md index 9d5afa16bd..c548bc6f6b 100644 --- a/docs/src/fragments/commands/auth.md +++ b/docs/src/fragments/commands/auth.md @@ -12,7 +12,8 @@ sentry auth login 2. Open the URL in your browser 3. Enter the code when prompted 4. Authorize the application -5. The CLI automatically receives your token +5. The CLI stores the OAuth credentials and, when the server provides a refresh + token, automatically refreshes the access token ### Token login @@ -40,7 +41,7 @@ See [Self-Hosted Sentry](../self-hosted/) for details. sentry auth logout ``` -### Refresh token +### Refresh the OAuth access token ```bash sentry auth refresh @@ -59,9 +60,10 @@ sentry auth status ``` ``` -Authenticated as: username -Organization: my-org -Token expires: 2024-12-31 +✓ Authenticated +User: username +Access token expires: in 4 weeks +Automatic refresh: enabled ``` ```bash @@ -74,16 +76,27 @@ sentry auth whoami ## Credential Storage -Auth tokens are stored in a SQLite database at `~/.sentry/cli.db` with restricted file permissions. +Auth tokens are stored in the Sentry CLI configuration directory (`~/.sentry/` +by default, overridable with `SENTRY_CONFIG_DIR`) with restricted file +permissions. + +OAuth access tokens expire. When the server provides a refresh token, the CLI +stores it and refreshes the access token automatically. Persist the +configuration directory across runs to keep automatic refresh working. For +ephemeral CI jobs or sandboxes that cannot persist stored credentials, provide +an API token with `sentry auth login --token` or `SENTRY_AUTH_TOKEN`. ## Token Precedence By default, the CLI checks for auth tokens in the following order: -1. The stored OAuth token in the SQLite database (from `sentry auth login`) +1. The stored credential from `sentry auth login` 2. `SENTRY_AUTH_TOKEN` environment variable 3. `SENTRY_TOKEN` environment variable (legacy alias) -The stored OAuth token takes priority because it supports automatic refresh. To override this and force environment tokens to win, set `SENTRY_FORCE_ENV_TOKEN=1`. +The stored credential takes priority. Stored OAuth credentials support +automatic refresh; manually provided API tokens do not use a refresh token. To +override this precedence and force environment tokens to win, set +`SENTRY_FORCE_ENV_TOKEN=1`. When a token comes from an environment variable, the CLI skips expiry checks and automatic refresh. diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 9ca08e1e51..41606ee246 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -298,7 +298,7 @@ Authenticate with Sentry - `sentry auth login` — Authenticate with Sentry - `sentry auth logout` — Log out of Sentry -- `sentry auth refresh` — Refresh your authentication token +- `sentry auth refresh` — Refresh your OAuth access token - `sentry auth status` — View authentication status - `sentry auth token` — Print the stored authentication token - `sentry auth whoami` — Show the currently authenticated identity diff --git a/plugins/sentry-cli/skills/sentry-cli/references/auth.md b/plugins/sentry-cli/skills/sentry-cli/references/auth.md index a54128ceba..e3e92c3754 100644 --- a/plugins/sentry-cli/skills/sentry-cli/references/auth.md +++ b/plugins/sentry-cli/skills/sentry-cli/references/auth.md @@ -47,10 +47,10 @@ sentry auth logout ### `sentry auth refresh` -Refresh your authentication token +Refresh your OAuth access token **Flags:** -- `--force - Force refresh even if token is still valid` +- `--force - Force refresh even if the access token is still valid` - `--read-only - Re-authenticate with read-only OAuth scopes (project:read, org:read, event:read, member:read, team:read)` - `-s, --scope ... - Re-authenticate with specific OAuth scopes (repeatable, comma-separated). E.g. --scope project:read --scope org:read` diff --git a/src/commands/auth/index.ts b/src/commands/auth/index.ts index 47a947f5a7..21dcd3a1a1 100644 --- a/src/commands/auth/index.ts +++ b/src/commands/auth/index.ts @@ -20,7 +20,7 @@ export const authRoute = buildRouteMap({ brief: "Authenticate with Sentry", fullDescription: "Manage authentication with Sentry. Use 'sentry auth login' to authenticate, " + - "'sentry auth logout' to remove credentials, 'sentry auth refresh' to manually refresh your token, " + + "'sentry auth logout' to remove credentials, 'sentry auth refresh' to manually refresh your OAuth access token, " + "'sentry auth status' to check your authentication status, " + "'sentry auth whoami' to show your current user identity, " + "and 'sentry auth token' to print your token for use in scripts.", diff --git a/src/commands/auth/login.ts b/src/commands/auth/login.ts index 50d698f86b..133da8791f 100644 --- a/src/commands/auth/login.ts +++ b/src/commands/auth/login.ts @@ -64,10 +64,19 @@ function formatLoginResult(result: LoginResult): string { if (result.user) { lines.push(` Logged in as: ${formatUserIdentity(result.user)}`); } - lines.push(` Config saved to: ${result.configPath}`); - if (result.expiresIn) { - lines.push(` Token expires in: ${formatDuration(result.expiresIn)}`); + if (result.method === "oauth" && result.refreshEnabled !== undefined) { + if (result.refreshEnabled) { + lines.push(" Automatic refresh: enabled"); + } else { + lines.push(" Automatic refresh: unavailable"); + if (result.expiresIn !== undefined) { + lines.push( + ` Access token expires in: ${formatDuration(result.expiresIn)}` + ); + } + } } + lines.push(` Config saved to: ${result.configPath}`); lines.push(""); // trailing newline return lines.join("\n"); } @@ -322,7 +331,7 @@ async function handleExistingAuth(force: boolean): Promise { `${envVar} is set in your environment (likely from build tooling).\n` + " OAuth credentials will be stored separately and used for CLI commands." ); - // If no stored OAuth token exists, proceed directly to login + // If no stored credential exists, proceed directly to login if (!hasStoredAuthCredentials()) { return true; } diff --git a/src/commands/auth/refresh.ts b/src/commands/auth/refresh.ts index 2b1a00d178..682cc34a5d 100644 --- a/src/commands/auth/refresh.ts +++ b/src/commands/auth/refresh.ts @@ -1,7 +1,7 @@ /** * sentry auth refresh * - * Manually refresh the authentication token, or re-authenticate with + * Manually refresh the OAuth access token, or re-authenticate with * different scopes via the OAuth device flow (like `gh auth refresh -s`). * * When `--scope` or `--read-only` is passed, the command runs a new device @@ -70,19 +70,28 @@ function resolveRefreshScope(flags: RefreshFlags): string { /** Format refresh result for terminal output */ function formatRefreshResult(data: RefreshOutput): string { - return data.refreshed - ? `${success("✓")} ${data.message}. Expires in ${formatDuration(data.expiresIn ?? 0)}.` - : `Token still valid (expires in ${formatDuration(data.expiresIn ?? 0)}).\nUse --force to refresh anyway.`; + if (data.refreshed) { + const validity = + data.expiresIn === undefined + ? "" + : ` Access token valid for ${formatDuration(data.expiresIn)}.`; + return `${success("✓")} ${data.message}.${validity}`; + } + const validity = + data.expiresIn === undefined + ? "" + : ` for ${formatDuration(data.expiresIn)}`; + return `${data.message}${validity}.\nUse --force to refresh anyway.`; } export const refreshCommand = buildCommand({ auth: false, docs: { - brief: "Refresh your authentication token", + brief: "Refresh your OAuth access token", fullDescription: ` -Manually refresh your authentication token using the stored refresh token. +Manually refresh your OAuth access token using the stored refresh token. -Token refresh normally happens automatically when making API requests. +Access token refresh normally happens automatically when making API requests. Use this command to force an immediate refresh or to verify the refresh mechanism is working correctly. @@ -93,10 +102,10 @@ session (similar to \`gh auth refresh -s \`). Examples: $ sentry auth refresh - Token refreshed successfully. Expires in 59 minutes. + ✓ Access token refreshed successfully. Access token valid for 59 minutes. $ sentry auth refresh --force - Token refreshed successfully. Expires in 60 minutes. + ✓ Access token refreshed successfully. Access token valid for 1 hour. $ sentry auth refresh --scope event:read --scope org:read Re-authenticating with scopes: event:read, org:read... @@ -113,7 +122,7 @@ Examples: flags: { force: { kind: "boolean", - brief: "Force refresh even if token is still valid", + brief: "Force refresh even if the access token is still valid", default: false, }, "read-only": { @@ -185,8 +194,8 @@ Examples: success: true, refreshed: result.refreshed, message: result.refreshed - ? "Token refreshed successfully" - : "Token still valid", + ? "Access token refreshed successfully" + : "Access token is still valid", expiresIn: result.expiresIn, expiresAt: result.expiresAt ? new Date(result.expiresAt).toISOString() diff --git a/src/lib/formatters/human.ts b/src/lib/formatters/human.ts index f6b791099e..aa72fd588f 100644 --- a/src/lib/formatters/human.ts +++ b/src/lib/formatters/human.ts @@ -1776,6 +1776,17 @@ function formatAuthHeader(source: string): string { return `## ${colorTag("green", "✓")} Authenticated`; } +/** Select a precise credential label for the auth status table. */ +function authTokenLabel(isEnv: boolean, isOAuthAccessToken: boolean): string { + if (isEnv) { + return "Token"; + } + if (isOAuthAccessToken) { + return "Access token"; + } + return "API token"; +} + /** * Build the key-value rows for the main auth details section. */ @@ -1790,14 +1801,21 @@ function buildAuthDetailRows(data: AuthStatusData): [string, string][] { rows.push(["User", formatUserIdentity(data.user)]); } if (data.token) { - rows.push(["Token", safeCodeSpan(data.token.display)]); + // Stored credentials do not retain an explicit auth method, so managed + // expiry or refresh capability identifies OAuth access tokens. + const isOAuthAccessToken = + data.token.refreshEnabled || data.token.expiresAt !== undefined; + const tokenLabel = authTokenLabel(isEnv, isOAuthAccessToken); + rows.push([tokenLabel, safeCodeSpan(data.token.display)]); if (data.token.expiresAt) { - rows.push(["Expires", formatExpiration(data.token.expiresAt)]); + rows.push([ + "Access token expires", + formatExpiration(data.token.expiresAt), + ]); } - // Only show auto-refresh for non-env tokens - if (!isEnv) { + if (isOAuthAccessToken) { rows.push([ - "Auto-refresh", + "Automatic refresh", data.token.refreshEnabled ? "enabled" : "disabled (no refresh token)", ]); } diff --git a/src/lib/interactive-login.ts b/src/lib/interactive-login.ts index f01421a492..585f7dcf2f 100644 --- a/src/lib/interactive-login.ts +++ b/src/lib/interactive-login.ts @@ -29,6 +29,8 @@ export type LoginResult = { configPath: string; /** Token lifetime in seconds, if known. */ expiresIn?: number; + /** Whether the OAuth access token can be refreshed automatically. */ + refreshEnabled?: boolean; }; /** @@ -200,6 +202,7 @@ export async function runInteractiveLogin( method: "oauth", configPath: getDbPath(), expiresIn: tokenResponse.expires_in, + refreshEnabled: Boolean(tokenResponse.refresh_token), }; if (user) { result.user = toLoginUser(user); diff --git a/test/commands/auth/login.test.ts b/test/commands/auth/login.test.ts index 4eabc9df4b..82169b26cb 100644 --- a/test/commands/auth/login.test.ts +++ b/test/commands/auth/login.test.ts @@ -444,13 +444,33 @@ describe("loginCommand.func --token path", () => { runInteractiveLoginSpy.mockResolvedValue({ method: "oauth", configPath: "/tmp/db", + expiresIn: 3600, + refreshEnabled: true, }); - const { context } = createContext(); + const { context, getStdout } = createContext(); await func.call(context, { force: false, timeout: 900 }); expect(runInteractiveLoginSpy).toHaveBeenCalled(); expect(setAuthTokenSpy).not.toHaveBeenCalled(); + expect(getStdout()).toContain("Automatic refresh: enabled"); + expect(getStdout()).not.toContain("expires"); + }); + + test("OAuth login warns when automatic refresh is unavailable", async () => { + isAuthenticatedSpy.mockReturnValue(false); + runInteractiveLoginSpy.mockResolvedValue({ + method: "oauth", + configPath: "/tmp/db", + expiresIn: 3600, + refreshEnabled: false, + }); + + const { context, getStdout } = createContext(); + await func.call(context, { force: false, timeout: 900 }); + + expect(getStdout()).toContain("Automatic refresh: unavailable"); + expect(getStdout()).toContain("Access token expires in: 1 hour"); }); test("--force when authenticated: clears auth and proceeds to interactive login", async () => { diff --git a/test/commands/auth/refresh.test.ts b/test/commands/auth/refresh.test.ts index 2cc7d5c7b4..64fe6a6c0c 100644 --- a/test/commands/auth/refresh.test.ts +++ b/test/commands/auth/refresh.test.ts @@ -144,7 +144,8 @@ describe("refreshCommand.func", () => { const { context, getStdout } = createContext(); await func.call(context, { json: false, force: false }); - expect(getStdout()).toContain("Token refreshed successfully"); + expect(getStdout()).toContain("Access token refreshed successfully"); + expect(getStdout()).toContain("Access token valid for"); expect(getStdout()).toContain("1 hour"); }); @@ -164,10 +165,31 @@ describe("refreshCommand.func", () => { const { context, getStdout } = createContext(); await func.call(context, { json: false, force: false }); - expect(getStdout()).toContain("Token still valid"); + expect(getStdout()).toContain("Access token is still valid"); + expect(getStdout()).toContain("30 minutes"); expect(getStdout()).toContain("--force"); }); + test("unknown lifetime does not render a zero-second validity", async () => { + isEnvTokenActiveSpy.mockReturnValue(false); + getAuthConfigSpy.mockReturnValue({ + token: "old_token", + source: "oauth", + refreshToken: "refresh_abc", + }); + refreshTokenSpy.mockResolvedValue({ + token: "new_token", + refreshed: true, + }); + + const { context, getStdout } = createContext(); + await func.call(context, { json: false, force: false }); + + expect(getStdout()).toContain("Access token refreshed successfully"); + expect(getStdout()).not.toContain("0 seconds"); + expect(getStdout()).not.toContain("valid for"); + }); + test("--json: outputs JSON for successful refresh", async () => { isEnvTokenActiveSpy.mockReturnValue(false); getAuthConfigSpy.mockReturnValue({ diff --git a/test/commands/auth/status.test.ts b/test/commands/auth/status.test.ts index 658356c5cf..f2f5b81923 100644 --- a/test/commands/auth/status.test.ts +++ b/test/commands/auth/status.test.ts @@ -208,7 +208,7 @@ describe("statusCommand.func", () => { expect(getOutput()).not.toContain("environment variable"); }); - test("shows expiration for OAuth token with expiresAt", async () => { + test("identifies access token expiration precisely", async () => { getAuthConfigSpy.mockReturnValue({ token: "sntrys_abc123def456", source: "oauth", @@ -219,10 +219,10 @@ describe("statusCommand.func", () => { const { context, getOutput } = createContext(); await func.call(context, humanFlags); - expect(getOutput()).toContain("Expires"); + expect(getOutput()).toContain("Access token expires"); }); - test("shows auto-refresh enabled with refresh token", async () => { + test("shows automatic refresh enabled with refresh token", async () => { getAuthConfigSpy.mockReturnValue({ token: "sntrys_abc123def456", source: "oauth", @@ -233,11 +233,12 @@ describe("statusCommand.func", () => { const { context, getOutput } = createContext(); await func.call(context, humanFlags); - expect(getOutput()).toContain("Auto-refresh"); + expect(getOutput()).toContain("Access token"); + expect(getOutput()).toContain("Automatic refresh"); expect(getOutput()).toContain("enabled"); }); - test("shows auto-refresh disabled without refresh token", async () => { + test("identifies a stored manual token without implying refresh is broken", async () => { getAuthConfigSpy.mockReturnValue({ token: "sntrys_abc123def456", source: "oauth", @@ -247,8 +248,9 @@ describe("statusCommand.func", () => { const { context, getOutput } = createContext(); await func.call(context, humanFlags); - expect(getOutput()).toContain("Auto-refresh"); - expect(getOutput()).toContain("disabled"); + expect(getOutput()).toContain("API token"); + expect(getOutput()).not.toContain("Automatic refresh"); + expect(getOutput()).not.toContain("disabled"); }); }); @@ -291,8 +293,8 @@ describe("statusCommand.func", () => { const { context, getOutput } = createContext(); await func.call(context, humanFlags); - expect(getOutput()).not.toContain("Expires"); - expect(getOutput()).not.toContain("Auto-refresh"); + expect(getOutput()).not.toContain("expires"); + expect(getOutput()).not.toContain("Automatic refresh"); }); test("masks token by default for env tokens", async () => {