-
-
Notifications
You must be signed in to change notification settings - Fork 6
feat(custom-headers): add SENTRY_CUSTOM_HEADERS for self-hosted proxy auth #761
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BYK
wants to merge
3
commits into
main
Choose a base branch
from
byk/feat-custom-headers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,220 @@ | ||
| /** | ||
| * Custom Headers for Self-Hosted Sentry | ||
| * | ||
| * Parses `SENTRY_CUSTOM_HEADERS` env var (or `defaults.headers` from SQLite) | ||
| * and injects user-specified HTTP headers into all requests to self-hosted | ||
| * Sentry instances. Designed for environments behind reverse proxies | ||
| * (e.g., Google IAP, Cloudflare Access) that require extra headers. | ||
| * | ||
| * Format: semicolon-separated `Name: Value` pairs (newlines also accepted). | ||
| * | ||
| * @example | ||
| * ```bash | ||
| * # Single header | ||
| * SENTRY_CUSTOM_HEADERS="X-IAP-Token: abc123" | ||
| * | ||
| * # Multiple headers | ||
| * SENTRY_CUSTOM_HEADERS="X-IAP-Token: abc123; X-Forwarded-For: 10.0.0.1" | ||
| * | ||
| * # Via defaults command | ||
| * sentry cli defaults headers "X-IAP-Token: abc123" | ||
| * ``` | ||
| */ | ||
|
|
||
| import { getConfiguredSentryUrl } from "./constants.js"; | ||
| import { getDefaultHeaders } from "./db/defaults.js"; | ||
| import { getEnv } from "./env.js"; | ||
| import { ConfigError } from "./errors.js"; | ||
| import { logger } from "./logger.js"; | ||
| import { isSentrySaasUrl } from "./sentry-urls.js"; | ||
|
|
||
| const log = logger.withTag("custom-headers"); | ||
|
|
||
| /** | ||
| * Header names that must not be overridden via custom headers. | ||
| * These are managed by the CLI's own request pipeline and overriding | ||
| * them would break authentication, content negotiation, or tracing. | ||
| */ | ||
| const FORBIDDEN_HEADER_NAMES = new Set([ | ||
| "authorization", | ||
| "host", | ||
| "content-type", | ||
| "content-length", | ||
| "user-agent", | ||
| "sentry-trace", | ||
| "baggage", | ||
| ]); | ||
|
|
||
| /** | ||
| * RFC 7230 token characters for header field names. | ||
| * Header names consist of visible ASCII characters except delimiters. | ||
| */ | ||
| const VALID_HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~\w]+$/; | ||
|
|
||
| /** Splits on semicolons and newlines (both valid header separators). */ | ||
| const HEADER_SEPARATOR_RE = /[;\n]/; | ||
|
|
||
| /** Strips trailing carriage return from a line (Windows line endings). */ | ||
| const TRAILING_CR_RE = /\r$/; | ||
|
|
||
| /** Cached parsed headers (from env var or defaults). `undefined` = not yet parsed. */ | ||
| let cachedHeaders: readonly [string, string][] | undefined; | ||
|
|
||
| /** Tracks the raw source string that produced `cachedHeaders`, for invalidation. */ | ||
| let cachedRawSource: string | undefined; | ||
|
|
||
| /** Whether the SaaS warning has already been logged this session. */ | ||
| let saasWarningLogged = false; | ||
|
|
||
| /** | ||
| * Parse a raw custom headers string into validated name/value pairs. | ||
| * | ||
| * Accepts semicolon-separated or newline-separated `Name: Value` entries. | ||
| * Empty segments and whitespace-only segments are silently skipped. | ||
| * | ||
| * @param raw - Raw header string (from env var or defaults) | ||
| * @returns Array of `[name, value]` tuples in declaration order | ||
| * @throws {ConfigError} On malformed segments or forbidden header names | ||
| */ | ||
| export function parseCustomHeaders(raw: string): readonly [string, string][] { | ||
| const results: [string, string][] = []; | ||
|
|
||
| // Split on semicolons and newlines | ||
| const segments = raw.split(HEADER_SEPARATOR_RE); | ||
|
|
||
| for (const segment of segments) { | ||
| const trimmed = segment.replace(TRAILING_CR_RE, "").trim(); | ||
| if (!trimmed) { | ||
| continue; | ||
| } | ||
|
|
||
| const colonIndex = trimmed.indexOf(":"); | ||
| if (colonIndex === -1) { | ||
| throw new ConfigError( | ||
| `Invalid header in SENTRY_CUSTOM_HEADERS: '${trimmed}'. Expected 'Name: Value' format.` | ||
| ); | ||
| } | ||
|
|
||
| const name = trimmed.slice(0, colonIndex).trim(); | ||
| const value = trimmed.slice(colonIndex + 1).trim(); | ||
|
|
||
| if (!name) { | ||
| throw new ConfigError( | ||
| `Invalid header in SENTRY_CUSTOM_HEADERS: empty header name in '${trimmed}'.` | ||
| ); | ||
| } | ||
|
|
||
| if (!VALID_HEADER_NAME_RE.test(name)) { | ||
| throw new ConfigError( | ||
| `Invalid header name '${name}' in SENTRY_CUSTOM_HEADERS. Header names must contain only alphanumeric characters, hyphens, and RFC 7230 token characters.` | ||
| ); | ||
| } | ||
|
|
||
| if (FORBIDDEN_HEADER_NAMES.has(name.toLowerCase())) { | ||
| throw new ConfigError( | ||
| `Cannot override reserved header '${name}' in SENTRY_CUSTOM_HEADERS. This header is managed by the CLI.` | ||
| ); | ||
| } | ||
|
|
||
| results.push([name, value]); | ||
| } | ||
|
|
||
| return results; | ||
| } | ||
|
|
||
| /** | ||
| * Check whether the current target is a self-hosted Sentry instance. | ||
| * | ||
| * Self-hosted = `SENTRY_HOST` or `SENTRY_URL` is set to a non-SaaS URL. | ||
| * Returns false if no custom URL is configured (implying SaaS) or if the | ||
| * configured URL points to `*.sentry.io`. | ||
| */ | ||
| function isSelfHosted(): boolean { | ||
| const configured = getConfiguredSentryUrl(); | ||
| if (!configured) { | ||
| return false; | ||
| } | ||
| return !isSentrySaasUrl(configured); | ||
| } | ||
|
|
||
| /** | ||
| * Resolve the raw custom headers string from env var or SQLite defaults. | ||
| * | ||
| * Priority: `SENTRY_CUSTOM_HEADERS` env var > `defaults.headers` in SQLite. | ||
| * Returns undefined when no headers are configured. | ||
| */ | ||
| function resolveRawHeaders(): string | undefined { | ||
| const envValue = getEnv().SENTRY_CUSTOM_HEADERS; | ||
| if (envValue?.trim()) { | ||
| return envValue.trim(); | ||
| } | ||
|
|
||
| const dbValue = getDefaultHeaders(); | ||
| if (dbValue?.trim()) { | ||
| return dbValue.trim(); | ||
| } | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| /** | ||
| * Get the parsed custom headers for the current session. | ||
| * | ||
| * Returns an empty array when: | ||
| * - No custom headers are configured (env var or defaults) | ||
| * - The target is not a self-hosted instance (warns once if headers are set) | ||
| * | ||
| * Parsed results are cached; the self-hosted guard is re-evaluated per call | ||
| * because `SENTRY_HOST` can be set dynamically by URL argument parsing. | ||
| */ | ||
| export function getCustomHeaders(): readonly [string, string][] { | ||
| const raw = resolveRawHeaders(); | ||
| if (!raw) { | ||
| return []; | ||
| } | ||
|
|
||
| // Self-hosted guard: warn once and skip on SaaS | ||
| if (!isSelfHosted()) { | ||
| if (!saasWarningLogged) { | ||
| saasWarningLogged = true; | ||
| log.warn( | ||
| "SENTRY_CUSTOM_HEADERS is set but no self-hosted Sentry instance is configured. Headers will be ignored." | ||
| ); | ||
| } | ||
| return []; | ||
| } | ||
|
|
||
| // Return cached result if the raw source hasn't changed | ||
| if (cachedHeaders !== undefined && cachedRawSource === raw) { | ||
| return cachedHeaders; | ||
| } | ||
|
|
||
| cachedHeaders = parseCustomHeaders(raw); | ||
| cachedRawSource = raw; | ||
| return cachedHeaders; | ||
| } | ||
|
|
||
| /** | ||
| * Apply custom headers to a `Headers` instance. | ||
| * | ||
| * Reads from the env var or SQLite defaults, validates, and sets each header. | ||
| * No-op when no custom headers are configured or when targeting SaaS. | ||
| * | ||
| * @param headers - The `Headers` instance to modify in-place | ||
| */ | ||
| export function applyCustomHeaders(headers: Headers): void { | ||
| const customHeaders = getCustomHeaders(); | ||
| for (const [name, value] of customHeaders) { | ||
| headers.set(name, value); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Reset module-level caches. Exported for testing only. | ||
| * @internal | ||
| */ | ||
| export function _resetCustomHeadersCache(): void { | ||
| cachedHeaders = undefined; | ||
| cachedRawSource = undefined; | ||
| saasWarningLogged = false; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.