Skip to content
Open
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
3 changes: 2 additions & 1 deletion app/modules/sentry/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* HTTP request tracing middleware for Hono.
*/
import type { Variables } from '@/server/types';
import { redactQuerySecrets } from '@/utils/helpers/url.helper';
import * as Sentry from '@sentry/react-router';
import { createMiddleware } from 'hono/factory';

Expand All @@ -22,7 +23,7 @@ export function sentryTracingMiddleware() {
op: 'http.server',
attributes: {
'http.method': method,
'http.url': c.req.url,
'http.url': redactQuerySecrets(c.req.url),
'http.route': path,
},
},
Expand Down
24 changes: 23 additions & 1 deletion app/utils/helpers/url.helper.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { toExternalHref } from './url.helper';
import { redactQuerySecrets, toExternalHref } from './url.helper';
import { describe, expect, test } from 'vitest';

describe('toExternalHref', () => {
Expand Down Expand Up @@ -36,3 +36,25 @@ describe('toExternalHref', () => {
expect(toExternalHref('not a url')).toBeNull();
});
});

describe('redactQuerySecrets', () => {
test('redacts the sign-in code and state from a callback URL, keeping other params', () => {
expect(
redactQuerySecrets('https://cloud.datum.net/auth/callback?code=abc123&state=xyz&lang=en')
).toBe('https://cloud.datum.net/auth/callback?code=[REDACTED]&state=[REDACTED]&lang=en');
});

test('redacts tokens in a path, a bare query string, and a fragment', () => {
expect(redactQuerySecrets('/cb?foo=1&access_token=t&ID_TOKEN=i')).toBe(
'/cb?foo=1&access_token=[REDACTED]&ID_TOKEN=[REDACTED]'
);
expect(redactQuerySecrets('code=abc&session_state=s')).toBe(
'code=[REDACTED]&session_state=[REDACTED]'
);
expect(redactQuerySecrets('/cb#refresh_token=r')).toBe('/cb#refresh_token=[REDACTED]');
});

test('leaves params that only contain a sensitive name alone', () => {
expect(redactQuerySecrets('/org?zipcode=123&tokenType=a')).toBe('/org?zipcode=123&tokenType=a');
});
});
32 changes: 32 additions & 0 deletions app/utils/helpers/url.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,35 @@ export function toExternalHref(raw?: string | null): string | null {
return null;
}
}

/**
* Query parameters that carry sign-in secrets: the one-time OIDC authorization
* code, CSRF state, and any token an identity provider puts in a URL.
*/
export const SENSITIVE_QUERY_PARAMS = [
'code',
'state',
'session_state',
'id_token',
'access_token',
'refresh_token',
'token',
];

const SENSITIVE_QUERY_PARAM_PATTERN = new RegExp(
`([?&#]|^)(${SENSITIVE_QUERY_PARAMS.join('|')})=[^&#]*`,
'gi'
);

/**
* Replace the values of sensitive query parameters with `[REDACTED]` so a URL
* can go to logs and telemetry. Works on a full URL, a path with a query, or a
* bare query string; other parameters are kept for debugging.
*
* @example
* redactQuerySecrets('/auth/callback?code=abc&foo=1')
* // '/auth/callback?code=[REDACTED]&foo=1'
*/
export function redactQuerySecrets(value: string): string {
return value.replace(SENSITIVE_QUERY_PARAM_PATTERN, '$1$2=[REDACTED]');
}
53 changes: 53 additions & 0 deletions observability/providers/otel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { REDACTED_SERVER_QUERY_PARAMS } from './otel';
import { SpanKind } from '@opentelemetry/api';
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { createRequire } from 'node:module';
import type { AddressInfo } from 'node:net';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';

// instrumentation-http is a dependency of auto-instrumentations-node, not of
// the portal, so resolve it the way the portal's NodeSDK does.
const require = createRequire(import.meta.url);
const requireFromAuto = createRequire(require.resolve('@opentelemetry/auto-instrumentations-node'));
const { HttpInstrumentation } = requireFromAuto('@opentelemetry/instrumentation-http');

describe('OpenTelemetry server span query redaction', () => {
const exporter = new InMemorySpanExporter();
const instrumentation = new HttpInstrumentation({
redactedQueryParamsServer: REDACTED_SERVER_QUERY_PARAMS,
});
let server: import('node:http').Server;
let baseUrl: string;

beforeAll(async () => {
instrumentation.setTracerProvider(
new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] })
);
instrumentation.enable();
// Load http after enabling so the instrumentation patches it.
const http = require('node:http') as typeof import('node:http');
server = http.createServer((_req, res) => res.end('ok'));
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});

afterAll(async () => {
instrumentation.disable();
await new Promise((resolve) => server.close(resolve));
});

it('redacts the sign-in code and signed-storage params but keeps ordinary ones', async () => {
await fetch(`${baseUrl}/auth/callback?code=one-time-code&X-Amz-Signature=sig123&lang=en`);

const serverSpan = exporter.getFinishedSpans().find((span) => span.kind === SpanKind.SERVER);

expect(serverSpan?.attributes['url.path']).toBe('/auth/callback');
expect(serverSpan?.attributes['url.query']).toBe(
'code=REDACTED&X-Amz-Signature=REDACTED&lang=en'
);
});
});
26 changes: 26 additions & 0 deletions observability/providers/otel.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { env } from '../../app/utils/env/env.server';
import { SENSITIVE_QUERY_PARAMS } from '../../app/utils/helpers/url.helper';
import { BaseProvider } from './base';
import { Client, credentials, Metadata } from '@grpc/grpc-js';
import { diag, DiagConsoleLogger, DiagLogLevel, trace, SpanStatusCode } from '@opentelemetry/api';
Expand All @@ -7,6 +8,26 @@ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';

// Mirrors DEFAULT_QUERY_STRINGS_TO_REDACT in @opentelemetry/instrumentation-http
// 0.222.0, which the package does not export. The instrumentation uses its
// defaults only when redactedQueryParamsServer is unset, so an override must
// keep them or server spans start recording signed-storage credentials.
const OTEL_DEFAULT_REDACTED_QUERY_PARAMS = [
'sig',
'Signature',
'AWSAccessKeyId',
'X-Goog-Signature',
'X-Amz-Signature',
'X-Amz-Credential',
'X-Amz-Security-Token',
];

/** Query params redacted on incoming (server) HTTP spans. */
export const REDACTED_SERVER_QUERY_PARAMS = [
...OTEL_DEFAULT_REDACTED_QUERY_PARAMS,
...SENSITIVE_QUERY_PARAMS,
];

// ============================================================================
// OTEL PROVIDER
// ============================================================================
Expand Down Expand Up @@ -267,6 +288,11 @@ export class OtelProvider extends BaseProvider {
// through prom-client, so this would only duplicate them.
// - fs: a span per file system call is noise, not signal.
'@opentelemetry/instrumentation-runtime-node': { enabled: false },
// Server spans record url.query. Redact sign-in secrets such as the
// OIDC callback code on top of the package's default list.
'@opentelemetry/instrumentation-http': {
redactedQueryParamsServer: REDACTED_SERVER_QUERY_PARAMS,
},
'@opentelemetry/instrumentation-fs': { enabled: false },
}),
],
Expand Down
31 changes: 31 additions & 0 deletions observability/providers/sentry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,37 @@ describe('Sentry server-side scrubbing', () => {
expect(result.request.headers).toEqual({ host: 'cloud.datum.net', 'user-agent': 'test-agent' });
});

it('redacts the sign-in code from the request URL and query string', () => {
const event = {
type: 'transaction',
request: {
url: 'https://cloud.datum.net/auth/callback?code=one-time-code&state=s&lang=en',
query_string: 'code=one-time-code&state=s&lang=en',
},
};

const result = hooks().beforeSendTransaction(event);

expect(result.request.url).toBe(
'https://cloud.datum.net/auth/callback?code=[REDACTED]&state=[REDACTED]&lang=en'
);
expect(result.request.query_string).toBe('code=[REDACTED]&state=[REDACTED]&lang=en');
});

it('redacts a query string sent as key/value pairs', () => {
const event = {
exception: { values: [{ type: 'Error', value: 'callback failed' }] },
request: {
query_string: [
['code', 'one-time-code'],
['lang', 'en'],
],
},
};

expect(hooks().beforeSend(event, {}).request.query_string).toBe('code=[REDACTED]&lang=en');
});

it('passes events without request data through unchanged', () => {
const event = { type: 'transaction', transaction: 'GET /_healthz' };

Expand Down
26 changes: 20 additions & 6 deletions observability/providers/sentry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { shouldDropSentryEvent } from '../../app/modules/sentry/filters';
import { env } from '../../app/utils/env/env.server';
import { redactQuerySecrets } from '../../app/utils/helpers/url.helper';
import { BaseProvider } from './base';
import { trace } from '@opentelemetry/api';
import * as Sentry from '@sentry/react-router';
Expand All @@ -17,10 +18,20 @@ function withoutSensitiveHeaders(headers: Record<string, unknown>): Record<strin
);
}

// The SDK sends query_string as a string, an object, or a list of pairs.
function redactQueryString(query: unknown): string {
const asString =
typeof query === 'string'
? query
: new URLSearchParams(query as Record<string, string>).toString();
return redactQuerySecrets(asString);
}

/**
* Strip cookies and auth headers from an error or transaction event.
* The session cookie holds the raw access and refresh tokens, and
* `sendDefaultPii` makes the SDK attach it to every event.
* Strip cookies and auth headers from an error or transaction event, and
* redact sign-in secrets (such as the OIDC `code`) from the request URL and
* query string. The session cookie holds the raw access and refresh tokens,
* and `sendDefaultPii` makes the SDK attach it to every event.
* Returns a new event; the input is not modified.
*/
export function scrubSensitiveRequestData<T extends Record<string, any>>(event: T): T {
Expand All @@ -29,9 +40,12 @@ export function scrubSensitiveRequestData<T extends Record<string, any>>(event:

if (request) {
const { cookies: _cookies, ...rest } = request;
scrubbed.request = rest.headers
? { ...rest, headers: withoutSensitiveHeaders(rest.headers) }
: rest;
scrubbed.request = {
...rest,
...(rest.headers && { headers: withoutSensitiveHeaders(rest.headers) }),
...(typeof rest.url === 'string' && { url: redactQuerySecrets(rest.url) }),
...(rest.query_string != null && { query_string: redactQueryString(rest.query_string) }),
};
}

const responseHeaders = contexts?.response?.headers;
Expand Down
Loading