Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.
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
9 changes: 8 additions & 1 deletion docs/src/content/docs/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down
29 changes: 21 additions & 8 deletions docs/src/fragments/commands/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
2 changes: 1 addition & 1 deletion plugins/sentry-cli/skills/sentry-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions plugins/sentry-cli/skills/sentry-cli/references/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <value>... - Re-authenticate with specific OAuth scopes (repeatable, comma-separated). E.g. --scope project:read --scope org:read`

Expand Down
2 changes: 1 addition & 1 deletion src/commands/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
17 changes: 13 additions & 4 deletions src/commands/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand Down Expand Up @@ -322,7 +331,7 @@ async function handleExistingAuth(force: boolean): Promise<boolean> {
`${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;
}
Expand Down
33 changes: 21 additions & 12 deletions src/commands/auth/refresh.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -93,10 +102,10 @@ session (similar to \`gh auth refresh -s <scope>\`).

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...
Expand All @@ -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": {
Expand Down Expand Up @@ -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()
Expand Down
28 changes: 23 additions & 5 deletions src/lib/formatters/human.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand All @@ -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)",
]);
}
Expand Down
3 changes: 3 additions & 0 deletions src/lib/interactive-login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

/**
Expand Down Expand Up @@ -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);
Expand Down
22 changes: 21 additions & 1 deletion test/commands/auth/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
26 changes: 24 additions & 2 deletions test/commands/auth/refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});

Expand All @@ -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({
Expand Down
Loading
Loading