Skip to content

feat: support SENTRY_AUTH_TOKEN and SENTRY_TOKEN env vars for headless auth#356

Merged
BYK merged 5 commits intomainfrom
byk/env-auth-token
Mar 5, 2026
Merged

feat: support SENTRY_AUTH_TOKEN and SENTRY_TOKEN env vars for headless auth#356
BYK merged 5 commits intomainfrom
byk/env-auth-token

Conversation

@BYK
Copy link
Member

@BYK BYK commented Mar 5, 2026

Summary

Support SENTRY_AUTH_TOKEN and SENTRY_TOKEN environment variables for authentication, bypassing the OAuth device flow and SQLite token storage. This enables headless environments (CI, Docker, agent sandboxes) to authenticate without interactive login.

Closes #348

Changes

Core auth layer (src/lib/db/auth.ts)

  • New AuthSource type: "env:SENTRY_AUTH_TOKEN" | "env:SENTRY_TOKEN" | "oauth"
  • getAuthToken() and getAuthConfig() check env vars first, then fall back to SQLite
  • refreshToken() short-circuits for env tokens (no refresh/expiry logic)
  • New isEnvTokenActive() helper for commands that need to branch on auth source

HTTP layer (src/lib/sentry-client.ts)

  • handleUnauthorized() skips token refresh when env token is active (401s propagate as-is)

Commands

  • auth status — Shows "Authenticated via SENTRY_AUTH_TOKEN environment variable ✓"; skips config path, expiry, and auto-refresh display for env tokens
  • auth refresh — Errors early with clear message when env token is active
  • auth login — Tells user to remove env var instead of re-authenticating
  • auth logout — Clears stored auth but warns env var still provides authentication

Tests

  • 22 unit tests covering env var priority, source tracking, trimming, refresh bypass
  • 9 property-based tests (fast-check) verifying priority invariants for any valid token values
  • Model-based test extensions with 5 new env var command classes
  • Test preload cleans SENTRY_TOKEN alongside existing SENTRY_AUTH_TOKEN

Design decisions

  • SENTRY_AUTH_TOKEN takes priority over SENTRY_TOKEN (matches legacy sentry-cli and Sentry SDK convention)
  • Empty/whitespace-only values are treated as unset
  • AuthConfig.source is required on every config object (not optional) so consumers can't forget to handle it

…s auth

Add environment variable authentication for headless/agent workflows.
SENTRY_AUTH_TOKEN takes priority over SENTRY_TOKEN, and both take
priority over stored OAuth tokens.

Core changes:
- Add getEnvToken() private helper in db/auth.ts that reads and trims
  env vars, returning the token and its source
- Add AuthSource type ('env:SENTRY_AUTH_TOKEN' | 'env:SENTRY_TOKEN' | 'oauth')
  and required source field on AuthConfig
- Add isEnvTokenActive() exported helper for commands and sentry-client
- Modify getAuthToken(), getAuthConfig(), refreshToken() to check env
  vars first, short-circuiting all SQLite and OAuth refresh logic
- Modify handleUnauthorized() in sentry-client.ts to skip token refresh
  for env tokens (let 401 propagate)

Command updates:
- auth status: shows 'Authenticated via <ENV_VAR> environment variable',
  skips config path and auto-refresh display for env tokens
- auth refresh: errors with clear message for env tokens
- auth login: warns that env var provides auth, suggests removing it
- auth logout: clears stored auth but warns env var still active
- auth token: works as-is (getAuthToken returns env token)
- auth whoami: works as-is (just needs valid token)

Tests:
- New test/lib/db/auth.test.ts: 22 unit tests for env var priority,
  source tracking, trimming, empty values, refresh bypass
- New test/lib/db/auth.property.test.ts: 9 property-based tests with
  fast-check verifying priority invariants for any valid token values
- Extended test/lib/db/model-based.test.ts: env var commands in model
  (SetEnvAuthToken, ClearEnvAuthToken, SetEnvSentryToken,
  ClearEnvSentryToken, IsEnvTokenActive) with save/restore in finally
- test/preload.ts: added SENTRY_TOKEN cleanup alongside SENTRY_AUTH_TOKEN
@github-actions
Copy link
Contributor

github-actions bot commented Mar 5, 2026

Semver Impact of This PR

🟡 Minor (new features)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


New Features ✨

Trace

Other

  • (api) Add --data/-d flag and auto-detect JSON body in fields by BYK in #320
  • (formatters) Render all terminal output as markdown by BYK in #297
  • (install) Add Sentry error telemetry to install script by BYK in #334
  • (issue-list) Global limit with fair distribution, compound cursor, and richer progress by BYK in #306
  • (log-list) Add --trace flag to filter logs by trace ID by BYK in #329
  • (logger) Add consola-based structured logging with Sentry integration by BYK in #338
  • (project) Add project create command by betegon in #237
  • (upgrade) Add binary delta patching via TRDIFF10/bsdiff by BYK in #327
  • Support SENTRY_AUTH_TOKEN and SENTRY_TOKEN env vars for headless auth by BYK in #356
  • Improve markdown rendering styles by BYK in #342

Bug Fixes 🐛

Api

  • Use numeric project ID to avoid "not actively selected" error by betegon in #312
  • Use limit param for issues endpoint page size by BYK in #309
  • Auto-correct ':' to '=' in --field values with a warning by BYK in #302

Formatters

  • Expand streaming table to fill terminal width by betegon in #314
  • Fix HTML entities and escaped underscores in table output by betegon in #313

Setup

  • Suppress agent skills and welcome messages on upgrade by BYK in #328
  • Suppress shell completion messages on upgrade by BYK in #326

Upgrade

  • Check GHCR for nightly version existence instead of GitHub Releases by BYK in #352
  • Replace Bun.mmap with arrayBuffer on all platforms by BYK in #343
  • Replace Bun.mmap with arrayBuffer on macOS to prevent SIGKILL by BYK in #340
  • Use MAP_PRIVATE mmap to prevent macOS SIGKILL during delta upgrade by BYK in #339

Other

  • (ci) Generate JUnit XML to silence codecov-action warnings by BYK in #300
  • (install) Fix nightly digest extraction on macOS by BYK in #331
  • (logger) Inject --verbose and --log-level as proper Stricli flags by BYK in #353
  • (nightly) Push to GHCR from artifacts dir so layer titles are bare filenames by BYK in #301
  • (project create) Auto-correct dot-separated platform to hyphens by BYK in #336
  • (region) Resolve DSN org prefix at resolution layer by BYK in #316
  • (test) Handle 0/-0 in getComparator anti-symmetry property test by BYK in #308
  • (trace-logs) Timestamp_precise is a number, not a string by BYK in #323

Documentation 📚

  • Document SENTRY_URL and self-hosted setup by BYK in #337

Internal Changes 🔧

Api

  • Upgrade @sentry/api to 0.21.0, remove raw HTTP pagination workarounds by BYK in #321
  • Wire listIssuesPaginated through @sentry/api SDK for type safety by BYK in #310

Other

  • (craft) Add sentry-release-registry target by BYK in #325
  • (project create) Migrate human output to markdown rendering system by BYK in #341
  • (telemetry) Add child spans to delta upgrade for bottleneck identification by BYK in #355
  • (upgrade) Use copy-then-mmap for zero JS heap during delta patching by BYK in #344

🤖 This preview updates automatically when you update the PR.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 5, 2026

Codecov Results 📊

101 passed | Total: 101 | Pass Rate: 100% | Execution Time: 0ms

📊 Comparison with Base Branch

Metric Change
Total Tests
Passed Tests
Failed Tests
Skipped Tests

✨ No test changes detected

All tests are passing successfully.

✅ Patch coverage is 93.18%. Project has 3553 uncovered lines.
✅ Project coverage is 81.5%. Comparing base (base) to head (head).

Files with missing lines (5)
File Patch % Lines
auth.ts 81.73% ⚠️ 36 Missing
sentry-client.ts 82.23% ⚠️ 35 Missing
preload.ts 55.38% ⚠️ 29 Missing
status.ts 98.21% ⚠️ 2 Missing
login.ts 98.82% ⚠️ 1 Missing
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
+ Coverage    80.80%    81.50%     +0.7%
==========================================
  Files          127       127         —
  Lines        19146     19205       +59
  Branches         0         0         —
==========================================
+ Hits         15470     15652      +182
- Misses        3676      3553      -123
- Partials         0         0         —

Generated by Codecov Action

- Logout no longer clears stored auth when env var is active; just
  informs user to unset the env var
- Extract ENV_SOURCE_PREFIX constant, use .length instead of magic 4
- Keep getEnvToken/isEnvTokenActive in db/auth.ts (tightly coupled with
  getAuthToken/getAuthConfig/refreshToken in the same file)
@BYK BYK marked this pull request as ready for review March 5, 2026 16:22
BYK added 2 commits March 5, 2026 16:36
Cover the env-token-aware branches in status, logout, refresh, and
login commands to push patch coverage above 80%.

- status: 14 tests (env source display, hidden config path, no
  expiry/refresh for env tokens, credential verification, defaults)
- logout: 5 tests (env token blocks clear, correct env var name,
  fallback to SENTRY_AUTH_TOKEN)
- refresh: 6 tests (env token throws, no-refresh-token, success,
  still-valid, --json output)
- login: 1 new test (env token active → remove env var message)
Login and refresh now dynamically extract the active env var name
(SENTRY_AUTH_TOKEN or SENTRY_TOKEN) from getAuthConfig().source,
matching the behavior of logout and status commands.

Addresses BugBot feedback about inconsistent generic env var references.
@BYK BYK force-pushed the byk/env-auth-token branch from a1d2ca9 to e1038db Compare March 5, 2026 17:01
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Replace the duplicated 3-line env var name extraction pattern in
login, logout, and refresh commands with a single getActiveEnvVarName()
helper exported from db/auth.ts.

Addresses BugBot feedback about code duplication across commands.
@BYK BYK force-pushed the byk/env-auth-token branch from e1038db to 142753f Compare March 5, 2026 17:11
@BYK BYK enabled auto-merge (squash) March 5, 2026 17:32
@BYK BYK merged commit bb04650 into main Mar 5, 2026
17 checks passed
@BYK BYK deleted the byk/env-auth-token branch March 5, 2026 17:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support SENTRY_AUTH_TOKEN env var for headless/agent authentication

1 participant