diff --git a/.changeset/nextjs-otel3-provider-fallback.md b/.changeset/nextjs-otel3-provider-fallback.md new file mode 100644 index 000000000..733cfbc7c --- /dev/null +++ b/.changeset/nextjs-otel3-provider-fallback.md @@ -0,0 +1,7 @@ +--- +'@bugsee/nextjs': minor +--- + +The zero-config OpenTelemetry provider now falls back to `@opentelemetry/sdk-trace` (its `TracerProvider`) when `@opentelemetry/sdk-trace-base` is not installed. OpenTelemetry JS 3 removed `sdk-trace-base`, so before this an OpenTelemetry 3 install silently left the zero-config provider `unavailable`. `sdk-trace-base` is still preferred when both are installed, so OpenTelemetry 1.x/2.x installs behave as before. + +`@opentelemetry/sdk-trace` (`>=2.9.0`) is now declared as an optional peer next to `@opentelemetry/sdk-trace-base` (`>=1.0.0 <3`). diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md new file mode 100644 index 000000000..edb2a647e --- /dev/null +++ b/.changeset/opentelemetry-3-support.md @@ -0,0 +1,17 @@ +--- +'@bugsee/opentelemetry': minor +'@bugsee/performance': minor +'@bugsee/protocol': minor +--- + +Support OpenTelemetry JS 3.x (issue #94). + +OpenTelemetry JS 3.0 removed `@opentelemetry/sdk-trace-base` and replaced it with `@opentelemetry/sdk-trace`, and `@opentelemetry/api` 1.10 widened span attributes to the spec's `AnyValue`. `@bugsee/opentelemetry` and `@bugsee/nextjs` (peer ranges) now declare `@opentelemetry/sdk-trace` (`>=2.9.0`) as an optional peer next to `@opentelemetry/sdk-trace-base` (now `>=1.0.0 <3`); `sdk-trace` exists from 2.9 and exports the same `TracerProvider`. Both stay optional: produce-only users install neither. On OpenTelemetry 3 register the processor with `new TracerProvider({ spanProcessors: [processor] })` from `@opentelemetry/sdk-trace` (on 3.x `sdk-trace` is the only SDK package and `BasicTracerProvider` no longer exists; `sdk-trace` 2.9+ exports the same `TracerProvider`). OpenTelemetry 3 itself needs Node.js 22.15 or newer; `@bugsee/opentelemetry` does not import OpenTelemetry and still runs on the Node versions the SDK supports. + +Complex span attributes (OpenTelemetry API 1.10 `AnyValue`) are now handled deliberately. Known limitation, unchanged by this release: SQL literal redaction can be defeated by comments, backslash escapes and dollar quoting shifting its quote pairing (bugsee/bugsee-javascript#109). Consumed scalars and small homogeneous scalar arrays are unchanged (a scalar string is capped at 32 KiB); a byte array becomes base64; a `bigint` becomes a number when exact and decimal text otherwise (it used to reach the transaction as a value JSON cannot serialize); `null`, `undefined`, functions and symbols drop the attribute; nested maps and mixed arrays become a bounded JSON-safe copy that the span sanitizer and `setSpanFilter` now see as a tree, so nested sensitive keys (`user: { password }`, `http.request.headers: { authorization }`) are redacted by default. What remains complex is flattened to a bounded JSON string when the transaction is recorded. The copy never throws and is bounded in work as well as size (leaf, key, node, depth and length caps). A raw byte array that Bugsee exports itself (a `Uint8Array`, `ArrayBuffer` or `DataView` attribute on a span Bugsee produced) is sent as OTLP `bytesValue` (valid base64) when it fits (up to 6144 bytes) and as a `stringValue` carrying the truncation marker when it was cut, so a strict collector never sees a marker inside `bytesValue`; a consumed span's bytes are already a base64 string by then and export as `stringValue`. A URL attribute keeps exporting its href (credentials removed), an Error its name and message, and a Date its ISO string. Arrays of one scalar type that contain null entries pass through unchanged. The default sanitizer now also redacts the current GenAI content attributes (`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.definitions`, `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`). One hostile attribute (a Proxy that throws, a cycle, an enormous string) no longer rejects the whole export batch. + +`createBugseeSpanProcessor` now ignores `onEnd` after `shutdown()`. + +The same bounding now applies to every span the SDK records itself (`setAttribute`, `recordChildSpan`, `recordExternal`), not only consumed OpenTelemetry spans: the nested redaction walk is only run on a bounded copy, with a shared per-span node and character budget (raw cyclic or branching values used to take seconds to forever). A key too long to keep has its value redacted; a statement cut by a length cap no longer leaves an open SQL literal in the clear, and a map leaf cut inside a token (a JWT after its payload, a `ghp_` prefix) drops the unfinished token, and an unbroken run such as `id_token=` keeps its prefix but backs off before a secret the cut lands inside, including a JWT whose payload contains a second `eyJ` (a long map-leaf URL is cut back to `https:` by the ordinary token-boundary rule; a top-level string is only cut, because secret-shape scanning does not apply to it, as before: top-level strings, scalar arrays and nested map keys are not shape-scanned); scalar-array attribute values are stored as copies, never aliases of the application's array; and a statement carried as a map or array has its string leaves' literals redacted. `isSensitiveKey` (`@bugsee/protocol`) now normalises its denylist once. + +New exports from `@bugsee/protocol`: `unfinishedSecretStart`. New exports from `@bugsee/performance` (some also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue`, `safeAnyValue`, `asBytes`, `boundedBase64` and the `MAX_ATTRIBUTE_*` limits. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a164e30f..59f309651 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,6 +90,10 @@ jobs: # hole the e2e job exists to close. - name: Harness unit tests (vitest) run: pnpm exec turbo run test:unit + env: + # This job runs Node 22, which OpenTelemetry JS 3.x supports (>= 22.15): the otel3-compat suite must + # RUN here. With this set, a too-old Node fails that suite instead of skipping it silently. + BUGSEE_REQUIRE_OTEL3: '1' # End-to-end harnesses: the REAL SDK booted in real node/bun/deno processes against a # mock collector, plus the real-framework suites (nuxt / sveltekit / astro / next). diff --git a/dev-packages/otel3-compat/package.json b/dev-packages/otel3-compat/package.json new file mode 100644 index 000000000..a2a92d71a --- /dev/null +++ b/dev-packages/otel3-compat/package.json @@ -0,0 +1,22 @@ +{ + "name": "@bugsee/otel3-compat", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Runs @bugsee/opentelemetry against a REAL @opentelemetry/sdk-trace@3 (OpenTelemetry JS 3.x). Separate from the package itself because sdk-trace@3 peers @opentelemetry/api >=1.10 <1.11 while sdk-trace-base@2 (the package's own devDependency) peers <1.10: one workspace package cannot satisfy both. Node >=22.15 only (OTel 3's engines floor); the suite skips cleanly below it.", + "engines": { + "node": ">=18" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test:unit": "vitest run", + "test": "vitest run" + }, + "devDependencies": { + "@bugsee/opentelemetry": "workspace:*", + "@bugsee/performance": "workspace:*", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/sdk-trace": "^3.0.0" + }, + "license": "MIT" +} diff --git a/dev-packages/otel3-compat/src/node-gate.test.ts b/dev-packages/otel3-compat/src/node-gate.test.ts new file mode 100644 index 000000000..133e7f8a2 --- /dev/null +++ b/dev-packages/otel3-compat/src/node-gate.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest'; +import { + nodeAtLeast, + OTEL3_MIN_NODE, + otel3Required, + otel3Supported, + skipIsForbidden, +} from './node-gate'; + +describe('nodeAtLeast', () => { + it.each([ + ['22.15.0', true], + ['22.15.1', true], + ['22.16.0', true], + ['23.0.0', true], + ['24.15.0', true], + ['22.14.9', false], + ['22.12.0', false], + ['20.19.0', false], + ['18.20.4', false], + ])('%s -> %s against the OTel 3 floor', (version, expected) => { + expect(nodeAtLeast(version)).toBe(expected); + }); + + it('treats missing trailing parts as zero and honours a custom floor', () => { + expect(nodeAtLeast('22.15')).toBe(true); + expect(nodeAtLeast('22')).toBe(false); + expect(nodeAtLeast('20.6.0', [20, 6, 0])).toBe(true); + expect(nodeAtLeast('20.5.9', [20, 6, 0])).toBe(false); + }); + + it('pins the floor to what sdk-trace@3 declares', () => { + expect(OTEL3_MIN_NODE).toEqual([22, 15, 0]); + }); + + it('agrees with the running Node', () => { + expect(otel3Supported).toBe(nodeAtLeast(process.versions.node)); + }); +}); + +describe('skipIsForbidden (BUGSEE_REQUIRE_OTEL3)', () => { + it('is on only for the exact value "1"', () => { + expect(skipIsForbidden({ BUGSEE_REQUIRE_OTEL3: '1' })).toBe(true); + for (const v of [undefined, '', '0', 'true', 'yes', ' 1']) { + expect(skipIsForbidden({ BUGSEE_REQUIRE_OTEL3: v })).toBe(false); + } + expect(skipIsForbidden({})).toBe(false); + }); + + it('reads the real environment for the exported flag', () => { + expect(otel3Required).toBe(skipIsForbidden(process.env)); + }); +}); diff --git a/dev-packages/otel3-compat/src/node-gate.ts b/dev-packages/otel3-compat/src/node-gate.ts new file mode 100644 index 000000000..9b3dd90c6 --- /dev/null +++ b/dev-packages/otel3-compat/src/node-gate.ts @@ -0,0 +1,36 @@ +// OpenTelemetry JS 3.x declares `engines.node >=22.15.0` on core / resources / sdk-trace. CI runs Node 22 +// (>= 22.15 satisfies it), but a developer machine can have an older Node: the OTel 3 suites stand down below +// that floor instead of failing, unless BUGSEE_REQUIRE_OTEL3=1 (see skipIsForbidden). + +/** The first Node release OpenTelemetry JS 3.x supports. */ +export const OTEL3_MIN_NODE = [22, 15, 0] as const; + +/** Compare a dotted Node version (`process.versions.node` shape) against `min`. */ +export function nodeAtLeast( + version: string, + min: readonly [number, number, number] = OTEL3_MIN_NODE, +): boolean { + const parts = version.split('.').map((part) => Number.parseInt(part, 10)); + for (let i = 0; i < 3; i++) { + const have = parts[i] ?? 0; + const need = min[i] as number; + if (have !== need) return have > need; + } + return true; +} + +/** True when the running Node can load OpenTelemetry JS 3.x. */ +export const otel3Supported: boolean = nodeAtLeast(process.versions.node); + +/** Suite title suffix that states WHY the suite is skipped, so a skip in the report is self-explanatory. */ +export const OTEL3_SKIP_NOTE = 'needs Node >= 22.15 (OpenTelemetry JS 3.x engines floor)'; + +/** + * Whether a skip of the OTel 3 suite must be treated as a FAILURE. A silent skip on a runner whose Node is too + * old would let the 3.x coverage rot unnoticed, so the CI job that runs Node 22 sets `BUGSEE_REQUIRE_OTEL3=1`. + */ +export function skipIsForbidden(env: Record): boolean { + return env.BUGSEE_REQUIRE_OTEL3 === '1'; +} + +export const otel3Required: boolean = skipIsForbidden(process.env); diff --git a/dev-packages/otel3-compat/src/provider.test.ts b/dev-packages/otel3-compat/src/provider.test.ts new file mode 100644 index 000000000..a62a2ac19 --- /dev/null +++ b/dev-packages/otel3-compat/src/provider.test.ts @@ -0,0 +1,317 @@ +import { + createBugseeSpanProcessor, + readableSpanToConsumed, + toOtlpExportRequest, +} from '@bugsee/opentelemetry'; +import { flattenAttributes, type TransactionWire } from '@bugsee/performance'; +import { type Context, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; +import { describe, expect, it } from 'vitest'; +import { OTEL3_SKIP_NOTE, otel3Required, otel3Supported } from './node-gate'; + +// The documented registration on OpenTelemetry JS 3.x: `new TracerProvider({ spanProcessors: [...] })` from +// `@opentelemetry/sdk-trace` (3.0 removed `sdk-trace-base`, and `BasicTracerProvider` was renamed +// `TracerProvider`). Spans are produced by the REAL SDK, not a hand-built ReadableSpan, so a change in the +// 3.x ReadableSpan shape (parent field, attribute widening, time encoding) fails here. + +type Sdk = typeof import('@opentelemetry/sdk-trace'); + +async function boot(): Promise<{ + sdk: Sdk; + transactions: TransactionWire[]; + errors: unknown[]; + provider: InstanceType; + tracer: ReturnType['getTracer']>; + seen: Parameters['onEnd']>[0][]; +}> { + const sdk = await import('@opentelemetry/sdk-trace'); + const transactions: TransactionWire[] = []; + const errors: unknown[] = []; + const seen: Parameters['onEnd']>[0][] = []; + const inner = createBugseeSpanProcessor({ + onTransaction: (t) => transactions.push(t), + onError: (e) => errors.push(e), + }); + // A spy in front of the Bugsee processor records the REAL ReadableSpan the SDK hands over. + const processor = { + onStart: () => inner.onStart(), + onEnd: (span: Parameters[0]) => { + seen.push(span); + inner.onEnd(span); + }, + forceFlush: () => inner.forceFlush(), + shutdown: () => inner.shutdown(), + }; + const provider = new sdk.TracerProvider({ + resource: undefined, + spanProcessors: [processor], + }); + return { + sdk, + transactions, + errors, + provider, + tracer: provider.getTracer('compat', '1.0.0'), + seen, + }; +} + +// CI sets BUGSEE_REQUIRE_OTEL3=1 on the Node 22 job: there the suite below must RUN, so an unsupported Node +// fails here instead of skipping silently. +describe.runIf(otel3Required)('OpenTelemetry 3 suite is mandatory in this environment', () => { + it(`runs on a Node that supports it (${OTEL3_SKIP_NOTE})`, () => { + expect(otel3Supported).toBe(true); + }); +}); + +describe.skipIf(!otel3Supported)( + `a real @opentelemetry/sdk-trace@3 provider (${OTEL3_SKIP_NOTE})`, + () => { + it('delivers a finished span to the Bugsee processor registered through spanProcessors', async () => { + const { provider, tracer, transactions, errors } = await boot(); + + tracer.startSpan('GET /users').end(); + await provider.shutdown(); + + expect(errors).toEqual([]); + expect(transactions).toHaveLength(1); + expect(transactions[0]?.name).toBe('GET /users'); + }); + + it('exposes the 3.x ReadableSpan shape ReadableSpanLike reads (parentSpanContext, HrTime, status)', async () => { + const { tracer, seen } = await boot(); + const root = tracer.startSpan('root'); + const ctx = trace.setSpan(ROOT_CONTEXT, root); + const child = tracer.startSpan('child', {}, ctx); + child.end(); + root.end(); + + const [childSpan, rootSpan] = seen; + // 3.x: the parent is `parentSpanContext` only; the 1.x `parentSpanId` field is gone. + expect('parentSpanId' in (childSpan as object)).toBe(false); + expect(childSpan?.parentSpanContext?.spanId).toBe(root.spanContext().spanId); + expect(rootSpan?.parentSpanContext).toBeUndefined(); + expect(childSpan?.startTime).toEqual(expect.arrayContaining([expect.any(Number)])); + expect(childSpan?.startTime).toHaveLength(2); + expect(childSpan?.status).toEqual({ code: SpanStatusCode.UNSET }); + }); + + it('rebuilds the span tree from nested spans: one transaction per trace, children linked by parent id', async () => { + const { provider, tracer, transactions, errors } = await boot(); + + const root = tracer.startSpan('GET /orders', { kind: SpanKind.SERVER }); + const rootCtx = trace.setSpan(ROOT_CONTEXT, root); + const db = tracer.startSpan('db.query', { kind: SpanKind.CLIENT }, rootCtx); + const dbCtx = trace.setSpan(rootCtx, db); + const driver = tracer.startSpan('driver.send', {}, dbCtx); + driver.end(); + db.end(); + root.end(); + await provider.shutdown(); + + expect(errors).toEqual([]); + expect(transactions).toHaveLength(1); + const txn = transactions[0] as TransactionWire; + expect(txn.traceId).toBe(root.spanContext().traceId); + expect(txn.spanId).toBe(root.spanContext().spanId); + expect(txn.name).toBe('GET /orders'); + expect(txn.spans.map((s) => s.operation).sort()).toEqual(['db.query', 'driver.send']); + const dbWire = txn.spans.find((s) => s.operation === 'db.query'); + const driverWire = txn.spans.find((s) => s.operation === 'driver.send'); + expect(dbWire?.spanId).toBe(db.spanContext().spanId); + expect(dbWire?.parentSpanId).toBe(root.spanContext().spanId); + expect(driverWire?.parentSpanId).toBe(db.spanContext().spanId); + expect(txn.attributes?.['otel.span.kind']).toBe(SpanKind.SERVER); + expect(dbWire?.attributes?.['otel.span.kind']).toBe(SpanKind.CLIENT); + }); + + it('carries attributes of every primitive and homogeneous-array kind through unchanged', async () => { + const { provider, tracer, transactions } = await boot(); + + const span = tracer.startSpan('attrs', { + attributes: { + s: 'x', + n: 3, + f: 1.5, + b: true, + strs: ['a', 'b'], + nums: [1, 2], + bools: [true, false], + }, + }); + span.setAttribute('late', 'set-after-start'); + span.end(); + await provider.shutdown(); + + expect(transactions[0]?.attributes).toMatchObject({ + s: 'x', + n: 3, + f: 1.5, + b: true, + strs: ['a', 'b'], + nums: [1, 2], + bools: [true, false], + late: 'set-after-start', + }); + }); + + it('keeps complex AnyValue attributes the 3.x SDK retains as bounded trees (bytes as base64), flattened at the wire', async () => { + const { provider, tracer, transactions, errors, seen } = await boot(); + const span = tracer.startSpan('complex'); + span.setAttributes({ + map: { a: { b: [1, 'x', true, null] } }, + mixed: [1, 'a', true], + bytes: new Uint8Array([102, 111, 111]), + tags: ['a', 'b'], + scalar: 1, + }); + // The SDK itself drops values with no AnyValue form (bigint/Date/function/symbol/cycle): never seen by us. + span.setAttribute('big', 10n as never); + span.end(); + await provider.shutdown(); + + expect(Object.keys(seen[0]?.attributes ?? {})).toEqual( + expect.arrayContaining(['map', 'mixed', 'bytes', 'tags', 'scalar']), + ); + expect(errors).toEqual([]); + // Consumed as TREES, so redaction can read nested keys; flattening is the later wire step. + expect(transactions[0]?.attributes).toMatchObject({ + map: { a: { b: [1, 'x', true, null] } }, + mixed: [1, 'a', true], + bytes: 'Zm9v', + tags: ['a', 'b'], + scalar: 1, + }); + expect(flattenAttributes(transactions[0]?.attributes ?? {})).toMatchObject({ + map: '{"a":{"b":[1,"x",true,null]}}', + mixed: '[1,"a",true]', + bytes: 'Zm9v', + tags: ['a', 'b'], + scalar: 1, + }); + // The whole transaction stays JSON-serializable and exportable. + expect(() => JSON.stringify(transactions)).not.toThrow(); + expect(() => JSON.stringify(toOtlpExportRequest(transactions))).not.toThrow(); + }); + + it('maps span status: OK, ERROR with a message, and UNSET', async () => { + const { provider, tracer, transactions } = await boot(); + + const ok = tracer.startSpan('ok'); + ok.setStatus({ code: SpanStatusCode.OK }); + ok.end(); + const bad = tracer.startSpan('bad'); + bad.setStatus({ code: SpanStatusCode.ERROR, message: 'TIMEOUT' }); + bad.end(); + const plain = tracer.startSpan('plain'); + plain.end(); + await provider.shutdown(); + + const byName = Object.fromEntries(transactions.map((t) => [t.name, t.status])); + expect(byName).toEqual({ ok: 'OK', bad: 'TIMEOUT', plain: 'UNKNOWN' }); + }); + + it('survives events, links, recordException and resource (lossy by design, never throws)', async () => { + const { sdk, provider, tracer, transactions, errors, seen } = await boot(); + const other = tracer.startSpan('other'); + other.end(); + + const span = tracer.startSpan('rich', { links: [{ context: other.spanContext() }] }); + span.addEvent('cache.miss', { key: 'k' }); + span.recordException(new Error('boom')); + span.setStatus({ code: SpanStatusCode.ERROR, message: 'boom' }); + span.end(); + await provider.shutdown(); + + const real = seen.find((s) => s.name === 'rich') as unknown as { + events: { name: string }[]; + links: unknown[]; + resource: { attributes: Record }; + }; + expect(real.events.map((e) => e.name)).toEqual(['cache.miss', 'exception']); + expect(real.links).toHaveLength(1); + expect(real.resource.attributes['telemetry.sdk.language']).toBe('nodejs'); + expect(errors).toEqual([]); + const txn = transactions.find((t) => t.name === 'rich') as TransactionWire; + expect(txn.status).toBe('ERROR'); + void sdk; + }); + + it('treats a remote parent as a local root, so a downstream service still yields a transaction', async () => { + const { provider, tracer, transactions } = await boot(); + const remote = { + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331', + traceFlags: 1, + isRemote: true, + }; + const ctx: Context = trace.setSpanContext(ROOT_CONTEXT, remote); + + tracer.startSpan('downstream', {}, ctx).end(); + await provider.shutdown(); + + expect(transactions).toHaveLength(1); + const txn = transactions[0] as TransactionWire; + expect(txn.traceId).toBe(remote.traceId); + expect(txn.parentSpanId).toBeUndefined(); + }); + + it('readableSpanToConsumed on a real span: ids, ms times, kind and parent', async () => { + const { tracer, seen } = await boot(); + const root = tracer.startSpan('r'); + const child = tracer.startSpan( + 'c', + { kind: SpanKind.PRODUCER }, + trace.setSpan(ROOT_CONTEXT, root), + ); + child.end(); + root.end(); + + const consumed = readableSpanToConsumed(seen[0] as never); + expect(consumed.spanId).toBe(child.spanContext().spanId); + expect(consumed.parentSpanId).toBe(root.spanContext().spanId); + expect(consumed.kind).toBe(SpanKind.PRODUCER); + expect(consumed.endTimeMs).toBeGreaterThanOrEqual(consumed.startTimeMs); + // Epoch milliseconds, not process-relative time, converted from the SDK's [seconds, nanos] HrTime. + const [startSec, startNanos] = (seen[0] as { startTime: [number, number] }).startTime; + const [endSec, endNanos] = (seen[0] as { endTime: [number, number] }).endTime; + expect(consumed.startTimeMs).toBe(startSec * 1000 + startNanos / 1e6); + expect(consumed.endTimeMs).toBe(endSec * 1000 + endNanos / 1e6); + expect(consumed.startTimeMs).toBeGreaterThan(1.7e12); + }); + + it('feeds the OTLP export path: a consumed 3.x trace round-trips to a valid ExportTraceServiceRequest', async () => { + const { provider, tracer, transactions } = await boot(); + const root = tracer.startSpan('GET /pay', { attributes: { 'http.route': '/pay' } }); + const child = tracer.startSpan('charge', {}, trace.setSpan(ROOT_CONTEXT, root)); + child.end(); + root.end(); + await provider.shutdown(); + + const request = toOtlpExportRequest(transactions, { resource: { 'service.name': 'compat' } }); + const spans = request.resourceSpans[0]?.scopeSpans[0]?.spans ?? []; + expect(spans).toHaveLength(2); + const byName = Object.fromEntries(spans.map((s) => [s.name, s])); + expect(byName['GET /pay']?.spanId).toBe(root.spanContext().spanId); + expect(byName.charge?.parentSpanId).toBe(root.spanContext().spanId); + expect(byName['GET /pay']?.traceId).toBe(root.spanContext().traceId); + const keys = (byName['GET /pay']?.attributes ?? []).map((kv) => kv.key); + expect(keys).toContain('http.route'); + expect(JSON.parse(JSON.stringify(request))).toEqual(request); + }); + + it('keeps the host span.end() alive when the Bugsee sink throws (contained boundary on the real SDK)', async () => { + const sdk = await import('@opentelemetry/sdk-trace'); + const errors: unknown[] = []; + const processor = createBugseeSpanProcessor({ + onTransaction: () => { + throw new Error('sink down'); + }, + onError: (e) => errors.push(e), + }); + const provider = new sdk.TracerProvider({ spanProcessors: [processor] }); + + expect(() => provider.getTracer('t').startSpan('x').end()).not.toThrow(); + expect(errors).toHaveLength(1); + }); + }, +); diff --git a/dev-packages/otel3-compat/src/types.test-d.ts b/dev-packages/otel3-compat/src/types.test-d.ts new file mode 100644 index 000000000..fc4c0124f --- /dev/null +++ b/dev-packages/otel3-compat/src/types.test-d.ts @@ -0,0 +1,22 @@ +import type { ReadableSpanLike } from '@bugsee/opentelemetry'; +import { createBugseeSpanProcessor, readableSpanToConsumed } from '@bugsee/opentelemetry'; +import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace'; + +// Type-level drift guard against the REAL OpenTelemetry JS 3.x contract (the 2.x twin is +// packages/opentelemetry/src/span-processor.test-d.ts). `tsc --noEmit` fails here the moment 3.x's +// `ReadableSpan` stops satisfying our structural `ReadableSpanLike`, or our processor stops being a valid +// 3.x `SpanProcessor` (so `new TracerProvider({ spanProcessors: [processor] })` would no longer compile). + +declare const realSpan: ReadableSpan; + +// A real 3.x ReadableSpan is accepted wherever we read a ReadableSpanLike. Its `attributes` is the API 1.10 +// `Attributes`, widened with AnyValue (OTEP 4485). +const asLike: ReadableSpanLike = realSpan; +const consumed = readableSpanToConsumed(realSpan); + +// Our processor is assignable to 3.x's SpanProcessor (onStart(span, parentContext), optional onEnding, ...). +const asProcessor: SpanProcessor = createBugseeSpanProcessor({ onTransaction: () => {} }); + +void asLike; +void consumed; +void asProcessor; diff --git a/dev-packages/otel3-compat/tsconfig.json b/dev-packages/otel3-compat/tsconfig.json new file mode 100644 index 000000000..118a27a8b --- /dev/null +++ b/dev-packages/otel3-compat/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["node"] + }, + "include": ["src", "vitest.config.ts"] +} diff --git a/dev-packages/otel3-compat/vitest.config.ts b/dev-packages/otel3-compat/vitest.config.ts new file mode 100644 index 000000000..b75dbecd6 --- /dev/null +++ b/dev-packages/otel3-compat/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config'; + +// No product code here and therefore no coverage gate: this package only exercises @bugsee/opentelemetry +// against the real OpenTelemetry JS 3.x SDK, so it runs under `turbo run test:unit`. +export default defineConfig({ + test: { include: ['src/**/*.test.ts'] }, +}); diff --git a/dev-packages/packaging-guard/src/otel-no-deep-imports.test.ts b/dev-packages/packaging-guard/src/otel-no-deep-imports.test.ts new file mode 100644 index 000000000..edb38e8b6 --- /dev/null +++ b/dev-packages/packaging-guard/src/otel-no-deep-imports.test.ts @@ -0,0 +1,91 @@ +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +// OpenTelemetry JS 3.0 ships an `exports` map on every package, so `@opentelemetry//build/...` deep +// imports and `@opentelemetry//package.json` reads stopped resolving (issue #94, upstream #6293), and +// the `browser` field became `#platform` subpath imports. Nothing in this SDK may reach into an OTel +// package's internals: the only specifiers we may write are a package's public entry points. This scans +// every tracked source/config file so a new deep import fails here, in the unit gate, not in a customer's +// bundler. + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); + +/** Public subpaths an OTel package documents in its `exports` map (api 1.10 ships `./experimental`). */ +const PUBLIC_SUBPATHS = new Set(['@opentelemetry/api/experimental']); + +// Built from pieces so this file's own text never matches itself. +const SPECIFIER = new RegExp(`@${'opentelemetry'}/[a-z0-9-]+/[A-Za-z0-9_.@/-]+`, 'g'); +const NODE_MODULES_PATH = new RegExp(`node_modules/@${'opentelemetry'}`); + +/** Every `@opentelemetry//` specifier (and any node_modules path into OTel) in `text`. */ +export function findOtelDeepImports(text: string): string[] { + const found = (text.match(SPECIFIER) ?? []).filter((specifier) => { + const parts = specifier.split('/'); + return !PUBLIC_SUBPATHS.has(parts.slice(0, 3).join('/')) || parts.length > 3; + }); + if (NODE_MODULES_PATH.test(text)) found.push('node_modules/@opentelemetry path'); + return found; +} + +describe('findOtelDeepImports', () => { + it.each([ + "import x from '@opentelemetry/sdk-trace-base/build/src/Span';", + "require('@opentelemetry/core/build/esm/index.js')", + "require.resolve('@opentelemetry/api/package.json')", + 'import("@opentelemetry/sdk-trace/dist/index.mjs")', + "readFileSync('node_modules/@opentelemetry/api/package.json')", + "join(here, '../node_modules/@opentelemetry/api')", + "import y from '@opentelemetry/api/experimental/extra';", + ])('flags %s', (source) => { + expect(findOtelDeepImports(source).length).toBeGreaterThan(0); + }); + + it.each([ + "import { trace } from '@opentelemetry/api';", + "import('@opentelemetry/sdk-trace-base')", + "import('@opentelemetry/sdk-trace')", + "import { x } from '@opentelemetry/api/experimental';", + "import z from '@bugsee/opentelemetry';", + 'plain text about OpenTelemetry', + ])('allows %s', (source) => { + expect(findOtelDeepImports(source)).toEqual([]); + }); +}); + +const SCANNED = /\.(?:[cm]?[jt]sx?|json|vue|svelte|astro)$/; + +/** Tracked and untracked-but-not-ignored files, so a new file is checked before it is committed. */ +const files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { + cwd: root, + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, +}) + .split('\n') + .filter((file) => file !== '' && SCANNED.test(file)) + // This file's own fixtures are deliberate deep imports. + .filter((file) => !file.endsWith('otel-no-deep-imports.test.ts')); + +describe('no package reaches into OpenTelemetry internals', () => { + it('scans a meaningful set of files', () => { + expect(files.length).toBeGreaterThan(500); + expect(files).toContain('packages/opentelemetry/src/span-processor.ts'); + expect(files).toContain('packages/nextjs/src/otel-provider.ts'); + }); + + it('finds no deep import, package.json read or node_modules path into @opentelemetry/*', () => { + const offenders: string[] = []; + for (const file of files) { + let text: string; + try { + text = readFileSync(join(root, file), 'utf8'); + } catch { + continue; // deleted in the working tree but still indexed + } + for (const hit of findOtelDeepImports(text)) offenders.push(`${relative('.', file)}: ${hit}`); + } + expect(offenders).toEqual([]); + }); +}); diff --git a/dev-packages/packaging-guard/src/otel-peers.test.ts b/dev-packages/packaging-guard/src/otel-peers.test.ts new file mode 100644 index 000000000..d98e4a287 --- /dev/null +++ b/dev-packages/packaging-guard/src/otel-peers.test.ts @@ -0,0 +1,45 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +// OpenTelemetry JS 3.0 (2026-10-20) REMOVED `@opentelemetry/sdk-trace-base` / `-web` / `-node` and replaced +// them with one `@opentelemetry/sdk-trace` (issue #94). A package that still lists only `sdk-trace-base` +// as its OTel SDK peer points OTel 3 users at a package that no longer exists on 3.x. Every package that +// names the SDK as an optional peer must name BOTH, split by OTel major, and keep both optional (a +// produce-only user installs neither). + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); + +interface Manifest { + peerDependencies?: Record; + peerDependenciesMeta?: Record; +} + +const read = (dir: string): Manifest => + JSON.parse(readFileSync(join(root, 'packages', dir, 'package.json'), 'utf8')) as Manifest; + +describe.each([ + 'opentelemetry', + 'nextjs', +])('@bugsee/%s declares the OTel SDK peers by major', (dir) => { + const manifest = read(dir); + + it('sdk-trace-base covers OTel 1.x/2.x only (it has no 3.x release)', () => { + expect(manifest.peerDependencies?.['@opentelemetry/sdk-trace-base']).toBe('>=1.0.0 <3'); + }); + + it('sdk-trace covers 2.9+ (a hard dependency of sdk-trace-base 2.9+) and 3.x', () => { + expect(manifest.peerDependencies?.['@opentelemetry/sdk-trace']).toBe('>=2.9.0'); + }); + + it('keeps every OTel peer optional', () => { + for (const name of [ + '@opentelemetry/api', + '@opentelemetry/sdk-trace-base', + '@opentelemetry/sdk-trace', + ]) { + expect(manifest.peerDependenciesMeta?.[name]?.optional, name).toBe(true); + } + }); +}); diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 1a7e6add4..815424407 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -596,6 +596,28 @@ its first consumer. Design references (Sentry/Faro/Datadog/Honeycomb/Embrace) in — STRUCTURAL `ReadableSpanLike`/`SpanProcessor` (no OTel import; covers SDK 1.x `parentSpanId` + 2.x `parentSpanContext`/`isRemote`→local-root); `@opentelemetry/*` are OPTIONAL peers (verified not pulled into node_modules) + a dev-only `.test-d.ts` drift guard. **OTel spans now flow INTO Bugsee.** +- **OTel JS 3.x compatibility — DONE (2026-10-21, issue #94, PR #104)** → `docs/design/opentelemetry-integration.md` + "OpenTelemetry JS major compatibility". (1) `@bugsee/opentelemetry` + `@bugsee/nextjs` peers: `sdk-trace-base` + `>=1.0.0 <3` (OTel 1.x/2.x) AND `sdk-trace` `>=2.9.0` (sdk-trace exists from 2.9, a hard dependency of + sdk-trace-base 2.9+, and is the only SDK package on 3.x, where sdk-trace-base was REMOVED and `BasicTracerProvider` + renamed `TracerProvider`), all optional; guard `packaging-guard/src/otel-peers.test.ts`. + (2) The REAL `sdk-trace@3` is tested in the private `dev-packages/otel3-compat` (not in the package: `sdk-trace@3` + peers `api >=1.10 <1.11`, `sdk-trace-base@2` peers `api <1.10`, one install cannot hold both), skipped below + Node 22.15 (OTel 3 engines floor); `packages/opentelemetry/src/span-processor.real-sdk.test.ts` is the 2.x + runtime twin; a tsc type test pins `ReadableSpan` -> `ReadableSpanLike` and processor -> 3.x `SpanProcessor`. + (3) `AnyValue` attributes, normalized LATE: `@bugsee/performance` `attribute-value.ts` — consume keeps scalars and + small homogeneous scalar arrays (strings capped at 32 KiB) and turns anything else into a bounded JSON-safe TREE + (bytes base64, bigint exact-or-text); the span filter / default sanitizer sees the tree (nested key-based + redaction, `span-sanitizer.ts`); `flattenTransactionAttributes` (extension, after the filter) flattens what + remains to bounded JSON strings at the wire. Cuts never defeat redaction (open SQL literal and partial token handling); arrays stored as copies. Bounded in WORK per attribute AND per span (leaf, key, node and character budgets, a span-level + budget, typed arrays read by index; entry step `normalizeTransactionAttributes` bounds the SDK's own raw values too) and total (never throws; produce path drops one bad attribute, never the batch). Native + OTLP `kvlistValue`/`arrayValue` on produce NOT done: the OTLP tee reads the post-wire (already flattened) + store, and the Bugsee wire/viewer read scalar attribute values. Found+fixed: a `bigint` attribute reached the + transaction as a value `JSON.stringify` throws on. + (4) `packaging-guard/src/otel-no-deep-imports.test.ts`: no `@opentelemetry/*` deep import / `package.json` + read / `node_modules/@opentelemetry` path anywhere (none existed). Also: nextjs zero-config provider falls back to + `sdk-trace` (`loadOtelModules`). NOT verified: OTel 3 on Node < 22.15 (unsupported upstream; the suite skips), a + real Next.js app on OTel 3 end to end. - **T — DONE (`main`):** the interception-transformer seam in `@bugsee/capture`. Capture interceptors stay observe-only; a `RequestDecorator` (sync, truthful-capture, never on SDK-internal traffic) is the ONLY way piped data is altered — byte-identical when none registered. Shared `createRequestDecoratorRegistry` diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 7970a5a35..0da8fc508 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -99,7 +99,8 @@ network interceptor's transformer seam, the `TransactionStore`) — core and per `TracerProvider`. `onEnd(otelSpan)` → map → Bugsee. Open sub-decision (Faro does both): consumed spans become Bugsee **Transactions** (native model, for UI/correlation) and/or are preserved as an **OTLP blob** in the bundle (full fidelity — events/links/resource/scope our model lacks). Peer: - `@opentelemetry/sdk-trace-base`. **Node-first.** + `@opentelemetry/sdk-trace-base` (OTel JS 1.x/2.x) or `@opentelemetry/sdk-trace` (2.9+, the only one on 3.x) — see + "OpenTelemetry JS major compatibility". **Node-first.** - **Produce (OTLP-JSON):** `TransactionStore.drain()` → `resourceSpans` (OTLP-JSON) → `POST application/json` → the user's collector / OTLP endpoint. Hand-rolled mapping or a thin `@opentelemetry/otlp-transformer` dep — no full SDK. Dropped vs the SDK exporter: protobuf, gzip, @@ -138,7 +139,7 @@ Mapping core is portable. **Produce** (light) ships on both runtimes. **Consume* - **A. Portable mapping core** — `@bugsee/opentelemetry`: Span/Transaction ↔ OTel span + the OTLP-JSON encoder. Foundation; pure; test-first. - **B. Produce** — OTLP-JSON exporter from `TransactionStore`. Read-only, low-risk, first user-visible win. -- **C. Consume** — `BugseeSpanProcessor` (peer `sdk-trace-base`), **Node-first**. Resolve the +- **C. Consume** — `BugseeSpanProcessor` (peer `sdk-trace-base` on OTel 1.x/2.x, `sdk-trace` on 2.9+/3.x), **Node-first**. Resolve the native-map-vs-OTLP-blob sub-decision here (likely both, Faro-style). - **T. Interception-transformer seam** — in `@bugsee/capture`/`InterceptorBase` (general; sync; truthful capture). Prerequisite for D, independently useful. @@ -169,6 +170,179 @@ move earlier if the distributed-trace story is the priority. --- +## OpenTelemetry JS major compatibility (issue #94, OTel JS 3.0 GA 2026-10-20) + +**Peers, split by OTel major.** OTel JS 3.0 removed `@opentelemetry/sdk-trace-base`, `-web` and `-node` +(npm `deprecated: "Use @opentelemetry/sdk-trace package"`; `sdk-trace-base` stays at 2.12.0, there is no 3.x) +and replaced them with the single `@opentelemetry/sdk-trace`. Both `@bugsee/opentelemetry` and +`@bugsee/nextjs` therefore declare, all OPTIONAL (a produce-only user installs none): + +| peer | range | for | +| --- | --- | --- | +| `@opentelemetry/api` | `>=1.0.0` | every major | +| `@opentelemetry/sdk-trace-base` | `>=1.0.0 <3` | OTel 1.x / 2.x | +| `@opentelemetry/sdk-trace` | `>=2.9.0` | OTel 2.9+ (a hard dependency of `sdk-trace-base` 2.9+, exports the same `TracerProvider`) and 3.x (the only SDK package there) | + +Guard: `dev-packages/packaging-guard/src/otel-peers.test.ts`. + +**The API peer ranges do not overlap, so the two SDKs cannot share one test install.** +`sdk-trace-base@2.12` peers `@opentelemetry/api >=1.3.0 <1.10.0`; `sdk-trace@3.0.0` peers +`>=1.10.0 <1.11.0`. One workspace package cannot satisfy both, so the 2.x tests stay in +`packages/opentelemetry` (api 1.9.x) and the 3.x tests live in the private `dev-packages/otel3-compat` +(api 1.10.x). That is a TEST-install constraint only: the package imports no OTel code at runtime (structural +`ReadableSpanLike` / `SpanProcessor`). What binds a customer is OUR optional peer ranges (`api >=1.0.0`, +`sdk-trace-base >=1.0.0 <3`, `sdk-trace >=2.9.0`), which accept every released OTel SDK, plus their own SDK's +peer range on `@opentelemetry/api`. + +**Node floor.** `@opentelemetry/api@1.10` keeps `engines.node >=8`, but `core@3`, `resources@3` and +`sdk-trace@3` require `>=22.15.0`. `@bugsee/opentelemetry` itself still supports the Node +versions the SDK supports (it never loads OTel). CI runs Node 22 only (both jobs), which satisfies the floor, so +the OTel 3 suite runs there; on a developer machine with an older Node it skips with a stated reason, unless `BUGSEE_REQUIRE_OTEL3=1` (set on the CI Node 22 job, passed through turbo `test:unit` env), which +turns the skip into a failure so the 3.x coverage cannot rot silently. + +**Registering the processor on 3.x.** `new TracerProvider({ spanProcessors: [processor] })` from +`@opentelemetry/sdk-trace`. Same `spanProcessors` option as `BasicTracerProvider` on `sdk-trace-base` 2.x +(`sdk-trace` 2.9+ already exports a `TracerProvider` with that option; on 3.x it is the only provider class, +`BasicTracerProvider` is gone), and `addSpanProcessor` has been gone since 2.0. There is no +`register()` either: call `trace.setGlobalTracerProvider(provider)` yourself. Verified against the real +package in `dev-packages/otel3-compat`. + +**Next.js zero-config provider.** `@bugsee/nextjs` lazy-imports the SDK for its zero-config provider +(`otel-provider.ts` `loadOtelModules`): `sdk-trace-base` first (`BasicTracerProvider`, OTel 1.x/2.x, behaviour +unchanged), then `sdk-trace` (`TracerProvider`, 2.9+ and 3.x). Before this, an OTel 3 install reported `unavailable` +because `sdk-trace-base` does not exist there. A real `next build` of `packages/nextjs-e2e` with neither package +installed compiles without a module-not-found error, so the second optional import does not break webpack. + +**Browser builds and deep imports.** OTel 3 ships an `exports` map on every package, so +`@opentelemetry//build/...` deep imports and `@opentelemetry//package.json` reads no longer resolve, +and the `browser` field was replaced by `#platform` subpath imports. A bundler that pulls OTel 3 into a +browser build therefore needs `imports` support (webpack >= 5.54; current Vite, Rollup, esbuild and Rspack +have it). That constraint falls on the customer's own OTel usage: `@bugsee/opentelemetry` imports no OTel code +(structural types only), and a repo-wide guard (`dev-packages/packaging-guard/src/otel-no-deep-imports.test.ts`) +fails the unit gate on any `@opentelemetry/*` deep import, `package.json` read or `node_modules/@opentelemetry` +path in tracked source, config or sample files (audited 2026-10-21: none, including the browser, webworker, +edge and bundler-plugin packages). + +**Complex attributes (OTEP 4485, `@opentelemetry/api` 1.10 `AnyValue`).** Since 1.10 `Attributes` values are +`AnyValue`: string/number/boolean, byte array (`Uint8Array`), array of any value, map of any value, null. +Verified against `sdk-trace@3.0.0`: the SDK keeps nested maps, mixed arrays, `Uint8Array` and `null` on +`ReadableSpan.attributes`, and itself drops bigint, `Date`, functions, symbols and cyclic values. An older or +third-party SDK can still hand us anything, so the mapping is total. Implementation: +`packages/performance/src/attribute-value.ts` (in `@bugsee/performance` because the redaction and wire steps +that need it sit below `@bugsee/opentelemetry`; the OTel package re-exports it). + +*Normalize late, flatten at the wire.* Three steps, in this order: + +0. **Entry, for every span** (`normalizeTransactionAttributes`, first step of the performance extension's + `filterTransaction`). The SDK's own spans carry whatever `setAttribute`, `recordChildSpan({ attributes })` + and `recordExternal` were handed, so every transaction's attributes are bounded here (shared per-span budget, + cycles marked, a throwing getter or Proxy trap turns into `"[Unreadable]"` or a dropped attribute) before the + redaction walk or an integrator filter sees them. Every later step reads the normalized COPY (plain data + properties, each source getter read exactly once), never the caller's record. + Measured before this step, on the raw redaction walk: a `node:http` request object 0.3-0.5 s, a branching + DAG (3 branches, 14 levels) 4 s, a self-referencing object 17 s; after it, each takes under 3 ms. +1. **Consume** (`readableSpanToConsumed` -> `normalizeAttributes`). Scalars and small homogeneous scalar arrays + (<= 1024 elements, strings totalling <= 32 KiB) pass through; a scalar string is capped at 32 KiB (so the cost + of `span.end()` does not scale with whatever instrumentation recorded). A byte array becomes base64; a bigint + a number when exact, decimal text otherwise; `null`/`undefined`/function/symbol drop the attribute. + Everything else (nested map, mixed/nested array, long scalar array) becomes a bounded JSON-safe TREE, NOT text. +2. **Redaction** sees that tree. The default span sanitizer applies the same rules to nested keys as to flat ones + (a sensitive key redacts its whole value at any depth, content keys redact, statement keys keep their shape + via `redactSqlLiterals`, including a statement carried as a map or an array: every string leaf under a + statement key is SQL; secret-shape scanning covers the string VALUES inside maps and arrays-of-maps only, + NOT nested map keys, and, exactly as on main, not a top-level string attribute or a flat string array; + depth-limited), so + `user: { password }` and `http.request.headers: { authorization }` are redacted by default. An integrator + `setSpanFilter` receives the tree too. +3. **Wire** (`flattenTransactionAttributes`, run by the performance extension after the filter, in both sinks): + what remains complex becomes one bounded JSON string, because the Bugsee attribute model and viewer read + scalar attribute values. + +An earlier revision stringified at step 1, which defeated step 2: the default sanitizer is key-based, so a nested +`{ password }` inside a JSON string was invisible to it while the flat key was redacted. That is the reason for +the ordering. + +Rejected: flattening to dotted keys (key explosion, no stable form for arrays) and dropping (silent loss of +exactly what OTEP 4485 carries). Native OTLP `kvlistValue`/`arrayValue` on produce was reconsidered and NOT done: +the OTLP tee exports from the store, which holds the post-wire (already flattened) transactions, and the +Bugsee wire and viewer read scalar attribute values, so a native kvlist could only be emitted by carrying trees +through the store and upload wire. `toAnyValue` (the exported mapping) still emits `bytesValue` for a byte array that fits (up to 6144 bytes, exactly +8192 base64 characters) +and a bounded JSON `stringValue` for maps/arrays. + +| input | after consume | at the wire / OTLP produce | +| --- | --- | --- | +| string / boolean / number | unchanged (a string over 32 KiB is cut, marked, and its unfinished final token dropped) | `stringValue` / `boolValue` / `intValue` or `doubleValue` | +| homogeneous scalar array (null entries allowed) | an equal COPY (never the caller's array: a later `push` cannot reach the store) | the same copy; OTLP: JSON `stringValue` (existing behaviour) | +| nested map, mixed/nested array | bounded tree (redactable) | one bounded JSON string | +| byte array | base64 string (cut at 8192 characters, marked) | string; `toAnyValue`: `bytesValue` (valid base64) up to 6144 bytes, a cut array is a `stringValue` carrying the marker | +| bigint | number if exact, else decimal string | `intValue` for a safe-range value (a number by then); a beyond-safe-range bigint is already decimal text and exports as `stringValue` | +| null, undefined, function, symbol | dropped | dropped | + +*Cuts and redaction.* Length caps run BEFORE redaction, so a cut must never leave something redaction can no +longer recognise: a SQL statement cut inside a string literal has its open trailing literal replaced +(`redactSqlLiterals` handles an unterminated `'`/`"`). Where secret-shape scanning applies (string leaves inside +maps and arrays-of-maps), a leaf cut inside a token (a JWT after its payload, a `ghp_` token at 15 of 36 +characters) drops the unfinished token, because secret shapes only match when complete. A leaf with NO token +boundary at all (one unbroken run, such as `id_token=`, a long hash, or a base64url blob) keeps its cut +prefix but backs off before a secret the cut LANDS INSIDE (`unfinishedSecretStart` in `@bugsee/protocol`). It +walks the shape starts left to right keeping the current secret's start, and moves on to a later start only once +the text since it is already a complete secret, so a start inside another secret (a JWT payload that itself +contains `eyJ` because it holds a nested `{"` claim, an `ASIA` inside an AWS key) does not move the answer off +the outer secret. A secret that is already complete in the prefix is left for redaction to match whole: a JWT cut +inside its signature keeps all three segments and `redactShapes` replaces them, while one cut inside its header +or payload backs off to the start of the header (a bare JWT collapses to the marker, `id_token=` becomes +`id_token=` plus the marker). A Stripe-style key counts as finished as soon as one character follows its +prefix, because its pattern matches a partial key (a cut right after `sk_live_` or `whsec_` itself is still +reported as unfinished). The shape starts and the redaction patterns are built from one table (`SHAPES` in `shapes.ts`), so a new +shape cannot be added to one and missed by the other. The walk examines the first start plus at most 16 further +starts per call and past that backs off to the current candidate (more dropped, never less). Known limitation, pinned by a test: a shape glued to a partial token of another +shape (`sk_live_` directly followed by `gho_<30>`) lets the outer pattern complete by swallowing the inner +token's alphanumeric prefix, so part of the inner token is not seen as unfinished; the same glue already survives +`redactShapes` on main without any cut. `:` is not a token character, so a long map-leaf +URL (`https://host/...` past the cap) is cut back to `https:` plus the marker by the ordinary boundary rule +(unrelated to the back-off): accepted data loss, a scheme-and-host-keeping rule was not worth another heuristic. A TOP-LEVEL string attribute is only cut (it is +never shape-scanned, so dropping its unfinished token would protect nothing and would lose the host of a long +URL). Byte arrays (base64) are not text and are only cut. Known limitation, pre-existing and not changed here: +SQL literal redaction pairs quotes left to right, so comments, backslash escapes and dollar quotes can shift the +pairing and leave a literal in the clear (bugsee/bugsee-javascript#109). + +*Bounds and totality.* Never throws, and bounded in WORK per ATTRIBUTE, and per SPAN for TREES: every string leaf and key is +cut at 8128 characters before it is copied (a key that long is not kept, and its value is redacted, so a cut can +never remove the `password` a key-based rule looks for), a tree stops at 1024 visited nodes or 32768 copied +characters, and one span's attributes together stop at 4096 nodes or 65536 characters (the rest is +`"[Truncated]"`; 128 attributes of 1000-node maps cost about 2 ms, not 1.2 s). Scalar strings and scalar-array +elements are NOT charged to the per-span budget: each is capped on its own (a string at 32 KiB, an array at 1024 +elements and 32 KiB of string), so a span is bounded by its attribute COUNT times that (the SDK default limit +is 128 attributes, about 4 MiB per span; a caller that lifts the limit and sets 10,000 maximal attributes would +copy about 327 MB), depth 8 (`"[MaxDepth]"`), the JSON text at 8192 characters (`...[truncated]`), cycles become +`"[Circular]"` (a shared acyclic reference is not a cycle), non-finite numbers the OTLP spellings, byte arrays are +encoded only up to what could fit, a non-byte typed array (a Float32Array embedding) is read by index within the +node budget, and `toJSON` or other user code is never called. A throwing getter, an element or a Proxy trap +yields `"[Unreadable]"` for that value, an unlistable record (a Proxy with a throwing `ownKeys`) yields no +attributes, and on the produce path (`toKeyValues`, `toOtlpExportRequest`) one bad attribute is dropped without +costing its siblings, the span or the export batch. Truncated text is NOT valid JSON after the `...[truncated]` marker (a cut at a leaf keeps the JSON valid; +a cut of the whole text does not). Non-plain values are handled deliberately: a URL becomes its href with +credentials removed, an Error its `name` and `message` (never the stack), a Date its ISO string (an invalid Date +drops the attribute), `ArrayBuffer`, `DataView` and a cross-realm `Uint8Array` are bytes; a `Map`, `Set` and any +other class instance is read by own enumerable properties (so a Map or Set is `{}`). A homogeneous scalar array +with null entries (`['a', null]`, which OTel 2/3 keep) passes through unchanged. Known limit: `Object.keys` on a plain object with millions of +keys still allocates its key list before the node budget stops the copy. Residual cost: the redaction step +still scans string leaves for secret shapes, and an adversarial leaf dense in `eyJ` (JWT-prefix) text costs about +10 ms per 8 KB; the per-span character budget caps that at roughly 100 ms for a span (measured by the review). `isSensitiveKey` now +normalises its denylist once (0.3 us per key instead of 4 us). `sanitizeSpan` is exported but assumes bounded +input (it is only safe on values that went through `normalizeTransactionAttributes`, as the extension does). + +**Using the processor.** Register it on ONE provider. Registering it on two providers, or alongside +`@bugsee/nextjs`'s zero-config provider, produces two transactions per trace (one per registration). Cost per +ended span is one normalization of its attributes plus one assembler insert; a span whose attributes are all +scalars copies nothing beyond the attribute record. After `shutdown()` the processor ignores further `onEnd` +calls. The zero-config provider in `@bugsee/nextjs` registers no context manager (pre-existing, identical on +`BasicTracerProvider` 2.12, `sdk-trace` 2.12 and 3.0), so a nested `startActiveSpan` there produces a separate +root transaction, not a child span. + +--- + ## Cross-SDK coordination addendum (2026-06-21, from the Android OTel workstream) The Android SDK is adding OTLP interop and the team decided to make **OTLP the native format of the internal diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index 5caa9b48c..90a12114b 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -16,7 +16,7 @@ pnpm add @bugsee/nextjs yarn add @bugsee/nextjs ``` -Optional peer dependencies: `react` >= 18, and `@opentelemetry/api` and `@opentelemetry/sdk-trace-base` (>= 1.0.0) for the automatic OpenTelemetry bridge. Server code requires Node.js 18 or newer. +Optional peer dependencies: `react` >= 18, and `@opentelemetry/api` plus your OpenTelemetry SDK for the automatic OpenTelemetry bridge: `@opentelemetry/sdk-trace-base` (OTel JS 1.x/2.x) or `@opentelemetry/sdk-trace` (OTel JS 2.9+, required on 3.x). Server code requires Node.js 18 or newer. ## Usage diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 0754868d3..68a215cf0 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -52,7 +52,8 @@ }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0", - "@opentelemetry/sdk-trace-base": ">=1.0.0", + "@opentelemetry/sdk-trace-base": ">=1.0.0 <3", + "@opentelemetry/sdk-trace": ">=2.9.0", "react": ">=18" }, "peerDependenciesMeta": { @@ -62,6 +63,9 @@ "@opentelemetry/sdk-trace-base": { "optional": true }, + "@opentelemetry/sdk-trace": { + "optional": true + }, "react": { "optional": true } @@ -69,6 +73,7 @@ "devDependencies": { "@bugsee/node": "workspace:*", "@opentelemetry/api": "^1.9.0", + "@opentelemetry/sdk-trace": "^2.12.0", "@opentelemetry/sdk-trace-base": "^2.12.0", "@types/react": "^18.3.0", "react": "^18.3.1" diff --git a/packages/nextjs/src/otel-provider.test.ts b/packages/nextjs/src/otel-provider.test.ts index 865def3ec..d3e41b7e3 100644 --- a/packages/nextjs/src/otel-provider.test.ts +++ b/packages/nextjs/src/otel-provider.test.ts @@ -1,6 +1,11 @@ import { trace } from '@opentelemetry/api'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { attachBugseeOtelProvider, type OtelTracerModules } from './otel-provider'; +import { + attachBugseeOtelProvider, + loadOtelModules, + type OtelImporters, + type OtelTracerModules, +} from './otel-provider'; // A structural stand-in for the Bugsee SpanProcessor (attach only forwards it into createProvider). const processor = { @@ -211,3 +216,141 @@ describe('attachBugseeOtelProvider', () => { }); }); }); + +// OpenTelemetry JS 3.0 removed `@opentelemetry/sdk-trace-base` (and renamed `BasicTracerProvider` to +// `TracerProvider` in its replacement `@opentelemetry/sdk-trace`). Without a fallback the zero-config +// provider silently stays 'unavailable' for every OTel 3 install (issue #94). +describe('loadOtelModules (which OTel SDK package provides the provider)', () => { + const absent = () => Promise.reject(new Error('Cannot find module')); + const ctor = (tag: string) => + class { + readonly tag = tag; + constructor(readonly options: { spanProcessors: unknown[] }) {} + }; + const api = () => Promise.resolve({ trace: { setGlobalTracerProvider: vi.fn(() => true) } }); + + const importers = (over: Partial): OtelImporters => ({ + api, + sdkTraceBase: absent, + sdkTrace: absent, + ...over, + }); + + it('builds a BasicTracerProvider from sdk-trace-base (OTel 1.x/2.x)', async () => { + const mods = await loadOtelModules( + importers({ sdkTraceBase: () => Promise.resolve({ BasicTracerProvider: ctor('base') }) }), + ); + expect(mods?.createProvider([processor])).toMatchObject({ + tag: 'base', + options: { spanProcessors: [processor] }, + }); + }); + + it('falls back to a TracerProvider from sdk-trace when sdk-trace-base is not installed (OTel 3.x)', async () => { + const mods = await loadOtelModules( + importers({ sdkTrace: () => Promise.resolve({ TracerProvider: ctor('v3') }) }), + ); + expect(mods?.createProvider([processor])).toMatchObject({ + tag: 'v3', + options: { spanProcessors: [processor] }, + }); + }); + + it('prefers sdk-trace-base when both are installed (existing 1.x/2.x behaviour is unchanged)', async () => { + const mods = await loadOtelModules( + importers({ + sdkTraceBase: () => Promise.resolve({ BasicTracerProvider: ctor('base') }), + sdkTrace: () => Promise.resolve({ TracerProvider: ctor('v3') }), + }), + ); + expect(mods?.createProvider([processor])).toMatchObject({ tag: 'base' }); + }); + + it('falls back when sdk-trace-base resolves but does not export a provider class', async () => { + const mods = await loadOtelModules( + importers({ + sdkTraceBase: () => Promise.resolve({}), + sdkTrace: () => Promise.resolve({ TracerProvider: ctor('v3') }), + }), + ); + expect(mods?.createProvider([processor])).toMatchObject({ tag: 'v3' }); + }); + + it('delegates global registration to @opentelemetry/api', async () => { + const setGlobal = vi.fn(() => true); + const mods = await loadOtelModules( + importers({ + api: () => Promise.resolve({ trace: { setGlobalTracerProvider: setGlobal } }), + sdkTrace: () => Promise.resolve({ TracerProvider: ctor('v3') }), + }), + ); + const provider = { p: 1 }; + expect(mods?.setGlobalTracerProvider(provider)).toBe(true); + expect(setGlobal).toHaveBeenCalledWith(provider); + }); + + it('is undefined (unavailable) when no SDK package is installed', async () => { + expect(await loadOtelModules(importers({}))).toBeUndefined(); + }); + + it('is undefined when @opentelemetry/api is not installed', async () => { + expect( + await loadOtelModules( + importers({ api: absent, sdkTrace: () => Promise.resolve({ TracerProvider: ctor('v3') }) }), + ), + ).toBeUndefined(); + }); + + it('is undefined when the SDK module exports no provider class at all', async () => { + expect( + await loadOtelModules( + importers({ sdkTraceBase: () => Promise.resolve({}), sdkTrace: () => Promise.resolve({}) }), + ), + ).toBeUndefined(); + }); +}); + +describe('attachBugseeOtelProvider default loading on an OTel 3 install (sdk-trace-base removed)', () => { + afterEach(() => { + vi.doUnmock('@opentelemetry/sdk-trace-base'); + vi.doUnmock('@opentelemetry/sdk-trace'); + vi.resetModules(); + trace.disable(); + }); + + it('registers a TracerProvider from sdk-trace through the real default loader', async () => { + vi.resetModules(); + vi.doMock('@opentelemetry/sdk-trace-base', () => { + throw new Error('Cannot find module @opentelemetry/sdk-trace-base'); + }); + const built: unknown[][] = []; + vi.doMock('@opentelemetry/sdk-trace', () => ({ + TracerProvider: class { + // Only the registration plumbing is under test here; the API calls are made on a global provider. + constructor(options: { spanProcessors: unknown[] }) { + built.push(options.spanProcessors); + } + getTracer() { + return trace.getTracer('noop'); + } + }, + })); + const fresh = await import('./otel-provider'); + + expect(await fresh.attachBugseeOtelProvider(processor)).toBe('registered'); + expect(built).toEqual([[processor]]); + }); + + it('reports unavailable when neither SDK package can be imported', async () => { + vi.resetModules(); + vi.doMock('@opentelemetry/sdk-trace-base', () => { + throw new Error('absent'); + }); + vi.doMock('@opentelemetry/sdk-trace', () => { + throw new Error('absent'); + }); + const fresh = await import('./otel-provider'); + + expect(await fresh.attachBugseeOtelProvider(processor)).toBe('unavailable'); + }); +}); diff --git a/packages/nextjs/src/otel-provider.ts b/packages/nextjs/src/otel-provider.ts index d6563153e..058f8f698 100644 --- a/packages/nextjs/src/otel-provider.ts +++ b/packages/nextjs/src/otel-provider.ts @@ -8,7 +8,8 @@ // Competitor-grounded mechanism: the OTel global tracer-provider slot is single-owner / // FIRST-WINS (`setGlobalTracerProvider` returns `false` if one exists) and `getTracerProvider()` hands // back a Proxy with no `addSpanProcessor` — so we register ONLY when the slot is free and NEVER clobber a -// pre-existing `@vercel/otel`. Mirrors @vercel/otel's own choice of `BasicTracerProvider`. The OTel SDK is +// pre-existing `@vercel/otel`. Mirrors @vercel/otel's own choice of `BasicTracerProvider` (`TracerProvider` on +// OTel JS 3, which removed sdk-trace-base). The OTel SDK is // an OPTIONAL peer (install-lean, matching @bugsee/opentelemetry) — lazy-imported and skipped if absent. // // SERVER-only (node OTel SDK) → reached only from `./server`; never the portable `.` graph. @@ -19,7 +20,7 @@ import { describeValue, reportGuarded, resolveFailClosedBoolean } from '@bugsee/ export interface OtelTracerModules { /** `@opentelemetry/api` `trace.setGlobalTracerProvider` — returns `false` if a provider already exists. */ setGlobalTracerProvider(provider: unknown): boolean; - /** Build a concrete provider (`@opentelemetry/sdk-trace-base` `BasicTracerProvider`) with our processors. */ + /** Build a concrete provider (`sdk-trace-base`'s `BasicTracerProvider` on OTel 1.x/2.x, `sdk-trace`'s `TracerProvider` on 3.x) with our processors. */ createProvider(spanProcessors: unknown[]): unknown; } @@ -40,25 +41,61 @@ export interface AttachOtelProviderOptions { load?: () => Promise; } -/** Dynamic-import the OPTIONAL OTel peers; returns `undefined` when they are not installed. */ -async function defaultLoad(): Promise { +/** A provider class: `BasicTracerProvider` (sdk-trace-base 1.x/2.x) or `TracerProvider` (sdk-trace 2.9+, the only SDK package on 3.x). */ +type ProviderCtor = new (options: { spanProcessors: unknown[] }) => unknown; + +/** The module loaders {@link loadOtelModules} uses — injectable so every install shape is testable. */ +export interface OtelImporters { + api(): Promise<{ trace: { setGlobalTracerProvider(provider: never): boolean } }>; + /** OTel JS 1.x/2.x. */ + sdkTraceBase(): Promise<{ BasicTracerProvider?: ProviderCtor }>; + /** OTel JS 2.9+ and 3.x (3.x removed `sdk-trace-base` and renamed `BasicTracerProvider` to `TracerProvider`). */ + sdkTrace(): Promise<{ TracerProvider?: ProviderCtor }>; +} + +/** + * Resolve the OTel modules from whichever optional SDK package is installed: `sdk-trace-base` first (OTel + * 1.x/2.x, unchanged behaviour), then `sdk-trace` (2.9+ and 3.x). `undefined` when `@opentelemetry/api` or every + * SDK package is absent. + */ +export async function loadOtelModules( + imports: OtelImporters, +): Promise { try { - const [api, sdk] = await Promise.all([ - import('@opentelemetry/api'), - import('@opentelemetry/sdk-trace-base'), - ]); + const api = await imports.api(); + let Provider: ProviderCtor | undefined; + try { + Provider = (await imports.sdkTraceBase()).BasicTracerProvider; + } catch { + // not installed (OTel 3 removed it) — try its replacement + } + if (Provider === undefined) { + try { + Provider = (await imports.sdkTrace()).TracerProvider; + } catch { + // not installed either + } + } + if (Provider === undefined) return undefined; + const ProviderClass = Provider; return { setGlobalTracerProvider: (provider) => api.trace.setGlobalTracerProvider(provider as never), - createProvider: (spanProcessors) => - new sdk.BasicTracerProvider({ spanProcessors: spanProcessors as never }), + createProvider: (spanProcessors) => new ProviderClass({ spanProcessors }), }; } catch { - /* v8 ignore next -- optional-peer-absent path: unreachable when the OTel peers are installed (as they - are, as devDeps, in the test env); the 'unavailable' outcome is covered via the injected `load` seam. */ return undefined; // peers absent → the coexistence path (onSpanProcessor) still stands } } +/** Dynamic-import the OPTIONAL OTel peers; returns `undefined` when they are not installed. */ +function defaultLoad(): Promise { + return loadOtelModules({ + api: () => import('@opentelemetry/api'), + sdkTraceBase: () => import('@opentelemetry/sdk-trace-base') as never, + sdkTrace: () => import('@opentelemetry/sdk-trace') as never, + }); +} + /** * Zero-config self-register an OTel provider carrying `processor`, but ONLY when the global slot is free. * Fully defensive — never throws; returns the {@link OtelProviderOutcome}. Fired (fire-and-forget) by diff --git a/packages/nextjs/src/server.ts b/packages/nextjs/src/server.ts index 73d7f1f2d..a694028df 100644 --- a/packages/nextjs/src/server.ts +++ b/packages/nextjs/src/server.ts @@ -47,7 +47,7 @@ export interface NextjsServerOptions extends BugseeNodeLaunchOptions { * Zero-config OTel (N1b-2): when NO OpenTelemetry provider is registered, Bugsee stands up its own * (carrying the consume-bridge processor) so Next.js emits + Bugsee consumes its spans with no user * OTel setup. First-wins — it never clobbers a pre-existing `@vercel/otel`. Requires the optional peers - * `@opentelemetry/api` + `@opentelemetry/sdk-trace-base` (skipped if absent). Set `false` to opt out + * `@opentelemetry/api` + an OTel SDK (`@opentelemetry/sdk-trace-base` on 1.x/2.x, `@opentelemetry/sdk-trace` on 3.x; skipped if absent). Set `false` to opt out * (e.g. you manage OTel yourself). Default `true`. It installs a process-wide provider that consumes every span, * so an INVALID value (`'false'`, `0`, `null`, `1`) is treated as OFF and reported through `onError`. */ diff --git a/packages/opentelemetry/README.md b/packages/opentelemetry/README.md index 17368f48c..381317b72 100644 --- a/packages/opentelemetry/README.md +++ b/packages/opentelemetry/README.md @@ -10,7 +10,12 @@ You do not need to install this package. It is a dependency of `@bugsee/bugsee`, npm install @bugsee/bugsee ``` -Consuming spans also needs your own OpenTelemetry SDK (`@opentelemetry/api` and `@opentelemetry/sdk-trace-base`, optional peers of this package). +Consuming spans also needs your own OpenTelemetry SDK, all optional peers of this package: + +| Your OpenTelemetry JS | Install | +| --- | --- | +| 1.x / 2.x | `@opentelemetry/api` and `@opentelemetry/sdk-trace-base` | +| 3.x (Node.js 22.15 or newer) | `@opentelemetry/api` and `@opentelemetry/sdk-trace` (3.0 removed `sdk-trace-base`; `sdk-trace` also exists on 2.9+) | ## Usage @@ -36,7 +41,9 @@ await launch('YOUR_APP_TOKEN', { onOtelSpanProcessor: (processor: BugseeSpanProcessor) => { // Register `processor` on your OpenTelemetry TracerProvider. // How depends on your OpenTelemetry SDK version (for example the - // `spanProcessors` constructor option on SDK 2.x). + // `spanProcessors` constructor option of `BasicTracerProvider` from + // `@opentelemetry/sdk-trace-base` on SDK 2.x, or of `TracerProvider` from + // `@opentelemetry/sdk-trace` on 3.x). }, }); ``` diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index a4ce7d8ed..717f4e773 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -34,11 +34,13 @@ }, "devDependencies": { "@opentelemetry/api": "^1.9.0", + "@opentelemetry/sdk-trace": "^2.12.0", "@opentelemetry/sdk-trace-base": "^2.12.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0", - "@opentelemetry/sdk-trace-base": ">=1.0.0" + "@opentelemetry/sdk-trace-base": ">=1.0.0 <3", + "@opentelemetry/sdk-trace": ">=2.9.0" }, "peerDependenciesMeta": { "@opentelemetry/api": { @@ -46,6 +48,9 @@ }, "@opentelemetry/sdk-trace-base": { "optional": true + }, + "@opentelemetry/sdk-trace": { + "optional": true } }, "publishConfig": { diff --git a/packages/opentelemetry/src/attribute-mapping.fuzz.test.ts b/packages/opentelemetry/src/attribute-mapping.fuzz.test.ts new file mode 100644 index 000000000..328c941c6 --- /dev/null +++ b/packages/opentelemetry/src/attribute-mapping.fuzz.test.ts @@ -0,0 +1,75 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { readableSpanToConsumed } from './span-processor'; +import { toAnyValue, toKeyValues } from './to-otlp'; + +/** + * The produce and consume mappings accept ANY attribute value. The values come from application + * instrumentation and from whatever OTel SDK the host runs, and both mappings run where a throw is expensive: + * `onEnd` inside the customer's `span.end()`, and the exporter, where one throw rejects the whole batch. + */ + +const exotic = fc.anything({ + withBigInt: true, + withDate: true, + withMap: true, + withSet: true, + withNullPrototype: true, + withSparseArray: true, + withTypedArray: true, + withObjectString: true, + maxDepth: 6, +}); + +const withCycle = exotic.map((value) => { + const holder: Record = { value }; + holder.self = holder; + holder.list = [holder, value]; + return holder; +}); + +const leaf = fc.oneof( + fc.constant(undefined), + fc.constant(null), + fc.constant(() => 1), + fc.constant(Symbol('s')), + fc.constantFrom(Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY), + fc.uint8Array({ maxLength: 64 }), + fc.bigInt(), +); + +const anyValue = fc.oneof(exotic, withCycle, leaf); + +describe('the OTLP and consume mappings accept any attribute value (fuzz)', () => { + it('toAnyValue never throws and its result survives JSON serialization', () => { + fc.assert( + fc.property(anyValue, (value) => { + const out = toAnyValue(value); + if (out === undefined) return; + expect(JSON.parse(JSON.stringify(out))).toEqual(out); + }), + { numRuns: 400 }, + ); + }); + + it('toKeyValues and readableSpanToConsumed keep working with an exotic value among the attributes', () => { + fc.assert( + fc.property(anyValue, (value) => { + const attributes = { before: 'a', hostile: value, after: 1 }; + expect(() => toKeyValues(attributes)).not.toThrow(); + const consumed = readableSpanToConsumed({ + spanContext: () => ({ traceId: 't', spanId: 's' }), + name: 'n', + startTime: [0, 0], + endTime: [1, 0], + status: { code: 0 }, + attributes, + }); + expect(consumed.attributes?.before).toBe('a'); + expect(consumed.attributes?.after).toBe(1); + expect(() => JSON.stringify(consumed.attributes)).not.toThrow(); + }), + { numRuns: 300 }, + ); + }); +}); diff --git a/packages/opentelemetry/src/index.ts b/packages/opentelemetry/src/index.ts index 597d4549c..a8caf08fb 100644 --- a/packages/opentelemetry/src/index.ts +++ b/packages/opentelemetry/src/index.ts @@ -5,6 +5,19 @@ // compatible); and the SpanProcessor consume bridge — `createBugseeSpanProcessor` below. // PLANNED: the interception-transformer propagation. +// Attribute normalization lives in @bugsee/performance (the redaction and wire steps need it below this +// package); re-exported so existing imports keep working. +export { + flattenAttributes, + MAX_ATTRIBUTE_ARRAY_LENGTH, + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + MAX_ATTRIBUTE_NODES, + MAX_ATTRIBUTE_STRING_LENGTH, + normalizeAttributes, + normalizeAttributeValue, + stringifyAnyValue, +} from '@bugsee/performance'; export { type ConsumedSpan, consumedRootToTransaction, diff --git a/packages/opentelemetry/src/otlp-exporter.test.ts b/packages/opentelemetry/src/otlp-exporter.test.ts index 931f75256..bdcea0363 100644 --- a/packages/opentelemetry/src/otlp-exporter.test.ts +++ b/packages/opentelemetry/src/otlp-exporter.test.ts @@ -143,3 +143,44 @@ describe('createOtlpTraceExporter', () => { expect(called).toBe(false); }); }); + +describe('createOtlpTraceExporter survives hostile attributes (one attribute never rejects the batch)', () => { + it('exports every transaction, including one carrying exotic attribute values', async () => { + const bodies: string[] = []; + const transport: HttpTransport = async (_url, opts = {}) => { + bodies.push(String(opts.body)); + return ok; + }; + const send = createOtlpTraceExporter({ transport, url: 'https://collector.test/v1/traces' }); + const huge = 'x'.repeat(8 * 1024 * 1024); + const cyc: Record = { a: 1 }; + cyc.self = cyc; + const hostile = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + + await send([ + txn({ attributes: { cyc, big: { a: huge, b: [huge, huge] }, bytes: new Uint8Array(1e6) } }), + txn({ spanId: '1111111111111111', attributes: hostile }), + txn({ spanId: '2222222222222222', attributes: { ok: 'yes' } }), + ]); + + expect(bodies).toHaveLength(1); + const spans = ( + JSON.parse(bodies[0] as string) as { + resourceSpans: { scopeSpans: { spans: { spanId: string }[] }[] }[]; + } + ).resourceSpans[0]?.scopeSpans[0]?.spans; + expect(spans?.map((s) => s.spanId)).toEqual([ + 'fedcba9876543210', + '1111111111111111', + '2222222222222222', + ]); + expect(bodies[0]?.length).toBeLessThan(100_000); + }); +}); diff --git a/packages/opentelemetry/src/otlp-wire.ts b/packages/opentelemetry/src/otlp-wire.ts index f74f06eb0..c5408085b 100644 --- a/packages/opentelemetry/src/otlp-wire.ts +++ b/packages/opentelemetry/src/otlp-wire.ts @@ -28,9 +28,12 @@ export const OtlpStatusCode = { */ export type OtlpSpecialDouble = 'NaN' | 'Infinity' | '-Infinity'; -/** OTLP `AnyValue` — a one-of over the scalar kinds we produce (uint64 `intValue` is a decimal string). */ +/** OTLP `AnyValue` — a one-of over the kinds we produce (uint64 `intValue` is a decimal string; `bytesValue` + * is base64 per the proto3 JSON mapping). Arrays and maps are emitted as a JSON `stringValue`, not as + * `arrayValue`/`kvlistValue` (see attribute-value.ts for why). */ export type OtlpAnyValue = | { stringValue: string } + | { bytesValue: string } | { boolValue: boolean } | { intValue: string } | { doubleValue: number | OtlpSpecialDouble }; diff --git a/packages/opentelemetry/src/span-processor.real-sdk.test.ts b/packages/opentelemetry/src/span-processor.real-sdk.test.ts new file mode 100644 index 000000000..7b5ba722e --- /dev/null +++ b/packages/opentelemetry/src/span-processor.real-sdk.test.ts @@ -0,0 +1,98 @@ +import type { TransactionWire } from '@bugsee/performance'; +import { ROOT_CONTEXT, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; +import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'; +import { describe, expect, it } from 'vitest'; +import { createBugseeSpanProcessor, readableSpanToConsumed } from './span-processor'; + +// The REAL @opentelemetry/sdk-trace-base 2.x (the OTel 1.x/2.x peer), not a hand-built ReadableSpan. The +// OTel 3.x twin of this file is dev-packages/otel3-compat/src/provider.test.ts (sdk-trace@3 cannot share +// this install: it peers @opentelemetry/api >=1.10, sdk-trace-base@2 peers <1.10). + +function boot() { + const transactions: TransactionWire[] = []; + const errors: unknown[] = []; + const processor = createBugseeSpanProcessor({ + onTransaction: (t) => transactions.push(t), + onError: (e) => errors.push(e), + }); + const provider = new BasicTracerProvider({ spanProcessors: [processor] }); + return { transactions, errors, provider, tracer: provider.getTracer('compat', '1.0.0') }; +} + +describe('a real @opentelemetry/sdk-trace-base@2 provider', () => { + it('rebuilds the span tree from nested spans through spanProcessors', async () => { + const { provider, tracer, transactions, errors } = boot(); + const root = tracer.startSpan('GET /orders', { kind: SpanKind.SERVER }); + const rootCtx = trace.setSpan(ROOT_CONTEXT, root); + const db = tracer.startSpan('db.query', { kind: SpanKind.CLIENT }, rootCtx); + const driver = tracer.startSpan('driver.send', {}, trace.setSpan(rootCtx, db)); + driver.end(); + db.end(); + root.end(); + await provider.shutdown(); + + expect(errors).toEqual([]); + expect(transactions).toHaveLength(1); + const txn = transactions[0] as TransactionWire; + expect(txn.spanId).toBe(root.spanContext().spanId); + const dbWire = txn.spans.find((s) => s.operation === 'db.query'); + const driverWire = txn.spans.find((s) => s.operation === 'driver.send'); + expect(dbWire?.parentSpanId).toBe(root.spanContext().spanId); + expect(driverWire?.parentSpanId).toBe(db.spanContext().spanId); + expect(txn.attributes?.['otel.span.kind']).toBe(SpanKind.SERVER); + }); + + it('reads the 2.x parentSpanContext (the 1.x parentSpanId field is gone) and ms times', () => { + const seen: Parameters[0][] = []; + const provider = new BasicTracerProvider({ + spanProcessors: [ + { + onStart() {}, + onEnd: (span) => { + seen.push(span); + }, + forceFlush: async () => {}, + shutdown: async () => {}, + }, + ], + }); + const tracer = provider.getTracer('t'); + const root = tracer.startSpan('r'); + tracer.startSpan('c', {}, trace.setSpan(ROOT_CONTEXT, root)).end(); + + expect('parentSpanId' in (seen[0] as object)).toBe(false); + const consumed = readableSpanToConsumed( + seen[0] as Parameters[0], + ); + expect(consumed.parentSpanId).toBe(root.spanContext().spanId); + const [sec, nanos] = (seen[0] as { startTime: [number, number] }).startTime; + expect(consumed.startTimeMs).toBe(sec * 1000 + nanos / 1e6); + expect(consumed.startTimeMs).toBeGreaterThan(1.7e12); + }); + + it('maps status and carries primitive attributes', async () => { + const { provider, tracer, transactions } = boot(); + const bad = tracer.startSpan('bad', { attributes: { n: 3, tags: ['a', 'b'] } }); + bad.setStatus({ code: SpanStatusCode.ERROR, message: 'TIMEOUT' }); + bad.end(); + await provider.shutdown(); + + expect(transactions[0]?.status).toBe('TIMEOUT'); + expect(transactions[0]?.attributes).toMatchObject({ n: 3, tags: ['a', 'b'] }); + }); + + it('treats a remote parent as a local root', async () => { + const { provider, tracer, transactions } = boot(); + const remote = { + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331', + traceFlags: 1, + isRemote: true, + }; + tracer.startSpan('downstream', {}, trace.setSpanContext(ROOT_CONTEXT, remote)).end(); + await provider.shutdown(); + + expect(transactions).toHaveLength(1); + expect(transactions[0]?.traceId).toBe(remote.traceId); + }); +}); diff --git a/packages/opentelemetry/src/span-processor.test.ts b/packages/opentelemetry/src/span-processor.test.ts index bd3e317c1..385c7100f 100644 --- a/packages/opentelemetry/src/span-processor.test.ts +++ b/packages/opentelemetry/src/span-processor.test.ts @@ -1,4 +1,4 @@ -import type { TransactionWire } from '@bugsee/performance'; +import { sanitizeSpan, type TransactionWire } from '@bugsee/performance'; import { describe, expect, it, vi } from 'vitest'; import { createBugseeSpanProcessor, @@ -58,6 +58,86 @@ describe('readableSpanToConsumed', () => { expect(consumed.attributes).toEqual({ s: 'x', n: 3, ok: true, tags: ['a', 'b'] }); }); + describe('complex attribute values (OTel API 1.10 AnyValue)', () => { + it('keeps a nested map and a mixed array as bounded copies, bytes as base64, and scalars as they are', () => { + const consumed = readableSpanToConsumed( + readable({ + attributes: { + s: 'x', + n: 3, + tags: ['a', 'b'], + map: { a: { b: [1, 'x'] } }, + mixed: [1, 'a', true], + bytes: new Uint8Array([102, 111, 111]), + }, + }), + ); + expect(consumed.attributes).toEqual({ + s: 'x', + n: 3, + tags: ['a', 'b'], + map: { a: { b: [1, 'x'] } }, + mixed: [1, 'a', true], + bytes: 'Zm9v', + }); + }); + + it('drops the OTel empty value (null) and unrepresentable values', () => { + const consumed = readableSpanToConsumed( + readable({ attributes: { keep: 1, nul: null, und: undefined, fn: () => 1 } }), + ); + expect(consumed.attributes).toEqual({ keep: 1 }); + }); + + it('never throws on exotic values: a cycle, a bigint inside an object, a hostile getter', () => { + const cyc: Record = { a: 1 }; + cyc.self = cyc; + const attributes = { + cyc, + big: { n: 10n }, + get hostile(): never { + throw new Error('getter'); + }, + after: 'still here', + }; + const consumed = readableSpanToConsumed(readable({ attributes })); + expect(consumed.attributes).toEqual({ + cyc: { a: 1, self: '[Circular]' }, + big: { n: 10 }, + after: 'still here', + }); + }); + + it('bounds a huge nested value so one attribute cannot bloat the transaction', () => { + const consumed = readableSpanToConsumed( + readable({ attributes: { huge: { s: 'x'.repeat(1e6) } } }), + ); + expect(JSON.stringify(consumed.attributes?.huge).length).toBeLessThanOrEqual(8192); + }); + + it('a statement cut by the consume cap still has its literals redacted by the default sanitizer', () => { + const doc = Array.from({ length: 4000 }, (_, i) => `p${i}@clinic.example;x`).join('\n'); + const consumed = readableSpanToConsumed( + readable({ attributes: { 'db.statement': `INSERT INTO r (d) VALUES ('${doc}')` } }), + ); + const out = sanitizeSpan({ + spanId: 's', + operation: 'db', + status: 'OK', + startTimestampMs: 1, + ...(consumed.attributes !== undefined ? { attributes: consumed.attributes } : {}), + }); + expect(JSON.stringify(out.attributes)).not.toContain('@clinic.example'); + }); + + it('keeps the tree through assembly, so redaction can read nested keys (flattening is the wire step)', () => { + const txns: TransactionWire[] = []; + const processor = createBugseeSpanProcessor({ onTransaction: (t) => txns.push(t) }); + processor.onEnd(readable({ attributes: { 'db.statement': { text: 'SELECT 1' } } })); + expect(txns[0]?.attributes?.['db.statement']).toEqual({ text: 'SELECT 1' }); + }); + }); + it('prefers the OTel 2.x parentSpanContext over the 1.x parentSpanId', () => { const consumed = readableSpanToConsumed( readable({ @@ -109,17 +189,23 @@ describe('createBugseeSpanProcessor', () => { await expect(proc.forceFlush()).resolves.toBeUndefined(); }); - it('shutdown() clears buffered (incomplete) traces', async () => { + it('shutdown() drops buffered (incomplete) traces and stops consuming: a late span.end() is a no-op', async () => { const emitted: TransactionWire[] = []; + const errors: unknown[] = []; const proc = createBugseeSpanProcessor({ onTransaction: (t) => emitted.push(t), + onError: (e) => errors.push(e), clock: { wallNow: () => 0 }, }); proc.onEnd(readable({ traceId: 'T', spanId: 'c', parentSpanId: 'r' })); // buffered child await proc.shutdown(); - // The buffer was cleared, so a later root for T assembles with NO child (the child was dropped). + // OTel's contract: a processor that was shut down receives nothing further. Keeping the assembler live + // would let spans that end after shutdown (provider.shutdown() is not a barrier for in-flight work) + // buffer forever or emit a transaction into a torn-down pipeline. proc.onEnd(readable({ traceId: 'T', spanId: 'r', name: 'root' })); - expect(emitted[0]?.spans).toEqual([]); + proc.onEnd(readable({ traceId: 'U', spanId: 'r2', name: 'other root' })); + expect(emitted).toEqual([]); + expect(errors).toEqual([]); }); // Two tests lived here that promised more than they checked, and are superseded by the forwarding diff --git a/packages/opentelemetry/src/span-processor.ts b/packages/opentelemetry/src/span-processor.ts index f1b5f8208..fb552fc74 100644 --- a/packages/opentelemetry/src/span-processor.ts +++ b/packages/opentelemetry/src/span-processor.ts @@ -1,5 +1,5 @@ import { neverThrow } from '@bugsee/core'; -import type { TransactionWire } from '@bugsee/performance'; +import { normalizeAttributes, type TransactionWire } from '@bugsee/performance'; import type { ConsumedSpan } from './from-otlp'; import { createTraceAssembler } from './trace-assembler'; @@ -7,8 +7,9 @@ import { createTraceAssembler } from './trace-assembler'; // `onEnd(readableSpan)` normalizes the span and feeds the trace assembler, which emits one Bugsee // transaction per trace (root-end policy). STRUCTURAL types (no @opentelemetry/* import) — robust to OTel // SDK version churn (1.x `parentSpanId` vs 2.x `parentSpanContext`) and keeps the package install-lean; -// @opentelemetry/api + sdk-trace-base are declared as OPTIONAL peer deps (a consumer needs them for their -// TracerProvider; produce-only users do not). The returned object is structurally assignable to OTel's +// @opentelemetry/api + the SDK (sdk-trace-base on OTel 1.x/2.x, sdk-trace on 3.x, which removed the former) +// are declared as OPTIONAL peer deps (a consumer needs them for their TracerProvider; produce-only users +// do not). The returned object is structurally assignable to OTel's // `SpanProcessor`. /** OTel `HrTime`: `[seconds, nanoseconds]` since the epoch. */ @@ -35,6 +36,7 @@ export interface ReadableSpanLike { startTime: HrTime; endTime: HrTime; status: { code: number; message?: string }; + /** OTel `Attributes`. Since API 1.10 a value is an `AnyValue` (maps, mixed arrays, bytes): see `normalizeAttributes`. */ attributes?: Record; } @@ -60,7 +62,7 @@ export function readableSpanToConsumed(span: ReadableSpanLike): ConsumedSpan { code: span.status.code, ...(span.status.message !== undefined ? { message: span.status.message } : {}), }, - ...(span.attributes !== undefined ? { attributes: span.attributes } : {}), + ...(span.attributes !== undefined ? { attributes: normalizeAttributes(span.attributes) } : {}), }; } @@ -100,9 +102,11 @@ export function createBugseeSpanProcessor( ...(options.maxAgeMs !== undefined ? { maxAgeMs: options.maxAgeMs } : {}), ...(options.maxTraces !== undefined ? { maxTraces: options.maxTraces } : {}), }); + let stopped = false; return { onStart() {}, // we assemble on span end, not start onEnd(span) { + if (stopped) return; // OTel: a shut-down processor receives nothing further // CONTAINED. Two independent host inputs meet here and BOTH can throw: the `span` (whatever OTel // version and exporter chain the app configured — every property read is a chance) and, downstream of // the assembler, the application's own `onTransaction` sink. Either one escaping lands inside the @@ -113,6 +117,7 @@ export function createBugseeSpanProcessor( return Promise.resolve(); }, shutdown() { + stopped = true; assembler.clear(); return Promise.resolve(); }, diff --git a/packages/opentelemetry/src/to-otlp.test.ts b/packages/opentelemetry/src/to-otlp.test.ts index 2c6854bb5..2145840a1 100644 --- a/packages/opentelemetry/src/to-otlp.test.ts +++ b/packages/opentelemetry/src/to-otlp.test.ts @@ -12,6 +12,15 @@ import { transactionToOtlpSpans, } from './to-otlp'; +/** Node's `Buffer` (a Uint8Array subclass) without pulling @types/node into this portable package. */ +const nodeBuffer = ( + globalThis as unknown as { + Buffer: { + from(input: string | Uint8Array): Uint8Array & { toString(encoding: string): string }; + }; + } +).Buffer; + describe('toUnixNanoString', () => { it('converts wall-clock ms to a decimal ns string WITHOUT precision loss (BigInt, not Number*1e6)', () => { // 1709990000123 * 1e6 = 1.709990000123e18 — beyond 2^53, so Number would lose the low digits. @@ -23,6 +32,8 @@ describe('toUnixNanoString', () => { }); }); +const Url = (globalThis as unknown as { URL: new (input: string) => object }).URL; + describe('toAnyValue', () => { it('maps a string to stringValue', () => { expect(toAnyValue('x')).toEqual({ stringValue: 'x' }); @@ -45,6 +56,84 @@ describe('toAnyValue', () => { expect(toAnyValue({ a: 1 })).toEqual({ stringValue: '{"a":1}' }); expect(toAnyValue([1, 2])).toEqual({ stringValue: '[1,2]' }); }); + it('maps a byte array to bytesValue as base64 (the OTLP/JSON bytes encoding)', () => { + expect(toAnyValue(new Uint8Array([102, 111, 111]))).toEqual({ bytesValue: 'Zm9v' }); + expect(toAnyValue(nodeBuffer.from('hi'))).toEqual({ bytesValue: 'aGk=' }); + expect(toAnyValue(new Uint8Array(0))).toEqual({ bytesValue: '' }); + }); + it('never throws on exotic objects: a cycle, a nested bigint and a nested byte array are encoded safely', () => { + const cyc: Record = { a: 1 }; + cyc.self = cyc; + expect(toAnyValue(cyc)).toEqual({ stringValue: '{"a":1,"self":"[Circular]"}' }); + expect(toAnyValue({ n: 10n })).toEqual({ stringValue: '{"n":10}' }); + expect(toAnyValue({ b: new Uint8Array([1, 2]) })).toEqual({ stringValue: '{"b":"AQI="}' }); + }); + it('caps an oversized object at the attribute JSON length', () => { + const out = toAnyValue({ big: 'x'.repeat(100_000) }) as { stringValue: string }; + expect(out.stringValue.length).toBeLessThanOrEqual(8192); + expect(out.stringValue).toContain('...[truncated]'); + }); + it('keeps bytesValue valid base64: a cut array is sent as a stringValue, never as bytesValue with a marker', () => { + const out = toAnyValue(new Uint8Array(1_000_000)) as { stringValue: string }; + expect('bytesValue' in out).toBe(false); + expect(out.stringValue.length).toBe(8192); + expect(out.stringValue.endsWith('...[truncated]')).toBe(true); + // An array that fits stays a real bytesValue. + expect(toAnyValue(new Uint8Array(1000))).toEqual({ + bytesValue: expect.stringMatching(/^[A-Za-z0-9+/]+=*$/), + }); + }); + it('pins the byte boundary: 6144 bytes (exactly 8192 base64 characters) stays bytesValue, 6145 is cut', () => { + const fits = toAnyValue(new Uint8Array(6144)) as { bytesValue: string }; + expect(fits.bytesValue.length).toBe(8192); + expect(fits.bytesValue.endsWith('...[truncated]')).toBe(false); + const cut = toAnyValue(new Uint8Array(6145)) as { stringValue: string }; + expect('bytesValue' in cut).toBe(false); + expect(cut.stringValue.length).toBe(8192); + expect(cut.stringValue.endsWith('...[truncated]')).toBe(true); + }); + it('never throws: an unencodable object yields no value instead of an exception', () => { + const original = JSON.stringify; + JSON.stringify = () => { + throw new RangeError('Invalid string length'); + }; + try { + expect(toAnyValue({ a: 1 })).toEqual({ stringValue: '"[Unreadable]"' }); + } finally { + JSON.stringify = original; + } + }); + it('exports a Date as its ISO string (not a doubly quoted one) and survives a revoked Proxy', () => { + expect(toAnyValue(new Date(0))).toEqual({ stringValue: '1970-01-01T00:00:00.000Z' }); + expect(toAnyValue(new Date(Number.NaN))).toBeUndefined(); + const { proxy, revoke } = Proxy.revocable({}, {}); + revoke(); + expect(toAnyValue(proxy)).toBeUndefined(); + }); + it('exports a URL as its credential-free href and an Error as name and message', () => { + expect(toAnyValue(new Url('https://u:p@example.com/a'))).toEqual({ + stringValue: 'https://example.com/a', + }); + expect(toAnyValue(new RangeError('too big'))).toEqual({ + stringValue: '{"name":"RangeError","message":"too big"}', + }); + }); + it('drops (never throws on) an object whose type probe throws', () => { + const trap = new Proxy( + {}, + { + getPrototypeOf() { + throw new Error('getPrototypeOf'); + }, + }, + ); + expect(toAnyValue(trap)).toBeUndefined(); + }); + it('bounds a huge nested leaf by size, not just count (no 64 MB copy, output within the cap)', () => { + const huge = 'x'.repeat(64 * 1024 * 1024); + const out = toAnyValue({ a: huge, b: [huge] }) as { stringValue: string }; + expect(out.stringValue.length).toBeLessThanOrEqual(8192); + }); it('returns undefined for undefined/null (the key is dropped)', () => { expect(toAnyValue(undefined)).toBeUndefined(); expect(toAnyValue(null)).toBeUndefined(); @@ -55,6 +144,116 @@ describe('toAnyValue', () => { }); }); +describe('toKeyValues is total (one bad attribute never costs the batch)', () => { + it('drops a throwing attribute and keeps its siblings', () => { + const attrs = { + before: 'a', + get boom(): never { + throw new Error('getter'); + }, + after: 'b', + }; + expect(toKeyValues(attrs)).toEqual([ + { key: 'before', value: { stringValue: 'a' } }, + { key: 'after', value: { stringValue: 'b' } }, + ]); + }); + it('returns no key values, not a throw, for a Proxy whose ownKeys trap throws', () => { + const hostile = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + expect(toKeyValues(hostile as Record)).toEqual([]); + }); + it('does not throw while deriving a child span kind from an unreadable bugsee.span.kind', () => { + const attributes = { + get 'bugsee.span.kind'(): never { + throw new Error('getter'); + }, + ok: 1, + }; + const txn = { + traceId: 'a'.repeat(32), + spanId: 'b'.repeat(16), + name: 'root', + operation: 'op', + status: 'OK', + sampled: true, + startTimestampMs: 1, + endTimestampMs: 2, + isSnapshot: false, + spans: [ + { + spanId: 'c'.repeat(16), + operation: 'http.client', + status: 'OK', + startTimestampMs: 1, + attributes, + }, + ], + } as unknown as TransactionWire; + const spans = transactionToOtlpSpans(txn); + expect(spans).toHaveLength(2); + expect(spans[1]?.kind).toBe(3); // falls back to the operation-derived CLIENT kind + expect(spans[1]?.attributes?.map((a) => a.key)).toContain('ok'); + }); + it('lets a whole export request survive a hostile attribute on one span', () => { + const txn = { + traceId: 'a'.repeat(32), + spanId: 'b'.repeat(16), + name: 'root', + operation: 'op', + status: 'OK', + sampled: true, + startTimestampMs: 1, + endTimestampMs: 2, + isSnapshot: false, + attributes: new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ), + spans: [], + } as unknown as TransactionWire; + const hostileProxy = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + const withChild = { + ...txn, + attributes: { ok: 1 }, + spans: [ + { + spanId: 'd'.repeat(16), + operation: 'child', + status: 'OK', + startTimestampMs: 1, + attributes: hostileProxy, + }, + ], + } as unknown as TransactionWire; + expect(() => + toOtlpExportRequest([withChild], { resource: hostileProxy as never }), + ).not.toThrow(); + const resourced = toOtlpExportRequest([withChild], { resource: hostileProxy as never }); + expect(resourced.resourceSpans[0]?.scopeSpans[0]?.spans).toHaveLength(2); + const good = { ...txn, spanId: 'c'.repeat(16), attributes: { ok: 1 } }; + const request = toOtlpExportRequest([txn, good]); + expect(request.resourceSpans[0]?.scopeSpans[0]?.spans).toHaveLength(2); + }); +}); + describe('toKeyValues', () => { it('maps an attributes record to KeyValue[], dropping undefined/null values', () => { expect(toKeyValues({ a: 'x', b: undefined, c: 2, d: null })).toEqual([ diff --git a/packages/opentelemetry/src/to-otlp.ts b/packages/opentelemetry/src/to-otlp.ts index 2428ede8b..679693fe1 100644 --- a/packages/opentelemetry/src/to-otlp.ts +++ b/packages/opentelemetry/src/to-otlp.ts @@ -1,4 +1,12 @@ -import type { SpanStatus, TransactionWire } from '@bugsee/performance'; +import { + asBytes, + boundedBase64, + type SpanStatus, + safeAnyValue, + stringifyAnyValue, + TRUNCATION_MARKER, + type TransactionWire, +} from '@bugsee/performance'; import { OTLP_SPAN_FLAG_SAMPLED, type OtlpAnyValue, @@ -62,18 +70,68 @@ export function toAnyValue(value: unknown): OtlpAnyValue | undefined { // with a genuinely large integer should pass a `bigint`, which is exact. return Number.isSafeInteger(value) ? { intValue: String(value) } : toDoubleValue(value); default: { - const json = JSON.stringify(value); // objects/arrays → string; functions/symbols → undefined (dropped) - return json !== undefined ? { stringValue: json } : undefined; + try { + const bytes = asBytes(value); + if (bytes !== undefined) { + const encoded = boundedBase64(bytes); + // `bytesValue` must be valid base64: a collector may reject the whole request over a marker in it. + // A cut array is therefore sent as plain text instead. + return encoded.endsWith(TRUNCATION_MARKER) + ? { stringValue: encoded } + : { bytesValue: encoded }; + } + // A value that is a plain string once made safe (a Date, a URL) is that string, not JSON text. + const safe = safeAnyValue(value); + if (typeof safe === 'string') return { stringValue: safe }; + // objects/arrays → bounded JSON string that cannot throw (cycles, bigint, depth); functions/symbols + // and an invalid Date → dropped + const json = safe === undefined || safe === null ? undefined : stringifyAnyValue(safe); + return json !== undefined ? { stringValue: json } : undefined; + } catch { + // An exotic object whose type probe throws (a Proxy with a throwing getPrototypeOf trap). One + // attribute must never cost the export batch: drop it. + return undefined; + } } } } -/** Map an attributes record to OTLP `KeyValue[]`, dropping keys whose value does not encode. */ +/** + * Copy an attributes record's own enumerable string keys, skipping any attribute that cannot be read (a + * throwing getter) and returning an empty copy when the keys cannot be listed (a Proxy with a throwing + * `ownKeys` trap). A spread (`{ ...attributes }`) throws on both, and a throw here rejects the whole export + * batch, so every produce-path read of a caller-supplied record goes through this. + */ +function safeCopy(attributes: Record | undefined): Record { + const out: Record = {}; + if (attributes === undefined) return out; + let keys: string[]; + try { + keys = Object.keys(attributes); + } catch { + return out; + } + for (const key of keys) { + try { + Object.defineProperty(out, key, { + value: attributes[key], + enumerable: true, + writable: true, + configurable: true, + }); + } catch { + // unreadable attribute: dropped, the rest survive + } + } + return out; +} + +/** Map an attributes record to OTLP `KeyValue[]`, dropping keys whose value does not encode. Total. */ export function toKeyValues(attributes: Record | undefined): OtlpKeyValue[] { const out: OtlpKeyValue[] = []; - if (attributes === undefined) return out; - for (const [key, raw] of Object.entries(attributes)) { - const value = toAnyValue(raw); + const safe = safeCopy(attributes); + for (const key of Object.keys(safe)) { + const value = toAnyValue(safe[key]); if (value !== undefined) out.push({ key, value }); } return out; @@ -137,7 +195,7 @@ export function transactionToOtlpSpans(txn: TransactionWire): OtlpSpan[] { const flags = txn.sampled ? OTLP_SPAN_FLAG_SAMPLED : 0; const rootAttributes: Record = { - ...txn.attributes, + ...safeCopy(txn.attributes), // Root requirements: the transaction name, the sampling decision, the lossless // original status, plus the operation + app info + snapshot flag. 'bugsee.transaction.name': txn.name, @@ -162,24 +220,29 @@ export function transactionToOtlpSpans(txn: TransactionWire): OtlpSpan[] { flags, }; - const children: OtlpSpan[] = txn.spans.map((s) => ({ - traceId: txn.traceId, - spanId: s.spanId, - // A parent that is itself a child stays; a dangling/absent parent (the dropped root) → the root. - parentSpanId: - s.parentSpanId !== undefined && childIds.has(s.parentSpanId) ? s.parentSpanId : rootSpanId, - name: s.description ?? s.operation, - kind: spanKindFor(s.operation, s.attributes), - startTimeUnixNano: toUnixNanoString(s.startTimestampMs), - endTimeUnixNano: toUnixNanoString(s.endTimestampMs ?? s.startTimestampMs), - attributes: toKeyValues({ - ...s.attributes, - 'bugsee.operation': s.operation, - 'bugsee.span.status': s.status, - }), - status: toStatus(s.status), - flags, - })); + const children: OtlpSpan[] = txn.spans.map((s) => { + // Copied ONCE and safely: the kind lookup below reads the record too, and a getter that throws there + // would reject the whole export batch. + const attrs = safeCopy(s.attributes); + return { + traceId: txn.traceId, + spanId: s.spanId, + // A parent that is itself a child stays; a dangling/absent parent (the dropped root) → the root. + parentSpanId: + s.parentSpanId !== undefined && childIds.has(s.parentSpanId) ? s.parentSpanId : rootSpanId, + name: s.description ?? s.operation, + kind: spanKindFor(s.operation, attrs), + startTimeUnixNano: toUnixNanoString(s.startTimestampMs), + endTimeUnixNano: toUnixNanoString(s.endTimestampMs ?? s.startTimestampMs), + attributes: toKeyValues({ + ...attrs, + 'bugsee.operation': s.operation, + 'bugsee.span.status': s.status, + }), + status: toStatus(s.status), + flags, + }; + }); return [root, ...children]; } @@ -210,7 +273,7 @@ export function toOtlpExportRequest( // resource, so they can't be overridden away); service.* + telemetry.sdk.language come from `resource`. resource: { attributes: toKeyValues({ - ...options.resource, + ...safeCopy(options.resource), 'telemetry.sdk.name': 'bugsee', 'bugsee.profile.version': '1', }), diff --git a/packages/performance/src/attribute-value.fuzz.test.ts b/packages/performance/src/attribute-value.fuzz.test.ts new file mode 100644 index 000000000..7296124d8 --- /dev/null +++ b/packages/performance/src/attribute-value.fuzz.test.ts @@ -0,0 +1,203 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { + flattenAttributes, + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + MAX_ATTRIBUTE_STRING_LENGTH, + MAX_ATTRIBUTE_TREE_CHARS, + normalizeAttributes, + normalizeAttributeValue, + stringifyAnyValue, + TRUNCATION_MARKER, +} from './attribute-value'; + +/** + * Property tests for complex attribute values (OTel API 1.10 AnyValue). `onEnd` runs inside the customer's + * `span.end()` and an attribute value is whatever their instrumentation put there, so the contract is + * "never throws, always bounded, scalars untouched", over the values that actually break serializers: + * cycles, bigint, typed arrays, sparse arrays, null-prototype objects, deep and wide trees. + */ + +/** Arbitrary JSON-ish trees including the exotic leaves, with optional injected self-references. */ +const exotic = fc.anything({ + withBigInt: true, + withDate: true, + withMap: true, + withSet: true, + withNullPrototype: true, + withSparseArray: true, + withTypedArray: true, + withObjectString: true, + maxDepth: 6, +}); + +const withCycle = exotic.map((value) => { + const holder: Record = { value }; + holder.self = holder; + holder.list = [holder, value]; + return holder; +}); + +const leaf = fc.oneof( + fc.constant(undefined), + fc.constant(null), + fc.constant(() => 1), + fc.constant(Symbol('s')), + fc.constantFrom(Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY), + fc.uint8Array({ maxLength: 64 }), + fc.bigInt(), +); + +const anyValue = fc.oneof(exotic, withCycle, leaf); + +/** A chain nested `levels` deep in objects or arrays. */ +const chain = (levels: number, asArray: boolean): unknown => { + let node: unknown = 'leaf'; + for (let i = 0; i < levels; i++) node = asArray ? [node] : { n: node }; + return node; +}; + +describe('stringifyAnyValue (fuzz)', () => { + it('never throws and never exceeds the length cap', () => { + fc.assert( + fc.property(anyValue, (value) => { + const out = stringifyAnyValue(value); + if (out !== undefined) expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + }), + { numRuns: 400 }, + ); + }); + + it('emits parseable JSON unless it says it truncated', () => { + fc.assert( + fc.property(anyValue, (value) => { + const out = stringifyAnyValue(value); + if (out === undefined || out.endsWith(TRUNCATION_MARKER)) return; + expect(() => JSON.parse(out)).not.toThrow(); + }), + { numRuns: 400 }, + ); + }); + + it('has no output only for values that have no JSON form', () => { + fc.assert( + fc.property(anyValue, (value) => { + const out = stringifyAnyValue(value); + const noForm = + value === undefined || typeof value === 'function' || typeof value === 'symbol'; + expect(out === undefined).toBe(noForm); + }), + { numRuns: 400 }, + ); + }); + + it('never nests deeper than the depth cap, whatever the depth or the container kind', () => { + fc.assert( + fc.property(fc.integer({ min: 0, max: 5000 }), fc.boolean(), (levels, asArray) => { + const parsed = JSON.parse(stringifyAnyValue(chain(levels, asArray)) as string) as unknown; + const depthOf = (node: unknown): number => + typeof node === 'object' && node !== null + ? 1 + Math.max(0, ...Object.values(node).map(depthOf)) + : 0; + const max = depthOf(parsed); + expect(max).toBeLessThanOrEqual(MAX_ATTRIBUTE_DEPTH); + }), + { numRuns: 100 }, + ); + }); + + it('is deterministic', () => { + fc.assert( + fc.property(anyValue, (value) => { + expect(stringifyAnyValue(value)).toBe(stringifyAnyValue(value)); + }), + { numRuns: 200 }, + ); + }); +}); + +const jsonLength = (value: unknown): number => JSON.stringify(value)?.length ?? 0; + +describe('normalizeAttributeValue (fuzz)', () => { + it('returns a scalar, an array, a JSON-safe bounded tree, or nothing, and never throws', () => { + fc.assert( + fc.property(anyValue, (value) => { + const out = normalizeAttributeValue(value); + if (out === undefined) return; + if (typeof out === 'string') { + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); + return; + } + if (typeof out === 'object') { + // A tree is always JSON-serializable and its size is bounded by the budgets, whatever came in. + expect(() => JSON.stringify(out)).not.toThrow(); + expect(jsonLength(out)).toBeLessThanOrEqual(MAX_ATTRIBUTE_TREE_CHARS * 4); + return; + } + expect(['number', 'boolean']).toContain(typeof out); + }), + { numRuns: 400 }, + ); + }); + + it('leaves every scalar and every small homogeneous scalar array untouched', () => { + const scalar = fc.oneof(fc.string({ maxLength: 100 }), fc.boolean(), fc.double(), fc.integer()); + fc.assert( + fc.property(scalar, (v) => { + expect(normalizeAttributeValue(v)).toBe(v); + }), + ); + const arrays: fc.Arbitrary[] = [ + fc.array(fc.string({ maxLength: 20 }), { maxLength: 50 }), + fc.array(fc.boolean(), { maxLength: 50 }), + fc.array(fc.double(), { maxLength: 50 }), + ]; + for (const arb of arrays) { + fc.assert( + fc.property(arb, (arr) => { + expect(normalizeAttributeValue(arr)).toEqual(arr); + }), + ); + } + }); +}); + +describe('flattenAttributes (fuzz)', () => { + it('always yields scalars, small scalar arrays or bounded strings, and is JSON-serializable', () => { + fc.assert( + fc.property(fc.dictionary(fc.string({ maxLength: 8 }), anyValue, { maxKeys: 8 }), (attrs) => { + const out = flattenAttributes(attrs); + expect(() => JSON.stringify(out)).not.toThrow(); + for (const value of Object.values(out)) { + expect(value !== null && typeof value === 'object' && !Array.isArray(value)).toBe(false); + if (typeof value === 'string') { + expect(value.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); + } + } + }), + { numRuns: 200 }, + ); + }); + + it('is idempotent', () => { + fc.assert( + fc.property(fc.dictionary(fc.string({ maxLength: 8 }), anyValue, { maxKeys: 8 }), (attrs) => { + const once = flattenAttributes(attrs); + expect(flattenAttributes(once)).toEqual(once); + }), + { numRuns: 100 }, + ); + }); +}); + +describe('normalizeAttributes (fuzz)', () => { + it('output is always JSON-serializable', () => { + fc.assert( + fc.property(fc.dictionary(fc.string({ maxLength: 8 }), anyValue, { maxKeys: 8 }), (attrs) => { + expect(() => JSON.stringify(normalizeAttributes(attrs))).not.toThrow(); + }), + { numRuns: 200 }, + ); + }); +}); diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts new file mode 100644 index 000000000..e6b914d94 --- /dev/null +++ b/packages/performance/src/attribute-value.test.ts @@ -0,0 +1,809 @@ +import { redactShapes } from '@bugsee/protocol'; +import { describe, expect, it, vi } from 'vitest'; +import { + boundedBase64, + bytesToBase64, + flattenAttributes, + flattenAttributeValue, + MAX_ATTRIBUTE_ARRAY_LENGTH, + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + MAX_ATTRIBUTE_NODES, + MAX_ATTRIBUTE_STRING_LENGTH, + MAX_ATTRIBUTE_TREE_CHARS, + normalizeAttributes, + normalizeAttributeValue, + safeAnyValue, + stringifyAnyValue, + TRUNCATION_MARKER, +} from './attribute-value'; + +/** Node's `Buffer` (a Uint8Array subclass) without pulling @types/node into this portable package. */ +const nodeBuffer = ( + globalThis as unknown as { + Buffer: { + from(input: string | Uint8Array): Uint8Array & { toString(encoding: string): string }; + }; + } +).Buffer; + +describe('bytesToBase64', () => { + it.each([ + [[], ''], + [[102], 'Zg=='], + [[102, 111], 'Zm8='], + [[102, 111, 111], 'Zm9v'], + [[0, 255, 254, 253], 'AP/+/Q=='], + ])('encodes %j as %s (RFC 4648, padded)', (bytes, expected) => { + expect(bytesToBase64(new Uint8Array(bytes))).toBe(expected); + }); + + it('agrees with Buffer on every byte value', () => { + const all = new Uint8Array(256).map((_, i) => i); + expect(bytesToBase64(all)).toBe(nodeBuffer.from(all).toString('base64')); + }); + + it('encodes a Node Buffer (a Uint8Array subclass)', () => { + expect(bytesToBase64(nodeBuffer.from('hello'))).toBe('aGVsbG8='); + }); +}); + +describe('stringifyAnyValue', () => { + it('serializes plain JSON-shaped values exactly like JSON.stringify', () => { + const value = { a: 1, b: ['x', true, null, { c: 2.5 }], d: { e: { f: 'g' } } }; + expect(stringifyAnyValue(value)).toBe(JSON.stringify(value)); + expect(stringifyAnyValue([1, 'a', true])).toBe('[1,"a",true]'); + expect(stringifyAnyValue('s')).toBe('"s"'); + expect(stringifyAnyValue(null)).toBe('null'); + }); + + it('has no output for a value with no JSON form at the top level', () => { + expect(stringifyAnyValue(undefined)).toBeUndefined(); + expect(stringifyAnyValue(() => 1)).toBeUndefined(); + expect(stringifyAnyValue(Symbol('s'))).toBeUndefined(); + }); + + it('writes a byte array as base64, at any depth', () => { + expect(stringifyAnyValue(new Uint8Array([102, 111, 111]))).toBe('"Zm9v"'); + expect(stringifyAnyValue({ blob: new Uint8Array([1, 2]) })).toBe('{"blob":"AQI="}'); + expect(stringifyAnyValue([nodeBuffer.from('hi')])).toBe('["aGk="]'); + }); + + it('handles a nested bigint like a top-level one: a number when exact, decimal text beyond it', () => { + expect(stringifyAnyValue({ n: 12345678901234567890n })).toBe('{"n":"12345678901234567890"}'); + expect(stringifyAnyValue({ n: 10n, list: [1n, -2n] })).toBe('{"n":10,"list":[1,-2]}'); + expect(safeAnyValue({ edge: BigInt(Number.MAX_SAFE_INTEGER) + 1n })).toEqual({ + edge: '9007199254740992', + }); + }); + + it('spells non-finite numbers the way the OTLP double does (JSON would say null)', () => { + expect( + stringifyAnyValue([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]), + ).toBe('["NaN","Infinity","-Infinity"]'); + }); + + it('drops function/symbol/undefined members of an object and nulls them in an array (JSON semantics)', () => { + expect(stringifyAnyValue({ a: 1, f: () => 1, s: Symbol('x'), u: undefined })).toBe('{"a":1}'); + expect(stringifyAnyValue([1, () => 1, Symbol('x'), undefined])).toBe('[1,null,null,null]'); + }); + + it('writes a Date as ISO-8601 and an invalid Date as null', () => { + expect(stringifyAnyValue({ at: new Date(0) })).toBe('{"at":"1970-01-01T00:00:00.000Z"}'); + expect(stringifyAnyValue([new Date(Number.NaN)])).toBe('[null]'); + }); + + it('does not run user code: toJSON is ignored and a class instance is read by own enumerable keys', () => { + let called = 0; + class Thing { + x = 1; + toJSON() { + called++; + return 'boom'; + } + } + expect(stringifyAnyValue(new Thing())).toBe('{"x":1}'); + expect(called).toBe(0); + }); + + it('marks a cycle instead of throwing, but does not mistake a shared (acyclic) reference for one', () => { + const cyc: Record = { a: 1 }; + cyc.self = cyc; + expect(stringifyAnyValue(cyc)).toBe('{"a":1,"self":"[Circular]"}'); + + const shared = { v: 1 }; + expect(stringifyAnyValue({ x: shared, y: shared })).toBe('{"x":{"v":1},"y":{"v":1}}'); + }); + + it('marks a deep structure at the depth cap rather than recursing without bound', () => { + let deep: unknown = 'leaf'; + for (let i = 0; i < 10_000; i++) deep = { n: deep }; + const out = stringifyAnyValue(deep) as string; + expect(out).toContain('"[MaxDepth]"'); + expect(out.split('{').length - 1).toBe(MAX_ATTRIBUTE_DEPTH); + }); + + it('stops visiting after the node budget, keeps what it read, and says so once', () => { + const wide = Array.from({ length: MAX_ATTRIBUTE_NODES * 3 }, (_, i) => i); + const parsed = JSON.parse(stringifyAnyValue(wide) as string) as unknown[]; + expect(parsed.filter((v) => v === '[Truncated]')).toHaveLength(1); + expect(parsed.at(-1)).toBe('[Truncated]'); + expect(parsed[0]).toBe(0); + // The array itself is one visited node, so MAX - 1 elements fit before the marker. + expect(parsed).toHaveLength(MAX_ATTRIBUTE_NODES); + }); + + it('applies the node budget across an object too, flagging it with a [Truncated] key', () => { + // Each member costs 4 nodes (the member, its array, two elements): the budget runs out near 256 members. + const wide = Object.fromEntries( + Array.from({ length: MAX_ATTRIBUTE_NODES }, (_, i) => [`k${i}`, [0, 0]]), + ); + const parsed = JSON.parse(stringifyAnyValue(wide) as string) as Record; + expect(parsed['[Truncated]']).toBe(true); + expect(parsed.k0).toEqual([0, 0]); + expect(Object.keys(parsed).length).toBeGreaterThan(200); + expect(Object.keys(parsed).length).toBeLessThan(MAX_ATTRIBUTE_NODES / 3); + }); + + it('caps the output length and marks the cut', () => { + const out = stringifyAnyValue({ big: 'word '.repeat(10_000) }) as string; + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + expect(out).toContain(TRUNCATION_MARKER); + expect(out.startsWith('{"big":"word word')).toBe(true); + // Many mid-size leaves overflow the text cap itself: the text is cut and ends with the marker. + const many = stringifyAnyValue(Array.from({ length: 20 }, () => 'y'.repeat(2000))) as string; + expect(many.length).toBe(MAX_ATTRIBUTE_JSON_LENGTH); + expect(many.endsWith(TRUNCATION_MARKER)).toBe(true); + }); + + it('does not truncate output that fits exactly at the cap', () => { + // `["",""]` is a.length + b.length + 7 characters of JSON. + const first = 'y'.repeat(4000); + const second = 'z'.repeat(MAX_ATTRIBUTE_JSON_LENGTH - 7 - first.length); + const out = stringifyAnyValue([first, second]) as string; + expect(out).toBe(JSON.stringify([first, second])); + expect(out.length).toBe(MAX_ATTRIBUTE_JSON_LENGTH); + }); + + it('cuts a single leaf string and a key to a bounded length, marked', () => { + const leaf = JSON.parse(stringifyAnyValue('x'.repeat(100_000)) as string) as string; + expect(leaf.length).toBeLessThan(MAX_ATTRIBUTE_JSON_LENGTH); + expect(leaf.endsWith(TRUNCATION_MARKER)).toBe(true); + const keyed = safeAnyValue({ ['k'.repeat(100_000)]: 1 }) as Record; + const [key] = Object.keys(keyed); + expect((key as string).length).toBeLessThan(MAX_ATTRIBUTE_JSON_LENGTH); + expect((key as string).endsWith(TRUNCATION_MARKER)).toBe(true); + }); + + it('bounds WORK by size, not just count: a huge nested leaf is cut before it is copied or encoded', () => { + const huge = 'word '.repeat(13 * 1024 * 1024); + const out = stringifyAnyValue({ a: huge, b: [huge, { c: huge }] }) as string; + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + const safe = safeAnyValue({ a: huge, b: [huge, { c: huge }] }); + expect(JSON.stringify(safe).length).toBeLessThanOrEqual(MAX_ATTRIBUTE_TREE_CHARS + 1024); + }); + + it('stops copying string leaves after the character budget, however many leaves there are', () => { + const megabyte = 'word '.repeat(200_000); + const many = Array.from({ length: 1000 }, () => megabyte); + const safe = safeAnyValue(many) as unknown[]; + expect(safe.at(-1)).toBe('[Truncated]'); + expect(JSON.stringify(safe).length).toBeLessThan(MAX_ATTRIBUTE_TREE_CHARS * 2); + expect((stringifyAnyValue(many) as string).length).toBeLessThanOrEqual( + MAX_ATTRIBUTE_JSON_LENGTH, + ); + }); + + it('reads a non-byte typed array by index within the node budget instead of listing every key', () => { + const embedding = new Float32Array(MAX_ATTRIBUTE_NODES * 10).fill(0.5); + const safe = safeAnyValue(embedding) as unknown[]; + expect(safe[0]).toBe(0.5); + expect(safe.at(-1)).toBe('[Truncated]'); + expect(safe.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_NODES); + }); + + it('does not throw when the serialized tree cannot be stringified', () => { + // A tree is JSON-safe by construction; force the failure path through an unusable JSON.stringify. + const original = JSON.stringify; + JSON.stringify = () => { + throw new RangeError('Invalid string length'); + }; + try { + expect(stringifyAnyValue({ a: 1 })).toBe('"[Unreadable]"'); + } finally { + JSON.stringify = original; + } + }); + + it('survives a hostile object: a throwing getter or a throwing Proxy never escapes', () => { + const getter = { + ok: 1, + get bad(): never { + throw new Error('getter'); + }, + }; + expect(stringifyAnyValue(getter)).toBe('{"ok":1,"bad":"[Unreadable]"}'); + + const proxy = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + expect(stringifyAnyValue({ p: proxy })).toBe('{"p":"[Unreadable]"}'); + expect(stringifyAnyValue(proxy)).toBe('"[Unreadable]"'); + }); + + it('survives a throwing array element and a Proxy that throws on type probing', () => { + const arr: unknown[] = [1, 2, 3]; + Object.defineProperty(arr, 1, { + get() { + throw new Error('element'); + }, + }); + expect(stringifyAnyValue(arr)).toBe('[1,"[Unreadable]",3]'); + + const protoTrap = new Proxy( + {}, + { + getPrototypeOf() { + throw new Error('getPrototypeOf'); + }, + }, + ); + expect(stringifyAnyValue(protoTrap)).toBe('"[Unreadable]"'); + expect(stringifyAnyValue([protoTrap])).toBe('["[Unreadable]"]'); + }); + + it('keeps a __proto__ key as data', () => { + const parsed = JSON.parse('{"__proto__":{"polluted":true},"a":1}') as unknown; + const out = JSON.parse(stringifyAnyValue(parsed) as string) as Record; + expect(Object.hasOwn(out, '__proto__')).toBe(true); + expect(({} as Record).polluted).toBeUndefined(); + }); +}); + +const Url = (globalThis as unknown as { URL: new (input: string) => object }).URL; + +describe('non-plain values (deliberate handling)', () => { + it('writes a URL as its href with any credentials removed', () => { + expect(safeAnyValue({ u: new Url('https://user:pw@example.com/a?b=1#c') })).toEqual({ + u: 'https://example.com/a?b=1#c', + }); + expect(normalizeAttributeValue(new Url('https://example.com/x'))).toBe('https://example.com/x'); + }); + + it('writes an Error as its name and message only (never the stack)', () => { + const out = safeAnyValue({ e: new TypeError('bad input') }) as { e: Record }; + expect(out.e).toEqual({ name: 'TypeError', message: 'bad input' }); + expect(JSON.stringify(out)).not.toContain('at '); + }); + + it('writes a top-level Date as a plain ISO string, not JSON text', () => { + expect(normalizeAttributeValue(new Date(0))).toBe('1970-01-01T00:00:00.000Z'); + expect(normalizeAttributeValue(new Date(Number.NaN))).toBeUndefined(); + }); + + it('reads ArrayBuffer, DataView and a cross-realm Uint8Array as bytes', () => { + const bytes = new Uint8Array([102, 111, 111]); + expect(normalizeAttributeValue(bytes.buffer)).toBe('Zm9v'); + expect(normalizeAttributeValue(new DataView(bytes.buffer, 1, 2))).toBe('b28='); + // A typed array from another realm fails `instanceof Uint8Array` (it became an index map before). + const vm = ( + globalThis as unknown as { + process: { getBuiltinModule(id: string): { runInNewContext(code: string): unknown } }; + } + ).process.getBuiltinModule('node:vm'); + const foreign = vm.runInNewContext('new Uint8Array([102, 111, 111])') as Uint8Array; + expect(foreign instanceof Uint8Array).toBe(false); + expect(normalizeAttributeValue(foreign)).toBe('Zm9v'); + const huge = vm.runInNewContext('new Uint8Array(100000)') as Uint8Array; + const out = normalizeAttributeValue(huge) as string; + expect(out.length).toBe(MAX_ATTRIBUTE_JSON_LENGTH); + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + }); + + it('leaves Map and Set as empty objects (documented: no own enumerable properties)', () => { + expect(safeAnyValue({ m: new Map([['a', 1]]), s: new Set([1]) })).toEqual({ m: {}, s: {} }); + }); +}); + +describe('normalizeAttributeValue', () => { + it('leaves primitives unchanged; a bigint becomes a number when exact, decimal text otherwise', () => { + for (const v of ['s', '', 0, -1.5, true, false, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(normalizeAttributeValue(v)).toBe(v); + } + expect(normalizeAttributeValue(7n)).toBe(7); + expect(normalizeAttributeValue(BigInt(Number.MAX_SAFE_INTEGER))).toBe(Number.MAX_SAFE_INTEGER); + expect(normalizeAttributeValue(BigInt(Number.MIN_SAFE_INTEGER))).toBe(Number.MIN_SAFE_INTEGER); + expect(normalizeAttributeValue(BigInt(Number.MAX_SAFE_INTEGER) + 1n)).toBe('9007199254740992'); + expect(normalizeAttributeValue(BigInt(Number.MIN_SAFE_INTEGER) - 1n)).toBe('-9007199254740992'); + }); + + it('leaves a homogeneous array of primitives unchanged (the same array)', () => { + const strs = ['a', 'b']; + const nums = [1, 2.5]; + const bools = [true, false]; + expect(normalizeAttributeValue(strs)).toEqual(strs); + expect(normalizeAttributeValue(nums)).toEqual(nums); + expect(normalizeAttributeValue(bools)).toEqual(bools); + expect(normalizeAttributeValue([])).toEqual([]); + }); + + it('keeps a mixed array, an array with null, or a nested array as a bounded COPY, not text', () => { + expect(normalizeAttributeValue([1, 'a', true])).toEqual([1, 'a', true]); + expect(normalizeAttributeValue(['a', null])).toEqual(['a', null]); + expect(normalizeAttributeValue([[1], [2]])).toEqual([[1], [2]]); + }); + + it('passes a homogeneous scalar array that contains null/undefined entries through (as an equal copy)', () => { + const withNull = ['a', null, 'b']; + const nums = [1, undefined, 3]; + expect(normalizeAttributeValue(withNull)).toEqual(withNull); + expect(normalizeAttributeValue(nums)).toEqual(nums); + expect(flattenAttributeValue(withNull)).toEqual(withNull); + // ...but a mixed array still goes the tree route + expect(normalizeAttributeValue(['a', 1, null])).toEqual(['a', 1, null]); + expect(normalizeAttributeValue(['a', 1, null])).not.toEqual(withNull); + }); + + it('routes a primitive array past the length cap through the bounded tree (truncated)', () => { + const long = Array.from({ length: MAX_ATTRIBUTE_ARRAY_LENGTH + 1 }, () => 'a'); + const out = normalizeAttributeValue(long) as unknown[]; + expect(out).not.toBe(long); + expect(out.at(-1)).toBe('[Truncated]'); + const atCap = Array.from({ length: MAX_ATTRIBUTE_ARRAY_LENGTH }, () => 'a'); + expect(normalizeAttributeValue(atCap)).toEqual(atCap); + }); + + it('keeps an object as a safe copy (nested keys still visible to redaction) and bytes as base64', () => { + const input = { a: { b: [1, 'x'] } }; + const out = normalizeAttributeValue(input); + expect(out).toEqual(input); + expect(out).not.toBe(input); + expect(normalizeAttributeValue(new Uint8Array([102, 111, 111]))).toBe('Zm9v'); + expect(normalizeAttributeValue(nodeBuffer.from('hi'))).toBe('aGk='); + }); + + it('caps a scalar string at the documented limit, marked, and leaves one at the limit alone', () => { + const atLimit = 'ab '.repeat(MAX_ATTRIBUTE_STRING_LENGTH).slice(0, MAX_ATTRIBUTE_STRING_LENGTH); + expect(normalizeAttributeValue(atLimit)).toBe(atLimit); + const over = normalizeAttributeValue(`${atLimit}y`) as string; + expect(over.length).toBe(MAX_ATTRIBUTE_STRING_LENGTH); + expect(over.endsWith(TRUNCATION_MARKER)).toBe(true); + }); + + it('does not pass a string array through when its strings add up past the string limit', () => { + const big = Array.from({ length: 4 }, () => 'x'.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 2)); + const out = normalizeAttributeValue(big) as string[]; + expect(out).toHaveLength(4); // went the tree route: each over-long leaf is cut, not passed through + expect(out.every((leaf) => leaf.length < MAX_ATTRIBUTE_JSON_LENGTH)).toBe(true); + const small = [ + 'a'.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 2), + 'b'.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 2), + ]; + expect(normalizeAttributeValue(small)).toEqual(small); + }); + + it('drops the attribute for the OTel empty value and for values with no JSON form', () => { + expect(normalizeAttributeValue(null)).toBeUndefined(); + expect(normalizeAttributeValue(undefined)).toBeUndefined(); + expect(normalizeAttributeValue(() => 1)).toBeUndefined(); + expect(normalizeAttributeValue(Symbol('s'))).toBeUndefined(); + }); + + it('caps a huge base64 attribute at the JSON length cap', () => { + const out = normalizeAttributeValue(new Uint8Array(100_000)) as string; + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + }); +}); + +describe('normalizeAttributes', () => { + it('normalizes every value and drops the ones with no representation', () => { + expect( + normalizeAttributes({ + s: 'x', + n: 3, + tags: ['a', 'b'], + obj: { k: 1 }, + mixed: [1, 'a'], + bytes: new Uint8Array([1]), + nul: null, + und: undefined, + fn: () => 1, + }), + ).toEqual({ s: 'x', n: 3, tags: ['a', 'b'], obj: { k: 1 }, mixed: [1, 'a'], bytes: 'AQ==' }); + }); + + it('keeps the other attributes when one attribute is unreadable', () => { + const attrs = { + ok: 'yes', + get boom(): never { + throw new Error('getter'); + }, + after: 2, + }; + expect(normalizeAttributes(attrs)).toEqual({ ok: 'yes', after: 2 }); + }); + + it('stores a __proto__ attribute as an own key and never rewrites the prototype', () => { + const attrs = JSON.parse('{"__proto__":["a","b"],"k":1}') as Record; + const out = normalizeAttributes(attrs); + expect(Object.hasOwn(out, '__proto__')).toBe(true); + expect(Object.getPrototypeOf(out)).toBe(Object.prototype); + expect(out.k).toBe(1); + }); + + it('yields no attributes, not a throw, when the keys cannot be listed (Proxy ownKeys trap)', () => { + const hostile = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + expect(normalizeAttributes(hostile)).toEqual({}); + }); + + it('reads only own enumerable string keys', () => { + const inherited = Object.create({ inherited: 'no' }) as Record; + inherited.own = 'yes'; + expect(normalizeAttributes(inherited)).toEqual({ own: 'yes' }); + }); +}); + +describe('work bounds that output alone cannot show', () => { + it('encodes at most what could fit: a huge byte array is cut BEFORE it is base64-encoded', () => { + const spy = vi.spyOn(Uint8Array.prototype, 'subarray'); + try { + boundedBase64(new Uint8Array(1_000_000)); + expect(spy).toHaveBeenCalledWith(0, Math.ceil((MAX_ATTRIBUTE_JSON_LENGTH * 3) / 4) + 3); + spy.mockClear(); + boundedBase64(new Uint8Array(10)); + expect(spy).not.toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + }); + + it('copies exactly MAX_ATTRIBUTE_NODES - 1 members of a wide object, then flags truncation', () => { + const wide = Object.fromEntries( + Array.from({ length: MAX_ATTRIBUTE_NODES + 50 }, (_, i) => [`k${i}`, 0]), + ); + const keys = Object.keys(safeAnyValue(wide) as Record); + expect(keys).toHaveLength(1024); // 1023 members + the flag: MAX_ATTRIBUTE_NODES is 1024 + expect(keys.at(-1)).toBe('[Truncated]'); + }); +}); + +const MAX_LEAF = MAX_ATTRIBUTE_JSON_LENGTH - 64; + +describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape scanning applies)', () => { + const leafEnd = MAX_LEAF - TRUNCATION_MARKER.length; + const spaced = (length: number): string => 'ab '.repeat(length).slice(0, length); + + it('drops a JWT cut after its payload from a map leaf', () => { + const jwtPrefix = 'eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InBhdGllbnRAeC5leGFtcGxlIn0'; + const out = safeAnyValue({ note: `${spaced(leafEnd - 20)} ${jwtPrefix}.sig` }) as { + note: string; + }; + expect(out.note.endsWith(TRUNCATION_MARKER)).toBe(true); + expect(out.note).not.toContain('eyJ'); + }); + + it('drops a GitHub-token prefix cut at a nested leaf', () => { + const text = `${spaced(leafEnd - 21)} ghp_abcdefghijklmnopqrstuvwxyz0123456789AB`; + const out = safeAnyValue({ note: text }) as { note: string }; + expect(out.note).not.toContain('ghp_'); + expect(out.note.endsWith(TRUNCATION_MARKER)).toBe(true); + }); + + // The run is dropped only if EVERY character of it counts as a token character. `-` (base64url JWT + // segments), `=`, `+`, `/`, `_` and `.` each need their own case: the cut lands right after the character. + it.each([ + '-', + '=', + '+', + '/', + '_', + '.', + 'a', + 'Z', + '5', + ])('treats %s as part of a token (cut right after it drops the whole unfinished token)', (ch) => { + const text = `${spaced(leafEnd - 8)} secret${ch}${'X'.repeat(50)}`; + expect(text[leafEnd - 1]).toBe(ch); + const out = safeAnyValue({ note: text }) as { note: string }; + expect(out.note).not.toContain('secret'); + expect(out.note.endsWith(`${TRUNCATION_MARKER}`)).toBe(true); + }); + + it('does NOT treat a space or punctuation as part of a token (that text is kept)', () => { + for (const ch of [' ', ',', ';', ':', '"']) { + const text = `${spaced(leafEnd - 8)} secret${ch}${'X'.repeat(50)}`; + const out = safeAnyValue({ note: text }) as { note: string }; + expect(out.note).toContain(`secret${ch}`); + } + }); + + it('keeps a token that ends exactly at the cut (it is complete, not partial)', () => { + const make = (pad: number): string => `${'z'.repeat(pad)}${'tok '.repeat(MAX_LEAF / 4 + 5)}`; + const pad = [0, 1, 2, 3].find((p) => make(p)[leafEnd] === ' ') as number; + const out = safeAnyValue({ note: make(pad) }) as { note: string }; + expect(out.note.endsWith(`tok${TRUNCATION_MARKER}`)).toBe(true); + }); + + describe('a leaf with no token boundary keeps its cut prefix, but never a half-written secret', () => { + const b64url = (text: string): string => + (globalThis as unknown as { btoa(input: string): string }) + .btoa(text) + .replace(/=+$/, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); + const header = 'eyJhbGciOiJIUzI1NiJ9'; + const claims = '"email":"patient@clinic.example","ssn":"123-45-6789"'; + const longPad = `"pad":"${'p'.repeat(9000)}"`; + // a payload long enough that the leaf cap lands INSIDE it, and one with a nested `{"` (an inner `eyJ`) + const plainPayload = b64url(`{${claims},${longPad}}`); + const nestedPayload = ((): string => { + for (let pad = 0; pad < 8; pad += 1) { + const payload = b64url( + `${' '.repeat(pad)}{${claims},"realm_access":{"roles":["admin"]},${longPad}}`, + ); + if (payload.indexOf('eyJ', 3) > 0) return payload; + } + throw new Error('no nested-eyJ payload found'); + })(); + const jwtOf = (payload: string): string => `${header}.${payload}.${'S'.repeat(40)}`; + const leaf = (text: string): string => (safeAnyValue({ note: text }) as { note: string }).note; + + it('keeps a hash or a URL-shaped prefix', () => { + const hash = leaf('f'.repeat(9000)); + expect(hash.length).toBe(MAX_LEAF); + expect(hash.startsWith('ffff')).toBe(true); + }); + + it.each([ + ['a flat payload', plainPayload], + ['a payload with a nested claim (a second eyJ inside it)', nestedPayload], + ])('backs off a JWT cut inside its payload to exactly its start: %s', (_name, payload) => { + expect(leaf(jwtOf(payload))).toBe(TRUNCATION_MARKER); // begins the leaf, nothing before it to keep + for (const prefix of ['id_token=', '/auth/callback/', 'token.', 'a_b-c']) { + expect(leaf(`${prefix}${jwtOf(payload)}`)).toBe(`${prefix}${TRUNCATION_MARKER}`); + } + }); + + it('backs off an unfinished JWT even when its payload holds a complete secret of another shape', () => { + // The AWS key is complete, the JWT is not (two segments): finishing the check on "a secret appears + // somewhere" instead of "a secret BEGINS here" would keep the whole payload. + const payload = `eyJleHAiOjEs${'x'.repeat(100)}AKIAIOSFODNN7EXAMPLE${'y'.repeat(9000)}`; + const out = leaf(`id_token=${header}.${payload}`); + expect(out).toBe(`id_token=${TRUNCATION_MARKER}`); + }); + + it('leaves a JWT cut inside its SIGNATURE to redaction, which matches the three segments whole', () => { + const shortPayload = b64url(`{${claims}}`); + const jwt = `${header}.${shortPayload}.${'S'.repeat(9000)}`; + const out = leaf(`id_token=${jwt}`); + expect(out.startsWith(`id_token=${header}.`)).toBe(true); + const redacted = redactShapes(out); + expect(redacted).not.toContain(shortPayload); + expect(redacted.startsWith('id_token=')).toBe(true); + }); + + it('drops a JWT that follows a space (the space is the boundary, the JWT is the unfinished run)', () => { + const out = leaf(`${'word '.repeat(10)} ${jwtOf(nestedPayload)}`); + expect(out).not.toContain(nestedPayload.slice(0, 20)); + expect(out.startsWith('word word')).toBe(true); + expect(leaf(` ${jwtOf(plainPayload)}`)).toBe(` ${TRUNCATION_MARKER}`); + }); + + it('ignores a secret that begins AFTER the cut (nothing of it is kept, the leaf stays at its cap)', () => { + const out = leaf(`${'a'.repeat(9000)}ghp_abcdefghijklmnopqrstuvwxyz0123456789`); + expect(out.length).toBe(MAX_LEAF); + expect(out.startsWith('aaaa')).toBe(true); + }); + + it.each([ + ['ghp_', 'ghp_abcdefghijklmnopqrstuvwxyz0123456789'], + ['AKIA', 'AKIAIOSFODNN7EXAMPLE'], + ['ASIA', 'ASIAIOSFODNN7EXAMPLE'], + ])('backs off a %s secret the cut leaves half-written to exactly its start', (_needle, secret) => { + const filler = 'a'.repeat(MAX_LEAF - TRUNCATION_MARKER.length - 9); // 9 characters of the secret survive + expect(leaf(`${filler}${secret}${'b'.repeat(200)}`)).toBe(`${filler}${TRUNCATION_MARKER}`); + }); + + it.each([ + ['sk_live_', ['sk', 'live', 'abcdefghijklmnopqrstuvwx'].join('_')], + ['whsec_', ['whsec', 'abcdefghijklmnopqrstuvwx'].join('_')], + ])('keeps a %s prefix: its pattern matches a partial key, so redaction takes it whole', (_needle, secret) => { + const filler = 'a'.repeat(MAX_LEAF - TRUNCATION_MARKER.length - 9); + const out = leaf(`${filler}${secret}${'b'.repeat(200)}`); + expect(redactShapes(out)).not.toContain(secret.slice(0, 12)); + }); + + it('does not cut a complete secret in half because another shape begins inside it', () => { + const filler = 'a'.repeat(MAX_LEAF - TRUNCATION_MARKER.length - 30); + // a complete AKIA key with an ASIA inside its tail, then more run past the cut + const out = leaf(`x=${filler}AKIAXXXXASIAYYYYYYYY${'c'.repeat(200)}`); + expect(out.startsWith('x=aaaa')).toBe(true); + expect(out).toContain('AKIAXXXXASIAYYYYYYYY'); // complete: kept for redaction to match whole + }); + + it('finds the unfinished secret after complete, independent ones', () => { + const first = `ghp_${'a'.repeat(36)}`; + const second = 'AKIAIOSFODNN7EXAMPLE'; + const lead = `${first}${second}`; + const filler = 'q'.repeat(MAX_LEAF - TRUNCATION_MARKER.length - lead.length - 9); + const out = leaf(`${lead}${filler}${'AKIAIOSFODNN7EXAMPLE'}${'d'.repeat(200)}`); + expect(out).toBe(`${lead}${filler}${TRUNCATION_MARKER}`); + }); + }); + + it('does not touch base64 of a byte array (not text)', () => { + const out = normalizeAttributeValue(new Uint8Array(100_000)) as string; + expect(out.length).toBe(MAX_ATTRIBUTE_JSON_LENGTH); + const nested = safeAnyValue({ b: new Uint8Array(100_000) }) as { b: string }; + expect(nested.b.length).toBeGreaterThan(MAX_ATTRIBUTE_JSON_LENGTH - 200); + }); + + it('a TOP-LEVEL string is only cut: shape scanning does not apply there, so dropping protects nothing', () => { + const url = `https://host.example/${'p'.repeat(MAX_ATTRIBUTE_STRING_LENGTH)}`; + const out = normalizeAttributeValue(url) as string; + expect(out.length).toBe(MAX_ATTRIBUTE_STRING_LENGTH); + expect(out.startsWith('https://host.example/')).toBe(true); + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + }); +}); + +describe('arrays are copied, not aliased', () => { + it('reads the length once: a Proxy array whose length keeps growing cannot loop forever', () => { + let reads = 0; + const target = ['a', 'b']; + const growing = new Proxy(target, { + get(t, key, receiver) { + if (key === 'length') return ++reads * 1000; // grows on every read + return Reflect.get(t, key, receiver); + }, + }); + const started = Date.now(); + const out = normalizeAttributeValue(growing); + expect(Date.now() - started).toBeLessThan(2000); + expect(Array.isArray(out)).toBe(true); + expect(reads).toBeLessThan(10); + }); + + it("flattening never hands back the caller's array (a custom filter may have set it)", () => { + const held: unknown[] = ['a', 'b']; + const out = flattenAttributeValue(held) as unknown[]; + expect(out).toEqual(['a', 'b']); + expect(out === held).toBe(false); + held.push({ password: 'x' }); + expect(out).toEqual(['a', 'b']); + const attrs = { tags: held.slice(0, 2) }; + const flat = flattenAttributes(attrs); + expect(flat.tags === attrs.tags).toBe(false); + }); + + it('passes a scalar array through as a COPY, so a later mutation of the original cannot reach the store', () => { + const original: unknown[] = ['a', 'b']; + const out = normalizeAttributeValue(original) as unknown[]; + expect(out).toEqual(['a', 'b']); + expect(out).not.toBe(original); + original.push({ password: 'x' }); + expect(out).toEqual(['a', 'b']); + }); + + it('reads an array by index: an overridden Symbol.iterator cannot smuggle values past the check', () => { + const sneaky: unknown[] = ['a', 'b']; + (sneaky as unknown as Record)[Symbol.iterator] = function* () { + yield 'a'; + yield 'b'; + }; + sneaky.push({ password: 'p' }); // an element the iterator hides + const out = normalizeAttributeValue(sneaky) as unknown[]; + expect(out).toEqual(['a', 'b', { password: 'p' }]); // went the tree route, element visible + }); + + it('reads each element once (a getter cannot answer differently on a second read)', () => { + let reads = 0; + const arr: unknown[] = []; + Object.defineProperty(arr, 0, { + get() { + reads++; + return reads === 1 ? 'ok' : { late: true }; + }, + enumerable: true, + }); + const out = normalizeAttributeValue(arr) as unknown[]; + expect(out).toEqual(['ok']); + expect(reads).toBe(1); + }); +}); + +describe('truncated keys cannot hide a sensitive name', () => { + it('redacts the value of a key too long to keep, instead of shipping it under a key that lost its tail', () => { + const key = `${'x'.repeat(MAX_ATTRIBUTE_JSON_LENGTH)}password`; + const out = safeAnyValue({ [key]: 'longkeysecret', fine: 1 }) as Record; + expect(JSON.stringify(out)).not.toContain('longkeysecret'); + expect(out.fine).toBe(1); + const [cut] = Object.keys(out); + expect(cut).toContain(TRUNCATION_MARKER); + expect(out[cut as string]).toBe(''); + }); + + it('keeps a key exactly at the limit', () => { + const key = 'k'.repeat(MAX_ATTRIBUTE_JSON_LENGTH - 64); + expect(safeAnyValue({ [key]: 'v' })).toEqual({ [key]: 'v' }); + }); +}); + +describe('boundedBase64', () => { + it('encodes small arrays whole and cuts a huge one with the marker', () => { + expect(boundedBase64(new Uint8Array([102, 111, 111]))).toBe('Zm9v'); + const out = boundedBase64(new Uint8Array(1_000_000)); + expect(out.length).toBe(MAX_ATTRIBUTE_JSON_LENGTH); + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + }); +}); + +describe('flattenAttributeValue (the wire form)', () => { + it('leaves scalars and small homogeneous scalar arrays untouched', () => { + const arr = ['a', 'b']; + expect(flattenAttributeValue('s')).toBe('s'); + expect(flattenAttributeValue(3)).toBe(3); + expect(flattenAttributeValue(arr)).toEqual(arr); + }); + + it('turns any remaining complex value into one bounded JSON string', () => { + expect(flattenAttributeValue({ a: { b: 1 } })).toBe('{"a":{"b":1}}'); + expect(flattenAttributeValue([1, 'a'])).toBe('[1,"a"]'); + expect(flattenAttributeValue(new Uint8Array([102, 111, 111]))).toBe('Zm9v'); + const cyc: Record = {}; + cyc.self = cyc; + expect(flattenAttributeValue(cyc)).toBe('{"self":"[Circular]"}'); + expect((flattenAttributeValue({ big: 'x'.repeat(1e6) }) as string).length).toBeLessThanOrEqual( + MAX_ATTRIBUTE_JSON_LENGTH, + ); + }); + + it('drops what has no representation', () => { + expect(flattenAttributeValue(null)).toBeUndefined(); + expect(flattenAttributeValue(() => 1)).toBeUndefined(); + }); +}); + +describe('flattenAttributes', () => { + it('returns the SAME record when nothing needed changing', () => { + const attrs = { a: 'x', n: 1, ok: true }; + expect(flattenAttributes(attrs)).toBe(attrs); + }); + + it('flattens only the complex entries and drops the unrepresentable ones', () => { + const out = flattenAttributes({ a: 'x', o: { k: 1 }, nul: null }); + expect(out).toEqual({ a: 'x', o: '{"k":1}' }); + }); + + it('never throws: an unreadable attribute is dropped, an unlistable record is emptied', () => { + const getter = { + ok: 1, + get boom(): never { + throw new Error('getter'); + }, + }; + expect(flattenAttributes(getter)).toEqual({ ok: 1 }); + const hostile = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + expect(flattenAttributes(hostile)).toEqual({}); + }); +}); diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts new file mode 100644 index 000000000..fe5bd5f24 --- /dev/null +++ b/packages/performance/src/attribute-value.ts @@ -0,0 +1,478 @@ +import { REDACTED, unfinishedSecretStart } from '@bugsee/protocol'; + +// Span attribute values: bounding, safe copying and the wire flattening of complex values. +// +// Context. Before OpenTelemetry API 1.10 an attribute was a string, number, boolean or a homogeneous array of +// those. 1.10 widened `Attributes` to the spec's AnyValue (OTEP 4485): nested maps, arrays of mixed values, +// byte arrays and null. `sdk-trace@3.0.0` keeps all of those on `ReadableSpan.attributes` (and itself drops +// bigint/Date/function/symbol/cyclic values); an older or third-party SDK can hand us anything. The consume +// bridge (`@bugsee/opentelemetry`) runs inside the customer's `span.end()`, so this module is TOTAL (it never +// throws) and BOUNDED in work and in memory, not only in output size. +// +// THE PIPELINE (normalize LATE, flatten at the wire): +// 1. consume `normalizeAttributeValue`: scalars and homogeneous scalar arrays pass through (strings +// capped); everything else becomes a bounded, JSON-safe COPY of the tree (maps stay maps, +// bytes become base64, bigint exact-or-decimal-text). It is NOT stringified here. +// 2. redaction the span filter / default sanitizer sees the TREE, so key-based redaction works on nested +// keys (`user: { password }`, `http.request.headers: { authorization }`). Stringifying first +// would hide those keys inside text the key-based scrub cannot read. +// 3. wire `flattenTransactionAttributes` (run by the performance extension AFTER the filter) turns any +// remaining complex value into one bounded JSON string, because the Bugsee attribute model +// and viewer read scalar attribute values. Produce-direction OTLP therefore sees strings. +// Rejected: flattening to dotted keys (key explosion, no stable form for arrays) and dropping (silent loss of +// exactly the data OTEP 4485 exists to carry). + +/** Longest JSON text kept for one attribute value, in UTF-16 units (the marker included). */ +export const MAX_ATTRIBUTE_JSON_LENGTH = 8192; +/** Deepest container nesting copied; a deeper container is replaced by a marker. */ +export const MAX_ATTRIBUTE_DEPTH = 8; +/** Most values (containers and scalars) visited per attribute before the rest is replaced by a marker. */ +export const MAX_ATTRIBUTE_NODES = 1024; +/** Longest homogeneous scalar array passed through unchanged; a longer one goes the bounded tree route. */ +export const MAX_ATTRIBUTE_ARRAY_LENGTH = 1024; +/** + * Longest scalar string attribute kept, in UTF-16 units. A scalar is passed through otherwise unchanged, but + * an unbounded string would make the cost of `span.end()` proportional to whatever instrumentation recorded + * (a request body, a prompt). 32 KiB keeps ordinary SQL statements and URLs whole. + */ +export const MAX_ATTRIBUTE_STRING_LENGTH = 32768; +/** Most characters of string leaves and keys copied into one tree before the rest is marked truncated. */ +export const MAX_ATTRIBUTE_TREE_CHARS = 32768; +/** Appended when text had to be cut. */ +export const TRUNCATION_MARKER = '...[truncated]'; + +/** Longest single leaf string or key in a tree (leaves a little room for the JSON around it). */ +const MAX_LEAF_LENGTH = MAX_ATTRIBUTE_JSON_LENGTH - 64; + +const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +/** RFC 4648 base64 with padding. Hand-rolled: `btoa`/`Buffer` are runtime-specific and this is portable. */ +export function bytesToBase64(bytes: Uint8Array): string { + let out = ''; + const full = bytes.length - (bytes.length % 3); + for (let i = 0; i < full; i += 3) { + const n = + ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8) | (bytes[i + 2] as number); + out += B64.charAt((n >> 18) & 63) + B64.charAt((n >> 12) & 63); + out += B64.charAt((n >> 6) & 63) + B64.charAt(n & 63); + } + const rest = bytes.length - full; + if (rest === 1) { + const n = (bytes[full] as number) << 16; + out += `${B64.charAt((n >> 18) & 63)}${B64.charAt((n >> 12) & 63)}==`; + } else if (rest === 2) { + const n = ((bytes[full] as number) << 16) | ((bytes[full + 1] as number) << 8); + out += `${B64.charAt((n >> 18) & 63)}${B64.charAt((n >> 12) & 63)}${B64.charAt((n >> 6) & 63)}=`; + } + return out; +} + +/** Enough bytes that their base64 form always exceeds the text cap, so an oversize array is cut and marked. */ +const MAX_BYTES_ENCODED = Math.ceil((MAX_ATTRIBUTE_JSON_LENGTH * 3) / 4) + 3; + +/** + * The bytes of an AnyValue byte array: a `Uint8Array` (a Node `Buffer` is one), plus the other ways an + * instrumentation hands over binary data (`ArrayBuffer`, `DataView`, and a `Uint8Array` from another realm, + * which fails `instanceof` but still has the slot). Other typed arrays are lists of numbers, not bytes. + * Wrapping is O(1) and `boundedBase64` windows the result before encoding, so the work stays bounded. + */ +export function asBytes(value: unknown): Uint8Array | undefined { + if (value instanceof Uint8Array) return value; + if (value instanceof ArrayBuffer) return new Uint8Array(value); + if (value instanceof DataView) { + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + } + if (Object.prototype.toString.call(value) === '[object Uint8Array]') { + return value as Uint8Array; // readable by index; boundedBase64 windows it before encoding + } + return undefined; +} + +/** Characters a secret-shaped token is made of (JWT, `ghp_`, `sk_live_`, AWS keys, base64url). */ +const isTokenChar = (code: number): boolean => + (code >= 48 && code <= 57) || // 0-9 + (code >= 65 && code <= 90) || // A-Z + (code >= 97 && code <= 122) || // a-z + code === 95 || // _ + code === 45 || // - + code === 46 || // . + code === 61 || // = + code === 43 || // + + code === 47; // / + +/** + * Cut `text` to `max` characters, ending with the marker. With `dropPartialToken`, a token the cut lands INSIDE + * is dropped whole: redaction runs after the cap, and a secret shape only matches when complete, so a JWT cut + * after its payload (claims readable) or a `ghp_` token cut at 15 of 36 characters would otherwise ship + * unredacted. A token that ends exactly at the cut is complete and kept. + */ +const capText = (text: string, max: number, dropPartialToken = false): string => { + if (text.length <= max) return text; + let end = max - TRUNCATION_MARKER.length; + if (dropPartialToken && isTokenChar(text.charCodeAt(end))) { + const cut = end; + while (end > 0 && isTokenChar(text.charCodeAt(end - 1))) end--; + // No boundary at all: one long unbroken run (a hash, a URL path, `id_token=`). Keep its prefix, which + // carries the data that matters, but back off before a secret the cut lands INSIDE: a half-written + // secret no longer matches `redactShapes`, so its readable part would ship as is. A secret that is already + // complete in the prefix (a JWT cut inside its signature) is left for redaction, which matches it whole. + if (end === 0) { + const start = unfinishedSecretStart(text.slice(0, cut)); + end = start === -1 ? cut : start; + } + } + return text.slice(0, end) + TRUNCATION_MARKER; +}; + +/** Base64 of a byte array, bounded in work (encodes at most what could fit) and in length. */ +export function boundedBase64(bytes: Uint8Array): string { + const head = bytes.length > MAX_BYTES_ENCODED ? bytes.subarray(0, MAX_BYTES_ENCODED) : bytes; + return capText(bytesToBase64(head), MAX_ATTRIBUTE_JSON_LENGTH); +} + +const SKIP = Symbol('skip'); + +/** + * Limits shared by ALL the attributes of one span. Each attribute has its own node and character budget, but a + * span can carry 128 of them, so without a span-level cap the work of one `span.end()` was 128 x the + * per-attribute bound (measured: 128 attributes of 1024-node maps cost 1.2 s in the redaction step). + */ +export const MAX_SPAN_ATTRIBUTE_NODES = 4096; +export const MAX_SPAN_ATTRIBUTE_CHARS = 65536; + +/** A running total across the attributes of one span. */ +export interface SpanBudget { + nodes: number; + chars: number; +} + +/** A fresh span-level budget (one per span, root and children each get their own). */ +export const createSpanBudget = (): SpanBudget => ({ nodes: 0, chars: 0 }); + +/** A bigint as JSON can carry it: a number when exact, decimal text beyond the safe range. */ +const bigintToJson = (value: bigint): number | string => + value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) + ? Number(value) + : value.toString(); + +const UrlClass = (): + | (new ( + input: string, + ) => { href: string; username: string; password: string }) + | undefined => + ( + globalThis as unknown as { + URL?: new (input: string) => { href: string; username: string; password: string }; + } + ).URL; + +interface Budget { + nodes: number; + chars: number; + span?: SpanBudget; +} + +const exhausted = (budget: Budget): boolean => + budget.nodes >= MAX_ATTRIBUTE_NODES || + budget.chars >= MAX_ATTRIBUTE_TREE_CHARS || + (budget.span !== undefined && + (budget.span.nodes >= MAX_SPAN_ATTRIBUTE_NODES || + budget.span.chars >= MAX_SPAN_ATTRIBUTE_CHARS)); + +const countNode = (budget: Budget): void => { + budget.nodes++; + if (budget.span !== undefined) budget.span.nodes++; +}; + +const setOwn = (target: Record, key: string, value: unknown): void => { + // `target[key] = v` with key "__proto__" rewrites the prototype instead of adding a key. + Object.defineProperty(target, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); +}; + +/** A string leaf or key, cut at the leaf cap and counted against the tree's character budget. */ +function leafText(text: string, budget: Budget, dropPartialToken = true): string { + const cut = capText(text, MAX_LEAF_LENGTH, dropPartialToken); + budget.chars += cut.length; + if (budget.span !== undefined) budget.span.chars += cut.length; + return cut; +} + +/** Copy a value into a tree containing only JSON-safe values, within the depth/node/character budget. */ +function toSafe(value: unknown, depth: number, budget: Budget, ancestors: Set): unknown { + if (value === null) return null; + switch (typeof value) { + case 'string': + return leafText(value, budget); + case 'boolean': + return value; + case 'number': + if (Number.isFinite(value)) return value; + return Number.isNaN(value) ? 'NaN' : value > 0 ? 'Infinity' : '-Infinity'; + case 'bigint': + return bigintToJson(value); + case 'object': + break; + default: + return SKIP; // undefined, function, symbol + } + const bytes = asBytes(value); + if (bytes !== undefined) return leafText(boundedBase64(bytes), budget, false); + if (value instanceof Date) { + const time = value.getTime(); + return Number.isNaN(time) ? null : new Date(time).toISOString(); + } + // A URL used to export its href (through toJSON); keep that, minus any credentials in the authority. + const Url = UrlClass(); + if (Url !== undefined && value instanceof Url) { + const bare = new Url(value.href); + bare.username = ''; + bare.password = ''; + return leafText(bare.href, budget); + } + // An Error has no enumerable own properties; name and message are what identify it (never the stack). + if (value instanceof Error) { + const out: Record = {}; + setOwn(out, 'name', leafText(String(value.name), budget)); + setOwn(out, 'message', leafText(String(value.message), budget)); + return out; + } + if (depth >= MAX_ATTRIBUTE_DEPTH) return '[MaxDepth]'; + if (exhausted(budget)) return '[Truncated]'; + if (ancestors.has(value)) return '[Circular]'; + ancestors.add(value); + try { + // A typed array that is not a byte array (Float32Array embeddings, ...) is a list of numbers; reading it + // by index is bounded by the node budget, where Object.keys would allocate every index string. + if (Array.isArray(value) || ArrayBuffer.isView(value)) { + return listToSafe(value as ArrayLike, depth, budget, ancestors); + } + return objectToSafe(value as Record, depth, budget, ancestors); + } catch { + return '[Unreadable]'; + } finally { + ancestors.delete(value); + } +} + +function listToSafe( + items: ArrayLike, + depth: number, + budget: Budget, + ancestors: Set, +): unknown[] { + const out: unknown[] = []; + countNode(budget); + for (let i = 0; i < items.length; i++) { + if (exhausted(budget)) { + out.push('[Truncated]'); + break; + } + countNode(budget); + let item: unknown; + try { + item = toSafe(items[i], depth + 1, budget, ancestors); + } catch { + item = '[Unreadable]'; + } + out.push(item === SKIP ? null : item); + } + return out; +} + +function objectToSafe( + source: Record, + depth: number, + budget: Budget, + ancestors: Set, +): Record { + const out: Record = {}; + countNode(budget); + for (const key of Object.keys(source)) { + if (exhausted(budget)) { + setOwn(out, '[Truncated]', true); + break; + } + countNode(budget); + let member: unknown; + if (key.length > MAX_LEAF_LENGTH) { + // The key is cut below, and a cut can remove the very word (`password`) a key-based redaction looks + // for. A key this long is not a real field name: keep neither its tail nor its value. + member = REDACTED; + } else { + try { + member = toSafe(source[key], depth + 1, budget, ancestors); + } catch { + member = '[Unreadable]'; + } + } + if (member !== SKIP) setOwn(out, leafText(key, budget), member); + } + return out; +} + +/** + * A bounded, JSON-safe COPY of an AnyValue, or `undefined` when it has no representation at all + * (undefined/function/symbol). Never throws; never follows a cycle; bytes become base64, bigint decimal text, + * non-finite numbers the OTLP spellings, `toJSON` and other user code is never called. + */ +export function safeAnyValue(value: unknown, span?: SpanBudget): unknown { + let safe: unknown; + try { + safe = toSafe( + value, + 0, + { nodes: 0, chars: 0, ...(span !== undefined ? { span } : {}) }, + new Set(), + ); + } catch { + safe = '[Unreadable]'; + } + return safe === SKIP ? undefined : safe; +} + +/** + * The JSON text of an AnyValue, bounded and never throwing (see {@link safeAnyValue}). Returns `undefined` + * when the value has no JSON form at all. + */ +export function stringifyAnyValue(value: unknown): string | undefined { + try { + const safe = safeAnyValue(value); + return safe === undefined + ? undefined + : capText(JSON.stringify(safe), MAX_ATTRIBUTE_JSON_LENGTH); + } catch { + return capText('"[Unreadable]"', MAX_ATTRIBUTE_JSON_LENGTH); + } +} + +const isScalar = (v: unknown): v is string | number | boolean => + typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'; + +/** + * A COPY of an array whose non-null elements are all strings, all numbers or all booleans (the pre-1.10 + * shape) and which is small, else `undefined`. Read by INDEX, once per element: an overridden + * `Symbol.iterator` cannot hide an element from the check, a getter cannot answer differently later, and the + * result does not alias the caller's array (a later `push({ password })` must not reach the store). + */ +function scalarArrayCopy(value: unknown[]): unknown[] | undefined { + // `length` is read ONCE: a Proxy (or an array being appended to) can answer differently every time, which + // would walk past the limit that was just checked. + const length = value.length; + if (length > MAX_ATTRIBUTE_ARRAY_LENGTH) return undefined; + const copy: unknown[] = []; + let kind: string | undefined; + let chars = 0; + for (let i = 0; i < length; i++) { + const item = value[i]; + copy.push(item); + // OTel 2/3 keep null/undefined entries in a homogeneous array (`['a', null, 'b']`); they pass through. + if (item === null || item === undefined) continue; + if (!isScalar(item)) return undefined; + kind ??= typeof item; + if (typeof item !== kind) return undefined; + if (typeof item === 'string') { + chars += item.length; + if (chars > MAX_ATTRIBUTE_STRING_LENGTH) return undefined; + } + } + return copy; +} + +const isPassThroughArray = (value: unknown[]): boolean => scalarArrayCopy(value) !== undefined; + +/** + * Normalize one OTel attribute value for the Bugsee attribute model (the pipeline at the top of this file). + * Scalars pass through (a string is capped at {@link MAX_ATTRIBUTE_STRING_LENGTH}; a bigint becomes a number + * when exact, decimal text otherwise); a small homogeneous scalar array passes through; a byte array becomes + * base64; everything else becomes a bounded JSON-safe tree. `undefined` means no representation: the + * attribute is dropped. + */ +export function normalizeAttributeValue(value: unknown, span?: SpanBudget): unknown { + if (value === null || value === undefined) return undefined; + // Only CUT: a top-level string is never shape-scanned, so dropping its unfinished token protects nothing. + if (typeof value === 'string') return capText(value, MAX_ATTRIBUTE_STRING_LENGTH); + if (typeof value === 'number' || typeof value === 'boolean') return value; + if (typeof value === 'bigint') return bigintToJson(value); + const bytes = asBytes(value); + if (bytes !== undefined) return boundedBase64(bytes); + if (Array.isArray(value)) { + const copy = scalarArrayCopy(value); + if (copy !== undefined) return copy; + } + const safe = safeAnyValue(value, span); + return safe === null ? undefined : safe; // an invalid Date: no value +} + +/** + * Normalize an attributes record: own enumerable string keys only, each value normalized. One attribute that + * cannot be read (a throwing getter) is skipped without losing its siblings, and a record whose keys cannot + * be listed (a Proxy with a throwing `ownKeys`) yields no attributes rather than throwing. + */ +export function normalizeAttributes( + attributes: Record, + span: SpanBudget = createSpanBudget(), +): Record { + const out: Record = {}; + let keys: string[]; + try { + keys = Object.keys(attributes); + } catch { + return out; + } + for (const key of keys) { + try { + const value = normalizeAttributeValue(attributes[key], span); + if (value !== undefined) setOwn(out, key, value); + } catch { + // unreadable attribute: skip it, keep the rest + } + } + return out; +} + +/** + * The wire form of one attribute value: scalars and small homogeneous scalar arrays unchanged, anything else + * one bounded JSON string. Total: never throws. `undefined` = drop the attribute. + */ +export function flattenAttributeValue(value: unknown, span?: SpanBudget): unknown { + if (Array.isArray(value)) { + // A custom span filter may have set an array it still holds: copy, never hand the same one on. + const copy = scalarArrayCopy(value); + if (copy !== undefined) return copy; + } + const normal = normalizeAttributeValue(value, span); + if (normal === null || typeof normal !== 'object') return normal; + return Array.isArray(normal) && isPassThroughArray(normal) ? normal : stringifyAnyValue(normal); +} + +/** + * Flatten an attributes record for the wire. Returns the SAME record only when every value is already a scalar; + * an array value is always copied (see {@link flattenAttributeValue}), so a record with one is a new record. + */ +export function flattenAttributes(attributes: Record): Record { + const span = createSpanBudget(); + let changed = false; + const out: Record = {}; + let keys: string[]; + try { + keys = Object.keys(attributes); + } catch { + return {}; + } + for (const key of keys) { + try { + const raw = attributes[key]; + const flat = flattenAttributeValue(raw, span); + if (flat !== raw) changed = true; + if (flat !== undefined) setOwn(out, key, flat); + } catch { + changed = true; // unreadable attribute: dropped + } + } + return changed ? out : attributes; +} diff --git a/packages/performance/src/extension.test.ts b/packages/performance/src/extension.test.ts index 8572475e5..42fca56b7 100644 --- a/packages/performance/src/extension.test.ts +++ b/packages/performance/src/extension.test.ts @@ -270,6 +270,228 @@ describe('createPerformanceExtension — the span filter reaches CONSUMED spans' }); }); +describe('createPerformanceExtension — nested (AnyValue) attributes: redact as a tree, then flatten', () => { + const external = (attributes: Record) => ({ + traceId: 't', + spanId: 's', + name: 'req', + operation: 'http', + status: 'OK' as const, + sampled: true, + startTimestampMs: 1, + endTimestampMs: 2, + isSnapshot: false, + attributes, + spans: [], + }); + + it('redacts nested sensitive keys by DEFAULT and only then stringifies, in both sinks', () => { + const { client, captured } = fakeClient(createFilterStore(() => {})); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + extension.recordExternal( + external({ + user: { name: 'ann', password: 'hunter2', authorization: 'Bearer abc' }, + 'http.request.headers': { cookie: 'sid=1', accept: 'x' }, + }), + ); + const stored = extension.store.drain()[0]?.attributes as Record; + expect(JSON.parse(stored.user as string)).toEqual({ + name: 'ann', + password: '', + authorization: '', + }); + expect(JSON.parse(stored['http.request.headers'] as string)).toEqual({ + cookie: '', + accept: 'x', + }); + for (const sink of [JSON.stringify(stored), JSON.stringify(captured)]) { + expect(sink).not.toContain('hunter2'); + expect(sink).not.toContain('Bearer abc'); + expect(sink).not.toContain('sid=1'); + } + }); + + it('hands an integrator span filter the TREE, and still flattens whatever it returns', () => { + const filters = createFilterStore(() => {}); + let seen: unknown; + filters.span = (span) => { + seen = span.attributes?.ctx; + return span; + }; + const { client } = fakeClient(filters); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + extension.recordExternal(external({ ctx: { a: { b: 1 } } })); + expect(seen).toEqual({ a: { b: 1 } }); + expect(extension.store.drain()[0]?.attributes?.ctx).toBe('{"a":{"b":1}}'); + }); + + it('flattens before the sinks even when the sanitizer is switched off', () => { + const { client } = fakeClient(createFilterStore(() => {})); + const extension = createPerformanceExtension({ sanitizeSpans: false }); + extension.setup(client as unknown as BugseeClient); + extension.recordExternal(external({ ctx: { k: [1, 'a'] } })); + expect(extension.store.drain()[0]?.attributes?.ctx).toBe('{"k":[1,"a"]}'); + }); +}); + +describe("createPerformanceExtension — raw attribute values on the SDK's own spans are bounded too", () => { + const dag = (levels: number, fanout: number): unknown => { + let node: unknown = { leaf: 'v' }; + for (let i = 0; i < levels; i++) { + const level: Record = {}; + for (let j = 0; j < fanout; j++) level[`k${j}`] = node; + node = level; + } + return node; + }; + const hostile = () => { + const cyc: Record = { password: 'hunter2' }; + for (let j = 0; j < 3; j++) cyc[`k${j}`] = cyc; + return { + dag: dag(14, 3), + cyc, + thrower: { + ok: 1, + get boom(): never { + throw new Error('getter'); + }, + }, + }; + }; + + it('setAttribute with a DAG, a cycle and a throwing getter finishes fast and keeps the transaction', () => { + const { client, ext, captured } = fakeClient(createFilterStore(() => {})); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + const txn = ext().startTransaction({ name: 'T', operation: 'op' }); + for (const [k, v] of Object.entries(hostile())) txn.setAttribute(k, v); + const started = Date.now(); + txn.finish('OK'); + expect(Date.now() - started).toBeLessThan(2000); + const stored = extension.store.drain(); + expect(stored).toHaveLength(1); + const attrs = stored[0]?.attributes as Record; + expect(typeof attrs.dag).toBe('string'); + expect(attrs.cyc).toContain('[Circular]'); + expect(attrs.cyc).not.toContain('hunter2'); + expect(attrs.thrower).toContain('[Unreadable]'); + expect(JSON.stringify(captured)).not.toContain('hunter2'); + }); + + it('a 20 MB byte array set natively becomes a bounded base64 string, not a 3 GB walk', () => { + const { client, ext } = fakeClient(createFilterStore(() => {})); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + const started = Date.now(); + ext() + .startTransaction({ name: 'T', operation: 'op' }) + .setAttribute('buf', new Uint8Array(20 * 1024 * 1024)) + .setAttribute( + 'wide', + Object.fromEntries(Array.from({ length: 100_000 }, (_, i) => [`k${i}`, i])), + ) + .finish('OK'); + expect(Date.now() - started).toBeLessThan(2000); + const attrs = extension.store.drain()[0]?.attributes as Record; + expect(attrs.buf?.length).toBeLessThanOrEqual(8192); + expect(attrs.wide?.length).toBeLessThanOrEqual(8192); + }); + + it('recordExternal and recordChildSpan-style raw attributes get the same treatment', () => { + const { client } = fakeClient(createFilterStore(() => {})); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + const raw = hostile(); + extension.recordExternal({ + ...externalWire(), + attributes: raw, + spans: [ + { + spanId: 'c', + operation: 'child', + status: 'OK', + startTimestampMs: 1, + attributes: { cyc: raw.cyc }, + }, + ], + }); + const stored = extension.store.drain()[0]; + expect(stored?.attributes?.thrower).toContain('[Unreadable]'); + expect(stored?.spans[0]?.attributes?.cyc).not.toContain('hunter2'); + }); + + it('hands an integrator span filter a TREE even for a raw SDK value', () => { + const filters = createFilterStore(() => {}); + let seen: unknown; + filters.span = (span) => { + seen = span.attributes?.ctx; + return span; + }; + const { client, ext } = fakeClient(filters); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + const cyc: Record = { a: 1 }; + cyc.self = cyc; + ext().startTransaction({ name: 'T', operation: 'op' }).setAttribute('ctx', cyc).finish('OK'); + expect(seen).toEqual({ a: 1, self: '[Circular]' }); + }); +}); + +describe('createPerformanceExtension — a statement CUT by a length cap still has its literals redacted', () => { + const doc = Array.from( + { length: 4000 }, + (_, i) => `patient${i}@clinic.example;hypertension`, + ).join('\n'); + const sql = `INSERT INTO records (doc) VALUES ('${doc}')`; + const leaked = (value: unknown): number => + (JSON.stringify(value).match(/@clinic\.example/g) ?? []).length; + const run = (attributes: Record, viaSdk = false) => { + const { client, ext } = fakeClient(createFilterStore(() => {})); + const extension = createPerformanceExtension(); + extension.setup(client as unknown as BugseeClient); + if (viaSdk) { + const txn = ext().startTransaction({ name: 'T', operation: 'op' }); + for (const [k, v] of Object.entries(attributes)) txn.setAttribute(k, v); + txn.finish('OK'); + } else { + extension.recordExternal({ + traceId: 't', + spanId: 's', + name: 'q', + operation: 'db', + status: 'OK', + sampled: true, + startTimestampMs: 1, + endTimestampMs: 2, + isSnapshot: false, + attributes, + spans: [], + }); + } + return extension.store.drain()[0]?.attributes as Record; + }; + + it('scalar statement, recordExternal path', () => { + expect(sql.length).toBeGreaterThan(100_000); + expect(leaked(run({ 'db.statement': sql }))).toBe(0); + }); + + it('scalar statement, SDK setAttribute path', () => { + expect(leaked(run({ 'db.statement': sql }, true))).toBe(0); + }); + + it('statement carried in a map, and db.query.text as an array', () => { + const out = run({ 'db.statement': { text: sql }, 'db.query.text': [sql, sql] }); + expect(leaked(out)).toBe(0); + }); + + it('a nested map under a non-statement key that holds a statement-keyed member', () => { + expect(leaked(run({ wrapper: { 'db.statement': sql } }))).toBe(0); + }); +}); + // `sanitizeSpans?? true` let `0`, `''`, `'false'` (anything not nullish) DISABLE the built-in span // sanitizer. It PROTECTS, so an invalid value keeps it ON and is reported; only boolean `false` opts out. describe('createPerformanceExtension — sanitizeSpans is fail-on', () => { diff --git a/packages/performance/src/extension.ts b/packages/performance/src/extension.ts index 7c6651dac..d49d45ed3 100644 --- a/packages/performance/src/extension.ts +++ b/packages/performance/src/extension.ts @@ -14,6 +14,10 @@ import { createPerformanceController, type PerformanceApi } from './controller'; import { stampDeviceIdOnWire } from './device-id-attribute'; import type { TransactionWire } from './span'; import { applySpanFilter } from './span-filter'; +import { + flattenTransactionAttributes, + normalizeTransactionAttributes, +} from './transaction-attributes'; import { createTransactionStore, type TransactionStore } from './transaction-store'; // The @bugsee/performance extension shell. There is no addExtension lifecycle on the @@ -113,13 +117,19 @@ export function createPerformanceExtension( options.deviceId === undefined ? transaction : stampDeviceIdOnWire(transaction, options.deviceId); - const filterTransaction = (transaction: TransactionWire): TransactionWire | null => - applySpanFilter( - stampDeviceId(transaction), + const filterTransaction = (transaction: TransactionWire): TransactionWire | null => { + const filtered = applySpanFilter( + // Bound every attribute FIRST (raw values on the SDK's own spans too), so the redaction walk and any + // integrator filter only ever see a bounded, cycle-free tree. + stampDeviceId(normalizeTransactionAttributes(transaction)), filters?.span ?? null, (error) => filters?.onError(error), sanitizeSpans, ); + // Redaction saw nested attributes as TREES; whatever survives is flattened to scalars / bounded JSON + // strings here, the wire boundary, because the attribute model downstream reads scalar values. + return filtered === null ? null : flattenTransactionAttributes(filtered); + }; return { name: 'performance', store, diff --git a/packages/performance/src/index.ts b/packages/performance/src/index.ts index 7a83d2642..d577450c3 100644 --- a/packages/performance/src/index.ts +++ b/packages/performance/src/index.ts @@ -7,6 +7,21 @@ // the umbrella `bugsee` package auto-registers it (passive web-vitals on by default, span API opt-in). export { type ActiveSpanStore, createSingleSlotActiveSpanStore } from './active-span-store'; +export { + asBytes, + boundedBase64, + flattenAttributes, + MAX_ATTRIBUTE_ARRAY_LENGTH, + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + MAX_ATTRIBUTE_NODES, + MAX_ATTRIBUTE_STRING_LENGTH, + normalizeAttributes, + normalizeAttributeValue, + safeAnyValue, + stringifyAnyValue, + TRUNCATION_MARKER, +} from './attribute-value'; export { createPerformanceController, NAME_SOURCE_ATTRIBUTE, diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index a7d7933d8..f6efb0a41 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -113,3 +113,138 @@ describe('sanitizeSpan', () => { expect(sanitizeSpan(input).attributes?.['db.statement']).toBe(42); }); }); + +describe('sanitizeSpan on nested (AnyValue) attributes', () => { + // OTel API 1.10 lets an attribute be a map. The key-based rule must see INTO it: `user.password` is + // redacted as a flat key, so `user: { password }` has to be redacted too. + it('redacts sensitive keys inside a nested map, keeping the rest', () => { + const out = sanitizeSpan( + span({ user: { name: 'ann', password: 'hunter2', authorization: 'Bearer abc' } }), + ); + expect(out.attributes?.user).toEqual({ + name: 'ann', + password: REDACTED, + authorization: REDACTED, + }); + }); + + it('redacts header maps and keys at any depth, including inside arrays', () => { + const out = sanitizeSpan( + span({ + 'http.request.headers': { authorization: 'Bearer abc', cookie: 'sid=1', accept: 'x' }, + calls: [{ meta: { token: 't', ok: 1 } }], + }), + ); + expect(out.attributes?.['http.request.headers']).toEqual({ + authorization: REDACTED, + cookie: REDACTED, + accept: 'x', + }); + expect(out.attributes?.calls).toEqual([{ meta: { token: REDACTED, ok: 1 } }]); + }); + + it('applies the content-key and statement rules to nested keys', () => { + const out = sanitizeSpan( + span({ + payload: { + 'http.request.body': 'secret body', + 'db.statement': "SELECT * FROM users WHERE email = 'a@b.com'", + }, + }), + ); + expect(out.attributes?.payload).toEqual({ + 'http.request.body': REDACTED, + 'db.statement': 'SELECT * FROM users WHERE email = ?', + }); + }); + + it('scans nested string leaves for secret shapes', () => { + const out = sanitizeSpan(span({ ctx: { note: 'key AKIAIOSFODNN7EXAMPLE end' } })); + expect(JSON.stringify(out.attributes?.ctx)).not.toContain('AKIAIOSFODNN7EXAMPLE'); + }); + + it('is bounded: a tree deeper than the walk limit is redacted whole, never recursed into', () => { + let deep: unknown = { password: 'p' }; + for (let i = 0; i < 5000; i++) deep = { n: deep }; + const out = sanitizeSpan(span({ deep })); + expect(JSON.stringify(out.attributes?.deep)).not.toContain('"p"'); + expect(JSON.stringify(out.attributes?.deep)).toContain(REDACTED); + }); + + it('returns the SAME span when a nested value needs no change', () => { + const attrs = { ctx: { a: 1, b: ['x'] }, flat: 'ok' }; + const input = span(attrs); + expect(sanitizeSpan(input)).toBe(input); + }); + + it('leaves null-prototype maps and non-plain leaves alone', () => { + const map = Object.assign(Object.create(null) as Record, { + k: 1, + password: 'p', + }); + const out = sanitizeSpan(span({ map })); + expect(out.attributes?.map).toEqual({ k: 1, password: REDACTED }); + }); +}); + +describe('sanitizeSpan: current GenAI content conventions', () => { + it.each([ + 'gen_ai.input.messages', + 'gen_ai.output.messages', + 'gen_ai.system_instructions', + 'gen_ai.tool.definitions', + 'gen_ai.tool.call.arguments', + 'gen_ai.tool.call.result', + ])('redacts %s by default, flat and nested', (key) => { + const flat = sanitizeSpan(span({ [key]: [{ role: 'user', parts: [{ content: 'secret' }] }] })); + expect(flat.attributes?.[key]).toBe(REDACTED); + const nested = sanitizeSpan(span({ wrapper: { [key]: 'secret prompt' } })); + expect(nested.attributes?.wrapper).toEqual({ [key]: REDACTED }); + }); +}); + +describe('sanitizeSpan: a statement key whose value is not a plain string', () => { + const SQL = "SELECT * FROM users WHERE email = 'a@b.com' AND id = 42"; + const SHAPE = 'SELECT * FROM users WHERE email = ? AND id = ?'; + + it('redacts the literals in string leaves under a statement key (map, array, nested)', () => { + const out = sanitizeSpan( + span({ + 'db.statement': { text: SQL, rows: 3 }, + 'db.query.text': [SQL, SQL], + wrapper: { 'db.statement': { inner: SQL } }, + }), + ); + const attrs = out.attributes as Record; + expect(attrs['db.statement']).toEqual({ text: SHAPE, rows: 3 }); + expect(attrs['db.query.text']).toEqual([SHAPE, SHAPE]); + expect(attrs.wrapper).toEqual({ 'db.statement': { inner: SHAPE } }); + expect(JSON.stringify(out.attributes)).not.toContain('a@b.com'); + }); + + it('still returns the same span for a statement-keyed value that has nothing to redact', () => { + const input = span({ 'db.statement': ['SELECT x FROM t'] }); + expect(sanitizeSpan(input)).toBe(input); + }); +}); + +describe('redactSqlLiterals on a statement that was CUT inside a literal', () => { + // Length caps run before redaction, so a long INSERT is cut mid-string. A closed-quote match alone would + // leave the open literal (and everything after its opening quote) in the clear. + it('replaces an unterminated trailing literal', () => { + expect(redactSqlLiterals("INSERT INTO t (doc) VALUES ('patient1@x.example;secret")).toBe( + 'INSERT INTO t (doc) VALUES (?', + ); + expect(redactSqlLiterals('SELECT "col FROM t')).toBe('SELECT ?'); + }); + + it('handles closed literals followed by an unterminated one, and a doubled quote before the cut', () => { + expect(redactSqlLiterals("a = 'x' AND b = 'cd")).toBe('a = ? AND b = ?'); + // `'it'` closes at the first quote and `'s a sec` is the open tail: both are data, both go. + expect(redactSqlLiterals("a = 'it''s a sec")).toBe('a = ??'); + }); + + it('leaves a statement without any quote alone', () => { + expect(redactSqlLiterals('SELECT x FROM t')).toBe('SELECT x FROM t'); + }); +}); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index a92d869c1..d35befeb6 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -1,5 +1,5 @@ import type { FilterableSpan } from '@bugsee/core'; -import { isSensitiveKey, REDACTED } from '@bugsee/protocol'; +import { isSensitiveKey, REDACTED, redactShapes } from '@bugsee/protocol'; // The BUILT-IN span sanitizer, applied to every span unless the integrator installs their own filter // (the same XOR the network sanitizer follows: a user filter REPLACES the default rather than layering). @@ -18,6 +18,14 @@ const CONTENT_KEYS = new Set([ 'gen_ai.response.messages', 'gen_ai.content.prompt', 'gen_ai.content.completion', + // The current GenAI semantic conventions: structured (array-of-message) content, the main reason + // complex attributes exist at all. + 'gen_ai.input.messages', + 'gen_ai.output.messages', + 'gen_ai.system_instructions', + 'gen_ai.tool.definitions', + 'gen_ai.tool.call.arguments', + 'gen_ai.tool.call.result', 'http.request.body', 'http.response.body', 'graphql.document', @@ -42,6 +50,11 @@ export function redactSqlLiterals(statement: string): string { // '...' with '' escapes, and "..." with "" escapes .replace(/'(?:[^']|'')*'/g, '?') .replace(/"(?:[^"]|"")*"/g, '?') + // A literal still OPEN at the end: the statement was cut by a length cap (which runs before this), and + // everything after the opening quote is literal data. (After the closed passes at most one lone quote is + // left, so no doubled-quote alternative is needed here.) + .replace(/'[^']*$/, '?') + .replace(/"[^"]*$/, '?') // numeric literals, but never the digits inside an identifier like `column2` .replace(/\b\d+(?:\.\d+)?\b/g, '?') ); @@ -50,6 +63,10 @@ export function redactSqlLiterals(statement: string): string { /** * Scrub one span's attributes. Returns the SAME span when nothing needed changing, so the common case — * an SDK-produced span with no such attributes — copies nothing. + * + * Assumes BOUNDED input: nested values are walked with only a depth limit, so a raw cyclic or branching + * object would not finish. The performance extension runs `normalizeTransactionAttributes` on every + * transaction first; a direct caller must do the same. */ export function sanitizeSpan(span: FilterableSpan): FilterableSpan { const attributes = span.attributes; @@ -68,10 +85,72 @@ export function sanitizeSpan(span: FilterableSpan): FilterableSpan { return changed ? { ...span, attributes: out } : span; } +/** How deep the nested walk goes; below it the subtree is redacted whole rather than recursed into. */ +const MAX_WALK_DEPTH = 16; + +/** Does this value need the nested walk (a map, or an array holding something other than scalars)? */ +const isComplex = (value: unknown): boolean => + value !== null && + typeof value === 'object' && + !(Array.isArray(value) && value.every((item) => item === null || typeof item !== 'object')); + +/** + * The same rules as the flat path, applied to a NESTED (OpenTelemetry API 1.10 `AnyValue`) attribute: a + * sensitive key redacts its whole value at any depth, content keys redact, statement keys keep their shape, + * and string leaves are scanned for secret shapes. Returns the SAME value when nothing changed. + * + * Why this exists: `user: { password }` and `http.request.headers: { authorization }` carry exactly the data + * the flat keys `user.password` / `http.request.headers.authorization` are redacted for, and a rule that only + * looked at the top-level key would let them through verbatim. + */ +function sanitizeNested(value: unknown, depth: number, statement = false): unknown { + if (typeof value === 'string') { + // Under a statement key every string leaf is SQL: keep its shape, lose its literals. + return redactShapes(statement ? redactSqlLiterals(value) : value); + } + if (value === null || typeof value !== 'object') { + return value; + } + if (depth >= MAX_WALK_DEPTH) { + return REDACTED; + } + if (Array.isArray(value)) { + let changed = false; + const items = value.map((item) => { + const next = sanitizeNested(item, depth + 1, statement); + if (next !== item) changed = true; + return next; + }); + return changed ? items : value; + } + let changed = false; + const out: Record = Object.create(null); + for (const [key, member] of Object.entries(value)) { + const next = sanitizeMember(key, member, depth, statement); + if (next !== member) changed = true; + out[key] = next; + } + return changed ? out : value; +} + +function sanitizeMember(key: string, value: unknown, depth: number, statement: boolean): unknown { + if (STATEMENT_KEYS.has(key)) { + return typeof value === 'string' + ? redactSqlLiterals(value) + : sanitizeNested(value, depth + 1, true); + } + if (CONTENT_KEYS.has(key) || isSensitiveKey(key)) { + return REDACTED; + } + return sanitizeNested(value, depth + 1, statement); +} + function sanitizeAttribute(key: string, value: unknown): unknown { // A statement keeps its SHAPE — that is what makes it worth reporting at all — while losing its data. - if (STATEMENT_KEYS.has(key) && typeof value === 'string') { - return redactSqlLiterals(value); + if (STATEMENT_KEYS.has(key)) { + if (typeof value === 'string') return redactSqlLiterals(value); + // A statement carried as a map or an array: every string leaf under it is SQL. + return isComplex(value) || Array.isArray(value) ? sanitizeNested(value, 0, true) : value; } // Free-form content: there is no shape worth keeping, and a prompt is as sensitive as a password. if (CONTENT_KEYS.has(key)) { @@ -85,5 +164,9 @@ function sanitizeAttribute(key: string, value: unknown): unknown { // substring of the key, so it can never match when the key does not. It also called // `isSensitiveInput({ name: leaf })`, which is a DOM-ELEMENT predicate reading `type` and `matches`: // handed a plain object it returns false for every input, always. A mutation run found both. - return isSensitiveKey(key) ? REDACTED : value; + if (isSensitiveKey(key)) { + return REDACTED; + } + // A nested value gets the same rules on ITS keys (see sanitizeNested). + return isComplex(value) ? sanitizeNested(value, 0) : value; } diff --git a/packages/performance/src/transaction-attributes.test.ts b/packages/performance/src/transaction-attributes.test.ts new file mode 100644 index 000000000..8e75567aa --- /dev/null +++ b/packages/performance/src/transaction-attributes.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest'; +import type { TransactionWire } from './span'; +import { + flattenTransactionAttributes, + normalizeTransactionAttributes, +} from './transaction-attributes'; + +const txn = (over: Partial = {}): TransactionWire => ({ + traceId: 't'.repeat(32), + spanId: 'r'.repeat(16), + name: 'root', + operation: 'op', + status: 'OK', + sampled: true, + startTimestampMs: 1, + isSnapshot: false, + spans: [], + ...over, +}); + +const child = (attributes?: Record): TransactionWire['spans'][number] => ({ + spanId: 'c'.repeat(16), + operation: 'child', + status: 'OK', + startTimestampMs: 1, + ...(attributes !== undefined ? { attributes } : {}), +}); + +describe('flattenTransactionAttributes', () => { + it('returns a NEW record (equal content) when an attribute is an array: arrays are always copied', () => { + const input = txn({ attributes: { tags: ['x'] }, spans: [child({ list: ['a', 'b'] })] }); + const out = flattenTransactionAttributes(input); + expect(out).toEqual(input); + expect(out.attributes?.tags === input.attributes?.tags).toBe(false); + expect(out.spans[0]?.attributes?.list === input.spans[0]?.attributes?.list).toBe(false); + }); + + it('returns the SAME transaction when no attribute is complex (the common path copies nothing)', () => { + const plain = txn({ attributes: { a: 1, ok: true }, spans: [child({ b: 'y' }), child()] }); + expect(flattenTransactionAttributes(plain)).toBe(plain); + const bare = txn(); + expect(flattenTransactionAttributes(bare)).toBe(bare); + }); + + it('flattens complex attributes on the root and on every child, leaving the rest untouched', () => { + const input = txn({ + attributes: { keep: 1, map: { a: { b: 1 } } }, + spans: [child({ list: [1, 'a'] }), child({ ok: true })], + }); + const out = flattenTransactionAttributes(input); + expect(out).not.toBe(input); + expect(out.attributes).toEqual({ keep: 1, map: '{"a":{"b":1}}' }); + expect(out.spans[0]?.attributes).toEqual({ list: '[1,"a"]' }); + expect(out.spans[1]).toBe(input.spans[1]); // untouched child kept by reference + expect(input.attributes?.map).toEqual({ a: { b: 1 } }); // the input is not mutated + }); + + it('copies only what changed: an unchanged root keeps its attributes reference', () => { + const rootAttrs = { a: 1 }; + const input = txn({ attributes: rootAttrs, spans: [child({ m: { k: 1 } })] }); + const out = flattenTransactionAttributes(input); + expect(out.attributes).toBe(rootAttrs); + expect(out.spans[0]?.attributes).toEqual({ m: '{"k":1}' }); + }); +}); + +const dag = (levels: number, fanout: number): unknown => { + let node: unknown = { leaf: 'v' }; + for (let i = 0; i < levels; i++) { + const level: Record = {}; + for (let j = 0; j < fanout; j++) level[`k${j}`] = node; + node = level; + } + return node; +}; + +describe('normalizeTransactionAttributes (SDK-produced spans carry RAW values too)', () => { + it('returns an equal transaction when every attribute is already a scalar or scalar array', () => { + const plain = txn({ attributes: { a: 1, tags: ['x'] }, spans: [child({ b: 'y' }), child()] }); + expect(normalizeTransactionAttributes(plain)).toEqual(plain); + const bare = txn(); + expect(normalizeTransactionAttributes(bare)).toBe(bare); // nothing to read, nothing copied + }); + + it('always carries a COPY forward: a getter cannot answer differently when a later step re-reads it', () => { + let reads = 0; + const attributes = { + get flip(): unknown { + reads++; + return reads === 1 ? 'ok' : dag(14, 3); + }, + }; + const out = normalizeTransactionAttributes(txn({ attributes })); + expect(reads).toBe(1); // read exactly once, by the normalization itself + expect(out.attributes).toEqual({ flip: 'ok' }); + expect(out.attributes === attributes).toBe(false); // (a matcher would re-read the getter) + expect(Object.getOwnPropertyDescriptor(out.attributes, 'flip')?.get).toBeUndefined(); + expect(out.attributes?.flip).toBe('ok'); // a plain data property, stable on every read + expect(reads).toBe(1); + }); + + it('keeps a child without attributes as is, and handles a root without attributes', () => { + const bare = child(); + const out = normalizeTransactionAttributes(txn({ attributes: { a: 1 }, spans: [bare] })); + expect(out.spans[0]).toBe(bare); + const rootless = normalizeTransactionAttributes(txn({ spans: [child({ b: 1 })] })); + expect(rootless.attributes).toBeUndefined(); + expect(rootless.spans[0]?.attributes).toEqual({ b: 1 }); + }); + + it('drops a key whose value is undefined (the copy differs from the input)', () => { + const t = txn({ attributes: { ok: 'x', gone: undefined } }); + const n = normalizeTransactionAttributes(t); + expect(n).not.toBe(t); + expect(Object.hasOwn(n.attributes ?? {}, 'gone')).toBe(false); + }); + + it('turns raw complex values (a DAG, a cycle, a throwing getter) into bounded trees on root and children', () => { + const cyc: Record = {}; + for (let j = 0; j < 3; j++) cyc[`k${j}`] = cyc; + const hostile = { + ok: 1, + get boom(): never { + throw new Error('getter'); + }, + }; + const input = txn({ + attributes: { dag: dag(14, 3), cyc, plain: 1 }, + spans: [child({ hostile, nul: null })], + }); + const started = Date.now(); + const out = normalizeTransactionAttributes(input); + expect(Date.now() - started).toBeLessThan(2000); // 3^14 = 4.7M paths walked raw + expect(JSON.stringify(out.attributes).length).toBeLessThan(200_000); + expect(out.attributes?.plain).toBe(1); + expect(JSON.stringify(out.attributes?.cyc)).toContain('[Circular]'); + expect(out.spans[0]?.attributes).toEqual({ hostile: { ok: 1, boom: '[Unreadable]' } }); + expect(input.attributes?.plain).toBe(1); // input untouched + }); + + it('shares one budget across a span: many large attributes cannot each take a full share', () => { + const wide = (): Record => + Object.fromEntries(Array.from({ length: 1000 }, (_, i) => [`k${i}`, 0])); + const attributes = Object.fromEntries(Array.from({ length: 40 }, (_, i) => [`a${i}`, wide()])); + const out = normalizeTransactionAttributes(txn({ attributes })); + const sizes = Object.values(out.attributes ?? {}).map( + (v) => Object.keys(v as Record).length, + ); + const total = sizes.reduce((a, b) => a + b, 0); + expect(total).toBeLessThan(6000); // 40 x 1000 members unbounded; the span budget is 4096 nodes + expect(out.attributes?.a39).toBe('[Truncated]'); + }); + + it('also caps the characters copied per span, not only the node count', () => { + const attributes = Object.fromEntries( + Array.from({ length: 40 }, (_, i) => [`a${i}`, { text: 'x'.repeat(8000) }]), + ); + const out = normalizeTransactionAttributes(txn({ attributes })); + expect(JSON.stringify(out.attributes).length).toBeLessThan(120_000); // 40 x 8 KB unbounded + expect(out.attributes?.a0).toEqual({ text: 'x'.repeat(8000) }); + expect(out.attributes?.a39).toBe('[Truncated]'); + }); + + it('survives an attribute record whose keys cannot be listed (a Proxy with a throwing ownKeys trap)', () => { + const hostile = new Proxy( + {}, + { + ownKeys() { + throw new Error('ownKeys'); + }, + }, + ); + const out = normalizeTransactionAttributes( + txn({ attributes: hostile, spans: [child(hostile)] }), + ); + expect(out.attributes).toEqual({}); + expect(out.spans[0]?.attributes).toEqual({}); + }); +}); diff --git a/packages/performance/src/transaction-attributes.ts b/packages/performance/src/transaction-attributes.ts new file mode 100644 index 000000000..a727a693b --- /dev/null +++ b/packages/performance/src/transaction-attributes.ts @@ -0,0 +1,53 @@ +import { flattenAttributes, normalizeAttributes } from './attribute-value'; +import type { TransactionWire } from './span'; + +/** + * The wire step for attributes: after redaction has seen any nested (OpenTelemetry `AnyValue`) value as a + * tree, flatten what remains to scalars and bounded JSON strings (see attribute-value.ts for the pipeline). + * Returns the SAME transaction, by reference, only when every attribute is already a scalar; any array + * attribute is copied (a filter may hold the array it set), so a transaction with one comes back as a new record. + */ +export function flattenTransactionAttributes(transaction: TransactionWire): TransactionWire { + const root = + transaction.attributes === undefined ? undefined : flattenAttributes(transaction.attributes); + let changed = root !== transaction.attributes; + const spans = transaction.spans.map((span) => { + if (span.attributes === undefined) return span; + const attributes = flattenAttributes(span.attributes); + if (attributes === span.attributes) return span; + changed = true; + return { ...span, attributes }; + }); + if (!changed) return transaction; + return { ...transaction, ...(root !== undefined ? { attributes: root } : {}), spans }; +} + +/** + * The FIRST step of the attribute pipeline, for EVERY transaction: bound each span's attributes (one shared + * span budget, cycles marked, hostile getters contained) before anything walks them. Consumed OTel spans + * already went through `normalizeAttributes`, but the SDK's own spans carry whatever `setAttribute`, + * `recordChildSpan({ attributes })` and `recordExternal` were handed, and the redaction walk that follows + * is only safe on a bounded tree: raw, a node:http request object took 1-2 s, a branching DAG 3-28 s and a + * self-referencing object never finished. Always carries the normalized COPY forward (never the caller's record), so every later step reads plain + * data properties once-evaluated instead of re-reading getters or proxies. A transaction with no attributes + * is returned as is. + */ +export function normalizeTransactionAttributes(transaction: TransactionWire): TransactionWire { + if ( + transaction.attributes === undefined && + transaction.spans.every((span) => span.attributes === undefined) + ) { + return transaction; // nothing to read, nothing copied + } + return { + ...transaction, + ...(transaction.attributes !== undefined + ? { attributes: normalizeAttributes(transaction.attributes) } + : {}), + spans: transaction.spans.map((span) => + span.attributes === undefined + ? span + : { ...span, attributes: normalizeAttributes(span.attributes) }, + ), + }; +} diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index c24d78e4f..d16690d50 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -47,7 +47,7 @@ export { SENSITIVE_HEADERS, SENSITIVE_KEY_SUBSTRINGS, } from './sensitive'; -export { redactShapes, type ShapeRedactionOptions } from './shapes'; +export { redactShapes, type ShapeRedactionOptions, unfinishedSecretStart } from './shapes'; export { bytesToMegabytes } from './units'; export { sanitizeErrorMessage, sanitizeUrl } from './url'; export type { diff --git a/packages/protocol/src/sensitive.ts b/packages/protocol/src/sensitive.ts index 5aa53d7df..76456fb08 100644 --- a/packages/protocol/src/sensitive.ts +++ b/packages/protocol/src/sensitive.ts @@ -120,6 +120,15 @@ function normalizeKey(name: string): string { return name.toLowerCase().replace(/[-_.\s]/g, ''); } +/** + * The denylist, normalised ONCE. `isSensitiveKey` used to re-normalise every entry (a lowercase plus a regex + * replace, ~60 times) on every call, ~4 us per key, and it now runs per NESTED key of a span attribute. + * Lazy, so the list is read after its declaration regardless of where this function is called from. + */ +let normalizedSubstrings: string[] | undefined; +const NORMALIZED_KEY_SUBSTRINGS = (): string[] => + (normalizedSubstrings ??= SENSITIVE_KEY_SUBSTRINGS.map(normalizeKey)); + /** * True if `name` is a sensitive body/query key. * @@ -134,7 +143,7 @@ function normalizeKey(name: string): string { */ export function isSensitiveKey(name: string): boolean { const normalized = normalizeKey(name); - if (SENSITIVE_KEY_SUBSTRINGS.some((sub) => normalized.includes(normalizeKey(sub)))) { + if (NORMALIZED_KEY_SUBSTRINGS().some((sub) => normalized.includes(sub))) { return true; } return isSensitiveHeader(name); diff --git a/packages/protocol/src/shapes.test.ts b/packages/protocol/src/shapes.test.ts index 85e19c488..b436b17b6 100644 --- a/packages/protocol/src/shapes.test.ts +++ b/packages/protocol/src/shapes.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { redactShapes } from './index'; +import { redactShapes, unfinishedSecretStart } from './index'; +import { compileShapePattern } from './shapes'; const R = ''; @@ -298,3 +299,145 @@ describe('the JWT bound sits at 8 KB, where the reachable window is', () => { expect(redactShapes(`${'x'.repeat(8000)} ${jwt}`)).toContain(''); }); }); + +// One COMPLETE secret per shape redactShapes knows. Built from pieces where it resembles a live key, so the +// repository's secret scanning does not take a fixture for a real one. +const SAMPLES: Record = { + jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln', + 'aws AKIA': 'AKIAIOSFODNN7EXAMPLE', + 'aws ASIA': 'ASIAIOSFODNN7EXAMPLE', + 'aws AGPA': 'AGPAIOSFODNN7EXAMPLE', + 'aws AIDA': 'AIDAIOSFODNN7EXAMPLE', + 'aws AROA': 'AROAIOSFODNN7EXAMPLE', + 'stripe sk': ['sk', 'live', 'abcdefghijklmnop'].join('_'), + 'stripe pk': ['pk', 'live', 'abcdefghijklmnop'].join('_'), + 'stripe rk': ['rk', 'live', 'abcdefghijklmnop'].join('_'), + 'stripe webhook': ['whsec', 'abcdefghijklmnop'].join('_'), + 'github ghp': `ghp_${'a'.repeat(36)}`, + 'github gho': `gho_${'a'.repeat(36)}`, + 'github ghu': `ghu_${'a'.repeat(36)}`, + 'github ghs': `ghs_${'a'.repeat(36)}`, +}; + +describe('unfinishedSecretStart', () => { + const b64url = (text: string): string => + (globalThis as unknown as { btoa(input: string): string }) + .btoa(text) + .replace(/=+$/, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); + + /** A JWT whose PAYLOAD contains a second `eyJ` (base64url of a nested `{"` on a 3-byte boundary). */ + const nestedJwt = (): { jwt: string; header: string; payload: string } => { + for (let pad = 0; pad < 8; pad += 1) { + const payload = b64url( + `${' '.repeat(pad)}{"exp":1,"realm_access":{"roles":["admin"]},"email":"alice@corp.example"}`, + ); + if (payload.indexOf('eyJ', 3) > 0) { + const header = 'eyJhbGciOiJIUzI1NiJ9'; + return { jwt: `${header}.${payload}.c2lnbmF0dXJl`, header, payload }; + } + } + throw new Error('no nested-eyJ payload found'); + }; + + it('is -1 when nothing secret-shaped begins, or when the text is empty', () => { + expect(unfinishedSecretStart('nothing secret here, just words and AKI')).toBe(-1); + expect(unfinishedSecretStart('')).toBe(-1); + }); + + it('is -1 for a complete secret of every shape (redactShapes will handle it whole)', () => { + for (const secret of Object.values(SAMPLES)) { + expect(redactShapes(secret)).not.toBe(secret); + expect(unfinishedSecretStart(`id_token=${secret}`)).toBe(-1); + } + }); + + it('points at the start of a secret the text ENDS inside: AWS (needs all 20), GitHub (needs 36)', () => { + expect(unfinishedSecretStart(`k=${'AKIAIOSFODNN7EXAMPLE'.slice(0, 14)}`)).toBe(2); + expect(unfinishedSecretStart(`k=${`ghp_${'a'.repeat(15)}`}`)).toBe(2); + }); + + it('treats a Stripe/webhook key as finished at any length (the pattern matches a partial one)', () => { + expect(unfinishedSecretStart(`k=${SAMPLES['stripe sk']?.slice(0, 10)}`)).toBe(-1); + expect(unfinishedSecretStart(`k=${SAMPLES['stripe webhook']?.slice(0, 8)}`)).toBe(-1); + }); + + it('handles a JWT whose payload contains a second eyJ: back off to the HEADER, not the inner start', () => { + const { jwt, header, payload } = nestedJwt(); + const innerAt = header.length + 1 + payload.indexOf('eyJ', 3); + expect(innerAt).toBeGreaterThan(header.length + 1); + // cut inside the payload, after the nested start + const cutInPayload = jwt.slice(0, innerAt + 10); + expect(unfinishedSecretStart(cutInPayload)).toBe(0); + expect(unfinishedSecretStart(`id_token=${cutInPayload}`)).toBe(9); + // cut inside the signature: a complete (3-segment) JWT, so nothing to back off from + expect(unfinishedSecretStart(jwt.slice(0, jwt.length - 4))).toBe(-1); + }); + + it('does not cut a complete secret in half because another shape begins inside it', () => { + // AKIA + 16 characters is a complete key even though `ASIA` appears inside its tail. + expect(unfinishedSecretStart('AKIAXXXXASIAYYYYYYYY')).toBe(-1); + // the same text one character short is unfinished, and the OUTER start is the answer + expect(unfinishedSecretStart('k=AKIAXXXXASIAYYYYYYY')).toBe(2); + // a ghp_ token that is complete with an AKIA-looking run inside it + expect(unfinishedSecretStart(`x=ghp_abcdefghijAKIAqrstuvwxyz0123456789ab`)).toBe(-1); + expect(unfinishedSecretStart('x=ghp_abcdefghijAKIAqrstuvwxyz012345')).toBe(2); + }); + + it('finds the unfinished one after several complete, independent secrets', () => { + const text = `${SAMPLES['github ghp']}/${SAMPLES['aws AKIA']}/${SAMPLES.jwt}/AKIAIOSFOD`; + expect(unfinishedSecretStart(text)).toBe(text.length - 'AKIAIOSFOD'.length); + expect(unfinishedSecretStart(text.slice(0, text.length - 'AKIAIOSFOD'.length))).toBe(-1); + }); + + it('does not take a COMPLETE secret that sits inside an unfinished JWT payload for the JWT being complete', () => { + // `id_token=
.` cut inside the payload, with an AWS key embedded in that payload. The AWS + // key is complete, but the JWT is not (two segments): the cut must still back off to the header. + const text = `id_token=eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjEs${'x'.repeat(20)}${SAMPLES['aws AKIA']}${'y'.repeat(30)}`; + expect(redactShapes(text)).toContain('eyJhbGciOiJIUzI1NiJ9'); // not matched as a JWT: only two segments + expect(unfinishedSecretStart(text)).toBe(9); + }); + + // The cap on starts examined: a JWT whose payload holds N inner `eyJ` starts, then a signature, then a + // half-written AWS key. Within the cap the walk sees the JWT finish and answers with the AWS key's start; past + // it the walk gives up and answers with the (earlier) current candidate. Pins 16 exactly. + const withInnerStarts = (inner: number): { text: string; awsAt: number } => { + const jwt = `eyJh.${'eyJ'.repeat(inner)}.sig`; + return { text: `${jwt}/AKIAxx`, awsAt: jwt.length + 1 }; + }; + + it('examines the first start plus 16 more: 15 inner starts still reach the AWS key (check 16 is allowed)', () => { + const { text, awsAt } = withInnerStarts(15); + expect(unfinishedSecretStart(text)).toBe(awsAt); + }); + + it('gives up at the 17th check and answers with the current candidate (16 inner starts)', () => { + const { text } = withInnerStarts(16); + expect(unfinishedSecretStart(text)).toBe(0); + expect(unfinishedSecretStart(withInnerStarts(1000).text)).toBe(0); + }); + + it('known limitation, pinned: a Stripe/GitHub token glued to another token start swallows its prefix', () => { + // `sk_live_` matches any alnum run, so it "completes" by swallowing `gho` of the glued `gho_<30>`, and the + // rest of the inner token is not seen as unfinished. The same glue already survives redactShapes on main + // without any cut, so this is not new exposure. + const glued = `k=sk_live_gho_${'a'.repeat(30)}`; + expect(unfinishedSecretStart(glued)).toBe(-1); + expect(redactShapes(`sk_live_ghp_${'a'.repeat(36)}`)).toContain(`_${'a'.repeat(36)}`); + }); + + it('stays bounded and safe on text dense with starts: past the candidate limit it backs off to the current one', () => { + const dense = `x=${'eyJ'.repeat(5000)}`; + const started = Date.now(); + expect(unfinishedSecretStart(dense)).toBe(2); + expect(Date.now() - started).toBeLessThan(2000); + }); +}); + +describe('compileShapePattern', () => { + it('groups the start, so an alternation at its top level cannot swallow the rest of the pattern', () => { + const pattern = compileShapePattern('foo|bar', '[0-9]{3}'); + expect('foo123 bar456 foo bar'.match(pattern)).toEqual(['foo123', 'bar456']); + }); +}); diff --git a/packages/protocol/src/shapes.ts b/packages/protocol/src/shapes.ts index fde012963..00a72afae 100644 --- a/packages/protocol/src/shapes.ts +++ b/packages/protocol/src/shapes.ts @@ -73,13 +73,71 @@ const JWT_UNANCHORED = /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g; */ const MAX_UNANCHORED_SCAN = 8192; -const SHAPE_PATTERNS: readonly RegExp[] = [ - /A(?:KIA|SIA|GPA|IDA|ROA)[0-9A-Z]{16}/g, // AWS access key id - /(?:sk|pk|rk)_live_[A-Za-z0-9]+/g, // Stripe live secret/publishable/restricted keys - /whsec_[A-Za-z0-9]+/g, // Stripe webhook signing secret - /gh[posu]_[A-Za-z0-9]{36,}/g, // GitHub personal access / OAuth / user / server token +/** + * Each shape declares where it BEGINS (`start`) and what follows (`rest`). The redaction patterns and + * {@link SECRET_SHAPE_START} are both built from these, so a new shape cannot be added to one and forgotten in + * the other. (The JWT is separate: it has two anchored patterns and begins `eyJ`.) + */ +const SHAPES: readonly { start: string; rest: string }[] = [ + { start: 'A(?:KIA|SIA|GPA|IDA|ROA)', rest: '[0-9A-Z]{16}' }, // AWS access key id + { start: '(?:sk|pk|rk)_live_', rest: '[A-Za-z0-9]+' }, // Stripe live secret/publishable/restricted keys + { start: 'whsec_', rest: '[A-Za-z0-9]+' }, // Stripe webhook signing secret + { start: 'gh[posu]_', rest: '[A-Za-z0-9]{36,}' }, // GitHub personal access / OAuth / user / server token ]; +/** One redaction pattern: the start is grouped so an alternation at its top level cannot split the pattern. */ +export const compileShapePattern = (start: string, rest: string): RegExp => + new RegExp(`(?:${start})${rest}`, 'g'); + +const SHAPE_PATTERNS: readonly RegExp[] = SHAPES.map(({ start, rest }) => + compileShapePattern(start, rest), +); + +/** Where any secret shape begins: the JWT header plus the start of every entry of {@link SHAPES}. */ +const SECRET_SHAPE_START = new RegExp( + ['eyJ', ...SHAPES.map(({ start }) => `(?:${start})`)].join('|'), + 'g', +); + +/** + * How many shape starts one call examines before it gives up and backs off to the current candidate. Each + * examination runs the redaction patterns over the text since that candidate, so the bound keeps the cost of a + * run made of nothing but starts (`eyJeyJeyJ...`) small; giving up errs toward dropping more, never less. + */ +const MAX_START_CHECKS = 16; + +/** Does a COMPLETE secret begin at offset 0 of `text` (so {@link redactShapes} would replace it)? */ +const beginsWithSecret = (text: string): boolean => redactShapes(text).startsWith(REDACTED); + +/** + * The offset where an UNFINISHED secret begins, i.e. the secret that `text` ends inside, or -1 when there is + * none. A caller that must cut text before redacting it uses this to back off before a secret the cut would + * leave half-written: a partial secret no longer matches {@link redactShapes}, so its readable part would + * reach the wire in the clear. + * + * Shape starts are walked left to right keeping the CURRENT secret's start, and the current secret only + * advances to a later start when the text since it is already a complete secret. That is what makes a start + * INSIDE another secret harmless: a JWT payload that itself contains `eyJ` (base64url of a nested `{"`), or an + * `ASIA` inside an AWS key's tail, does not move the answer off the outer secret. If the secret at the final + * candidate is complete (a JWT cut inside its signature still has three segments), there is nothing to back + * off from and the answer is -1. + */ +export function unfinishedSecretStart(text: string): number { + let current = -1; + let checks = 0; + for (const match of text.matchAll(SECRET_SHAPE_START)) { + const at = match.index; + if (current === -1) { + current = at; + } else { + checks += 1; + if (checks > MAX_START_CHECKS) return current; + if (beginsWithSecret(text.slice(current, at))) current = at; + } + } + return current === -1 || beginsWithSecret(text.slice(current)) ? -1 : current; +} + function isLuhnValid(digits: string): boolean { let sum = 0; let double = false; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5894e11fc..0cd998fa9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -55,7 +55,22 @@ importers: version: 6.0.3 vitest: specifier: ^4.1.7 - version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + + dev-packages/otel3-compat: + devDependencies: + '@bugsee/opentelemetry': + specifier: workspace:* + version: link:../../packages/opentelemetry + '@bugsee/performance': + specifier: workspace:* + version: link:../../packages/performance + '@opentelemetry/api': + specifier: ^1.10.0 + version: 1.10.0 + '@opentelemetry/sdk-trace': + specifier: ^3.0.0 + version: 3.0.0(@opentelemetry/api@1.10.0) dev-packages/packaging-guard: devDependencies: @@ -280,7 +295,7 @@ importers: version: 5.18.2(@types/node@22.20.5)(db0@0.3.4)(ioredis@5.11.1)(jiti@2.7.0)(lightningcss@1.33.0)(rollup@4.64.7)(terser@5.51.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.0) vitest: specifier: ^4.0.0 - version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) packages/babel-plugin-component-annotate: devDependencies: @@ -896,6 +911,9 @@ importers: '@opentelemetry/api': specifier: ^1.9.0 version: 1.9.1 + '@opentelemetry/sdk-trace': + specifier: ^2.12.0 + version: 2.12.0(@opentelemetry/api@1.9.1) '@opentelemetry/sdk-trace-base': specifier: ^2.12.0 version: 2.12.0(@opentelemetry/api@1.9.1) @@ -917,7 +935,7 @@ importers: devDependencies: next: specifier: ^15.5.28 - version: 15.5.28(@babel/core@7.29.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + version: 15.5.28(@babel/core@7.29.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) react: specifier: ^18.3.1 version: 18.3.1 @@ -926,7 +944,7 @@ importers: version: 18.3.1(react@18.3.1) vitest: specifier: ^4.0.0 - version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) packages/node: dependencies: @@ -1011,7 +1029,7 @@ importers: version: 4.6.1(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.153.0)(@parcel/watcher@2.5.6)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.43)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(rolldown@1.2.13)(rollup-plugin-visualizer@7.0.1(rolldown@1.2.13)(rollup@4.64.7))(rollup@4.64.7)(terser@5.51.2)(tsx@4.23.15)(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.0(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.30))(yaml@2.9.0) vitest: specifier: ^4.0.0 - version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) packages/opentelemetry: dependencies: @@ -1028,6 +1046,9 @@ importers: '@opentelemetry/api': specifier: ^1.9.0 version: 1.9.1 + '@opentelemetry/sdk-trace': + specifier: ^2.12.0 + version: 2.12.0(@opentelemetry/api@1.9.1) '@opentelemetry/sdk-trace-base': specifier: ^2.12.0 version: 2.12.0(@opentelemetry/api@1.9.1) @@ -1192,7 +1213,7 @@ importers: version: link:../web-adapter '@sveltejs/kit': specifier: '>=2' - version: 2.67.0(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.56.3(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 2.67.0(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.56.3(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) svelte: specifier: '>=4' version: 5.56.3(@typescript-eslint/types@8.59.4) @@ -1230,7 +1251,7 @@ importers: version: link:../node '@sveltejs/kit': specifier: ^2.70.3 - version: 2.70.3(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 2.70.3(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) packages/sveltekit-e2e: dependencies: @@ -1246,10 +1267,10 @@ importers: devDependencies: '@sveltejs/adapter-node': specifier: ^5.2.0 - version: 5.5.7(@sveltejs/kit@2.70.3(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))) + version: 5.5.7(@sveltejs/kit@2.70.3(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))) '@sveltejs/kit': specifier: ^2.70.3 - version: 2.70.3(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 2.70.3(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@sveltejs/vite-plugin-svelte': specifier: ^7.3.1 version: 7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -1261,7 +1282,7 @@ importers: version: 8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) vitest: specifier: ^4.0.0 - version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) packages/trackers: devDependencies: @@ -3670,6 +3691,10 @@ packages: engines: {node: '>=8.0.0', npm: '>=5.0.0'} hasBin: true + '@opentelemetry/api@1.10.0': + resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} + engines: {node: '>=8.0.0'} + '@opentelemetry/api@1.9.1': resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} engines: {node: '>=8.0.0'} @@ -3680,15 +3705,28 @@ packages: peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/core@3.0.0': + resolution: {integrity: sha512-whOLlww0R/RLtCWGBXhK1fdvL9t2/TL0fqdjZvcaoUUuNilRPjXecqQdzyVwV68s6XEDA5oYbm7/bZT62GXF4A==} + engines: {node: '>=22.15.0'} + peerDependencies: + '@opentelemetry/api': '>=1.10.0 <1.11.0' + '@opentelemetry/resources@2.12.0': resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/resources@3.0.0': + resolution: {integrity: sha512-4762KVmlDroRIt+4Ra8AnwcQqdXlkAR55jDrhzna8bzhJx1mUzvHW/Lh/OemFuY9+ouM4xaDc6CbUmoJmM6BFg==} + engines: {node: '>=22.15.0'} + peerDependencies: + '@opentelemetry/api': '>=1.10.0 <1.11.0' + '@opentelemetry/sdk-trace-base@2.12.0': resolution: {integrity: sha512-JOERgZCxRM06FEJ5kEWxlSRChah6MmXDx3KwCruqEv/iEyLkTokCSemf2y1w8oIHtfrr8EVTpzebq/31vn2Cpg==} engines: {node: ^18.19.0 || >=20.6.0} + deprecated: Use @opentelemetry/sdk-trace package peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' @@ -3698,6 +3736,12 @@ packages: peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/sdk-trace@3.0.0': + resolution: {integrity: sha512-4T0DbDGdtsjNmYK5/lNalHro4fsMZ0UZ3JE+C8fcqYP25xaJC22FHg8kdJNJ21srjJY5XoT7WNFCtj88NNTl4Q==} + engines: {node: '>=22.15.0'} + peerDependencies: + '@opentelemetry/api': '>=1.10.0 <1.11.0' + '@opentelemetry/semantic-conventions@1.43.0': resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} engines: {node: '>=14'} @@ -13266,6 +13310,8 @@ snapshots: transitivePeerDependencies: - encoding + '@opentelemetry/api@1.10.0': {} + '@opentelemetry/api@1.9.1': {} '@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1)': @@ -13273,12 +13319,23 @@ snapshots: '@opentelemetry/api': 1.9.1 '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/core@3.0.0(@opentelemetry/api@1.10.0)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/resources@3.0.0(@opentelemetry/api@1.10.0)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -13294,6 +13351,13 @@ snapshots: '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/sdk-trace@3.0.0(@opentelemetry/api@1.10.0)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/semantic-conventions@1.43.0': {} '@oslojs/encoding@1.1.0': {} @@ -13950,7 +14014,7 @@ snapshots: '@stryker-mutator/util': 9.6.1 semver: 7.8.1 tslib: 2.8.1 - vitest: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@sveltejs/acorn-typescript@1.0.10(acorn@8.16.0)': dependencies: @@ -13960,16 +14024,16 @@ snapshots: dependencies: acorn: 8.19.0 - '@sveltejs/adapter-node@5.5.7(@sveltejs/kit@2.70.3(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))': + '@sveltejs/adapter-node@5.5.7(@sveltejs/kit@2.70.3(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))': dependencies: '@rollup/plugin-commonjs': 29.0.3(rollup@4.64.7) '@rollup/plugin-json': 6.1.0(rollup@4.64.7) '@rollup/plugin-node-resolve': 16.0.3(rollup@4.64.7) '@rollup/plugin-replace': 6.0.3(rollup@4.64.7) - '@sveltejs/kit': 2.70.3(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + '@sveltejs/kit': 2.70.3(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) rollup: 4.64.7 - '@sveltejs/kit@2.67.0(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.56.3(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': + '@sveltejs/kit@2.67.0(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.56.3(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': dependencies: '@standard-schema/spec': 1.1.0 '@sveltejs/acorn-typescript': 1.0.10(acorn@8.16.0) @@ -13987,10 +14051,10 @@ snapshots: svelte: 5.56.3(@typescript-eslint/types@8.59.4) vite: 8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) optionalDependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 typescript: 6.0.3 - '@sveltejs/kit@2.70.3(@opentelemetry/api@1.9.1)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': + '@sveltejs/kit@2.70.3(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.57.2(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)))(svelte@5.57.2(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': dependencies: '@standard-schema/spec': 1.1.0 '@sveltejs/acorn-typescript': 1.0.13(acorn@8.19.0) @@ -14008,7 +14072,7 @@ snapshots: svelte: 5.57.2(@typescript-eslint/types@8.59.4) vite: 8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) optionalDependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 typescript: 6.0.3 '@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': @@ -14397,7 +14461,7 @@ snapshots: obug: 2.1.1 std-env: 4.1.0 tinyrainbow: 3.1.0 - vitest: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@vitest/expect@4.1.7': dependencies: @@ -17786,7 +17850,7 @@ snapshots: neotraverse@0.6.18: {} - next@15.5.28(@babel/core@7.29.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1): + next@15.5.28(@babel/core@7.29.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(react-dom@18.3.1(react@18.3.1))(react@18.3.1): dependencies: '@next/env': 15.5.28 '@swc/helpers': 0.5.15 @@ -17804,7 +17868,7 @@ snapshots: '@next/swc-linux-x64-musl': 15.5.28 '@next/swc-win32-arm64-msvc': 15.5.28 '@next/swc-win32-x64-msvc': 15.5.28 - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 sharp: 0.35.5(@types/node@22.20.5) transitivePeerDependencies: - '@babel/core' @@ -20761,7 +20825,7 @@ snapshots: optionalDependencies: vite: 8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) - vitest@4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.7 '@vitest/mocker': 4.1.7(vite@8.3.4(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -20785,14 +20849,14 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@edge-runtime/vm': 5.0.0 - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@types/node': 22.20.5 '@vitest/coverage-v8': 4.1.7(vitest@4.1.7) jsdom: 25.0.1 transitivePeerDependencies: - msw - vitest@4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.7 '@vitest/mocker': 4.1.7(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -20816,7 +20880,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@edge-runtime/vm': 5.0.0 - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@types/node': 22.20.5 '@vitest/coverage-v8': 4.1.7(vitest@4.1.7) jsdom: 25.0.1 diff --git a/turbo.json b/turbo.json index 49ab2ed1f..c2bff0c2b 100644 --- a/turbo.json +++ b/turbo.json @@ -17,7 +17,8 @@ "outputs": ["coverage/**"] }, "test:unit": { - "dependsOn": ["^build"] + "dependsOn": ["^build"], + "env": ["BUGSEE_REQUIRE_OTEL3"] }, "test:e2e": { "dependsOn": ["^build"],