From abec2a18ec9624792959feff5fe2691071719628 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 22:44:24 +0500 Subject: [PATCH 01/16] fix(opentelemetry): declare sdk-trace (OTel JS 3.x) as an optional peer next to sdk-trace-base (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenTelemetry JS 3.0 removed @opentelemetry/sdk-trace-base and replaced it with @opentelemetry/sdk-trace. @bugsee/opentelemetry and @bugsee/nextjs now declare sdk-trace-base >=1.0.0 <3 and sdk-trace >=3, all optional. The 3.x suite lives in the private dev-packages/otel3-compat because sdk-trace@3 peers api >=1.10 <1.11 while sdk-trace-base@2 peers api <1.10: one install cannot satisfy both. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- dev-packages/otel3-compat/package.json | 22 +++ .../otel3-compat/src/node-gate.test.ts | 33 +++++ dev-packages/otel3-compat/src/node-gate.ts | 25 ++++ .../otel3-compat/src/provider.test.ts | 25 ++++ dev-packages/otel3-compat/tsconfig.json | 8 ++ dev-packages/otel3-compat/vitest.config.ts | 7 + .../packaging-guard/src/otel-peers.test.ts | 45 ++++++ docs/design/opentelemetry-integration.md | 39 +++++- packages/nextjs/README.md | 2 +- packages/nextjs/package.json | 6 +- packages/nextjs/src/server.ts | 2 +- packages/opentelemetry/README.md | 11 +- packages/opentelemetry/package.json | 6 +- packages/opentelemetry/src/span-processor.ts | 5 +- pnpm-lock.yaml | 130 ++++++++++++++---- pnpm-workspace.yaml | 7 + 16 files changed, 339 insertions(+), 34 deletions(-) create mode 100644 dev-packages/otel3-compat/package.json create mode 100644 dev-packages/otel3-compat/src/node-gate.test.ts create mode 100644 dev-packages/otel3-compat/src/node-gate.ts create mode 100644 dev-packages/otel3-compat/src/provider.test.ts create mode 100644 dev-packages/otel3-compat/tsconfig.json create mode 100644 dev-packages/otel3-compat/vitest.config.ts create mode 100644 dev-packages/packaging-guard/src/otel-peers.test.ts 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..30a2ec9f4 --- /dev/null +++ b/dev-packages/otel3-compat/src/node-gate.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { nodeAtLeast, OTEL3_MIN_NODE, otel3Supported } 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)); + }); +}); 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..6732cfa75 --- /dev/null +++ b/dev-packages/otel3-compat/src/node-gate.ts @@ -0,0 +1,25 @@ +// OpenTelemetry JS 3.x declares `engines.node >=22.15.0` on core / resources / sdk-trace. The repo's CI matrix +// is Node 18-24, so the OTel 3 suites must stand down below that floor instead of failing the old legs. + +/** 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)'; 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..3216066dc --- /dev/null +++ b/dev-packages/otel3-compat/src/provider.test.ts @@ -0,0 +1,25 @@ +import { createBugseeSpanProcessor } from '@bugsee/opentelemetry'; +import type { TransactionWire } from '@bugsee/performance'; +import { describe, expect, it } from 'vitest'; +import { OTEL3_SKIP_NOTE, 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. +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 { TracerProvider } = await import('@opentelemetry/sdk-trace'); + const transactions: TransactionWire[] = []; + const processor = createBugseeSpanProcessor({ onTransaction: (t) => transactions.push(t) }); + const provider = new TracerProvider({ spanProcessors: [processor] }); + + provider.getTracer('t').startSpan('GET /users').end(); + await provider.shutdown(); + + expect(transactions).toHaveLength(1); + expect(transactions[0]?.name).toBe('GET /users'); + }); + }, +); 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-peers.test.ts b/dev-packages/packaging-guard/src/otel-peers.test.ts new file mode 100644 index 000000000..e8b06d9df --- /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 OTel 3.x', () => { + expect(manifest.peerDependencies?.['@opentelemetry/sdk-trace']).toBe('>=3'); + }); + + 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/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 7970a5a35..4828af411 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` (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 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,40 @@ 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` | `>=3` | OTel 3.x | + +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`), so a customer is bound only by their own SDK's peer range. + +**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 Node 18+ (it never loads +OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix only. + +**Registering the processor on 3.x.** `new TracerProvider({ spanProcessors: [processor] })` from +`@opentelemetry/sdk-trace`. Same `spanProcessors` option as 2.x, but the class was renamed from +`BasicTracerProvider` (which no longer exists), 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`. + +--- + ## 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..e6acafb39 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` 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 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..cbc08e8de 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": ">=3", "react": ">=18" }, "peerDependenciesMeta": { @@ -62,6 +63,9 @@ "@opentelemetry/sdk-trace-base": { "optional": true }, + "@opentelemetry/sdk-trace": { + "optional": true + }, "react": { "optional": true } 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..6ff342bcc 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 replaced `sdk-trace-base`) | ## 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..ebe2549f2 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -38,7 +38,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": ">=3" }, "peerDependenciesMeta": { "@opentelemetry/api": { @@ -46,6 +47,9 @@ }, "@opentelemetry/sdk-trace-base": { "optional": true + }, + "@opentelemetry/sdk-trace": { + "optional": true } }, "publishConfig": { diff --git a/packages/opentelemetry/src/span-processor.ts b/packages/opentelemetry/src/span-processor.ts index f1b5f8208..06efcff64 100644 --- a/packages/opentelemetry/src/span-processor.ts +++ b/packages/opentelemetry/src/span-processor.ts @@ -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. */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5894e11fc..d4706b573 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: @@ -889,6 +904,9 @@ importers: '@bugsee/vercel-edge': specifier: workspace:* version: link:../vercel-edge + '@opentelemetry/sdk-trace': + specifier: '>=3' + version: 3.0.0(@opentelemetry/api@1.9.1) devDependencies: '@bugsee/node': specifier: workspace:* @@ -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: @@ -1024,6 +1042,9 @@ importers: '@bugsee/performance': specifier: workspace:* version: link:../performance + '@opentelemetry/sdk-trace': + specifier: '>=3' + version: 3.0.0(@opentelemetry/api@1.9.1) devDependencies: '@opentelemetry/api': specifier: ^1.9.0 @@ -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,34 @@ 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/core@3.0.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@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/resources@3.0.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.9.1) + '@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 +13362,20 @@ 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/sdk-trace@3.0.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/semantic-conventions@1.43.0': {} '@oslojs/encoding@1.1.0': {} @@ -13950,7 +14032,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 +14042,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 +14069,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 +14090,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 +14479,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 +17868,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 +17886,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 +20843,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 +20867,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 +20898,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/pnpm-workspace.yaml b/pnpm-workspace.yaml index 2ce82d351..1c36d3d8a 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -21,3 +21,10 @@ allowBuilds: minimumReleaseAgeExclude: - '@bugsee/bugsee-cli@0.7.11' + # OpenTelemetry JS 3.0 GA (2026-10-20): the lockfile pins these inside the minimum-release-age window, and a + # frozen install rejects them without an exclusion. Remove these four lines once the versions are a day old + # (the policy then accepts them on its own). + - '@opentelemetry/api@1.10.0' + - '@opentelemetry/core@3.0.0' + - '@opentelemetry/resources@3.0.0' + - '@opentelemetry/sdk-trace@3.0.0' From c87271a479cde8431625597953b4970818792838 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 22:47:12 +0500 Subject: [PATCH 02/16] test(opentelemetry): run the span processor and OTLP path against real sdk-trace@3 and sdk-trace-base@2 providers (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dev-packages/otel3-compat drives a real @opentelemetry/sdk-trace@3 TracerProvider (nested spans, parent ids, attributes, status, events, links, exceptions, resource, remote parent, OTLP export) and tsc-checks that the 3.x ReadableSpan still satisfies ReadableSpanLike and the processor is a valid 3.x SpanProcessor. Skips with a stated reason below Node 22.15 (OTel 3 engines floor). A 2.x runtime twin lives in packages/opentelemetry. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../otel3-compat/src/provider.test.ts | 259 +++++++++++++++++- dev-packages/otel3-compat/src/types.test-d.ts | 22 ++ .../src/span-processor.real-sdk.test.ts | 98 +++++++ 3 files changed, 372 insertions(+), 7 deletions(-) create mode 100644 dev-packages/otel3-compat/src/types.test-d.ts create mode 100644 packages/opentelemetry/src/span-processor.real-sdk.test.ts diff --git a/dev-packages/otel3-compat/src/provider.test.ts b/dev-packages/otel3-compat/src/provider.test.ts index 3216066dc..2446dee2f 100644 --- a/dev-packages/otel3-compat/src/provider.test.ts +++ b/dev-packages/otel3-compat/src/provider.test.ts @@ -1,25 +1,270 @@ -import { createBugseeSpanProcessor } from '@bugsee/opentelemetry'; +import { + createBugseeSpanProcessor, + readableSpanToConsumed, + toOtlpExportRequest, +} from '@bugsee/opentelemetry'; import 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, 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. +// `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, + }; +} + 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 { TracerProvider } = await import('@opentelemetry/sdk-trace'); - const transactions: TransactionWire[] = []; - const processor = createBugseeSpanProcessor({ onTransaction: (t) => transactions.push(t) }); - const provider = new TracerProvider({ spanProcessors: [processor] }); + const { provider, tracer, transactions, errors } = await boot(); - provider.getTracer('t').startSpan('GET /users').end(); + 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('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/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); + }); +}); From bcda2159ff6d7bb3511bc4e57a63bab61361db51 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 22:52:45 +0500 Subject: [PATCH 03/16] feat(opentelemetry): map OTel API 1.10 AnyValue attributes deliberately (nested maps, mixed arrays, bytes) (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Scalars and homogeneous scalar arrays pass through unchanged; every other value becomes one bounded JSON string (bytes as base64, bytesValue on OTLP produce), so span redaction keeps seeing strings. The serializer never throws (cycles, bigint, Proxy, depth/width/length caps) and a bigint attribute no longer reaches the transaction JSON as an unserializable value. fast-check properties plus a real sdk-trace@3 test cover it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../otel3-compat/src/provider.test.ts | 31 ++ docs/design/opentelemetry-integration.md | 31 ++ .../src/attribute-value.fuzz.test.ts | 207 ++++++++++++ .../opentelemetry/src/attribute-value.test.ts | 297 ++++++++++++++++++ packages/opentelemetry/src/attribute-value.ts | 239 ++++++++++++++ packages/opentelemetry/src/index.ts | 9 + packages/opentelemetry/src/otlp-wire.ts | 5 +- .../opentelemetry/src/span-processor.test.ts | 65 ++++ packages/opentelemetry/src/span-processor.ts | 4 +- packages/opentelemetry/src/to-otlp.test.ts | 26 ++ packages/opentelemetry/src/to-otlp.ts | 5 +- 11 files changed, 916 insertions(+), 3 deletions(-) create mode 100644 packages/opentelemetry/src/attribute-value.fuzz.test.ts create mode 100644 packages/opentelemetry/src/attribute-value.test.ts create mode 100644 packages/opentelemetry/src/attribute-value.ts diff --git a/dev-packages/otel3-compat/src/provider.test.ts b/dev-packages/otel3-compat/src/provider.test.ts index 2446dee2f..49589b516 100644 --- a/dev-packages/otel3-compat/src/provider.test.ts +++ b/dev-packages/otel3-compat/src/provider.test.ts @@ -146,6 +146,37 @@ describe.skipIf(!otel3Supported)( }); }); + it('keeps complex AnyValue attributes the 3.x SDK retains: nested map, mixed array, bytes become strings', 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([]); + expect(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(); diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 4828af411..35825c614 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -202,6 +202,37 @@ OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix on `register()` either: call `trace.setGlobalTracerProvider(provider)` yourself. Verified against the real package in `dev-packages/otel3-compat`. +**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/opentelemetry/src/attribute-value.ts`. + +| input | consume (`readableSpanToConsumed`) | produce (`toAnyValue` -> OTLP) | +| --- | --- | --- | +| string / boolean / number | unchanged | `stringValue` / `boolValue` / `intValue` or `doubleValue` | +| homogeneous array of scalars (<= 1024) | unchanged (same array) | JSON `stringValue` (unchanged behaviour) | +| nested map, mixed/nested array, longer scalar array | one JSON string | JSON `stringValue` | +| byte array | base64 string | `bytesValue` (base64, per the proto3 JSON mapping) | +| bigint | number if exact, else decimal string | `intValue` (decimal string) | +| null, undefined, function, symbol | attribute dropped | attribute dropped | + +Why a JSON string and not a nested value, flattened keys, or a drop: Bugsee's attribute model is flat and its +redaction (`setSpanFilter`, the span sanitizer's `db.statement` scrub) reads values as strings, so a nested +`{ text: 'SELECT ...' }` would pass a string-keyed scrub; a string keeps it inside every existing redaction +path. Flattening to dotted keys explodes key counts and has no stable form for arrays. Dropping silently loses +exactly the attributes OTEP 4485 exists to carry. Native OTLP `arrayValue`/`kvlistValue` on produce is +possible (the wire supports it) but would change the existing exported shape of array attributes; deferred. + +The serializer never throws and is bounded: depth 8 (deeper containers become `"[MaxDepth]"`), 1024 visited +nodes (the rest becomes `"[Truncated]"`), 8192 characters of text (cut with `...[truncated]`), cycles become +`"[Circular]"` (a shared acyclic reference is not a cycle), non-finite numbers become the OTLP spellings +(`"NaN"`, `"Infinity"`, `"-Infinity"`), `toJSON` and other user code is never called, and a throwing +getter/Proxy yields `"[Unreadable]"` for that value (one unreadable attribute never costs its siblings or the +span). Covered by example tests, fast-check properties (`attribute-value.fuzz.test.ts`) and a real +`sdk-trace@3` test. + --- ## Cross-SDK coordination addendum (2026-06-21, from the Android OTel workstream) diff --git a/packages/opentelemetry/src/attribute-value.fuzz.test.ts b/packages/opentelemetry/src/attribute-value.fuzz.test.ts new file mode 100644 index 000000000..390657d3f --- /dev/null +++ b/packages/opentelemetry/src/attribute-value.fuzz.test.ts @@ -0,0 +1,207 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + normalizeAttributes, + normalizeAttributeValue, + stringifyAnyValue, + TRUNCATION_MARKER, +} from './attribute-value'; +import { readableSpanToConsumed } from './span-processor'; +import { toAnyValue, toKeyValues } from './to-otlp'; + +/** + * 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 }, + ); + }); +}); + +describe('normalizeAttributeValue (fuzz)', () => { + it('returns a scalar, a homogeneous scalar array, a bounded string, or nothing', () => { + fc.assert( + fc.property(anyValue, (value) => { + const out = normalizeAttributeValue(value); + if (out === undefined) return; + if (typeof out === 'string') { + // A string input is passed through untouched; any other input is bounded. + if (typeof value !== 'string') + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + return; + } + if (Array.isArray(out)) { + const kinds = new Set(out.map((v) => typeof v)); + expect(kinds.size).toBeLessThanOrEqual(1); + for (const kind of kinds) expect(['string', 'number', 'boolean']).toContain(kind); + return; + } + expect(['number', 'boolean']).toContain(typeof out); + }), + { numRuns: 400 }, + ); + }); + + it('leaves every scalar and every homogeneous scalar array untouched', () => { + const scalar = fc.oneof(fc.string(), 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: 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)).toBe(arr); + }), + ); + } + }); +}); + +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.parse(JSON.stringify(consumed.attributes))).toBeDefined(); + }), + { numRuns: 300 }, + ); + }); + + it('normalizeAttributes output is always JSON-serializable', () => { + fc.assert( + fc.property(fc.dictionary(fc.string({ maxLength: 8 }), anyValue, { maxKeys: 8 }), (attrs) => { + const out = normalizeAttributes(attrs); + expect(() => JSON.stringify(out)).not.toThrow(); + }), + { numRuns: 200 }, + ); + }); +}); diff --git a/packages/opentelemetry/src/attribute-value.test.ts b/packages/opentelemetry/src/attribute-value.test.ts new file mode 100644 index 000000000..32ffabd44 --- /dev/null +++ b/packages/opentelemetry/src/attribute-value.test.ts @@ -0,0 +1,297 @@ +import { describe, expect, it } from 'vitest'; +import { + bytesToBase64, + MAX_ATTRIBUTE_ARRAY_LENGTH, + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + MAX_ATTRIBUTE_NODES, + normalizeAttributes, + normalizeAttributeValue, + 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('keeps a bigint exact as a decimal string (JSON.stringify would throw)', () => { + expect(stringifyAnyValue({ n: 12345678901234567890n })).toBe('{"n":"12345678901234567890"}'); + }); + + 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 ends with the truncation marker', () => { + const out = stringifyAnyValue({ big: 'x'.repeat(50_000) }) as string; + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + expect(out.startsWith('{"big":"xxx')).toBe(true); + }); + + it('does not truncate output that fits exactly at the cap', () => { + const exact = 'y'.repeat(MAX_ATTRIBUTE_JSON_LENGTH - 2); // the two quotes make it exactly the cap + expect(stringifyAnyValue(exact)).toBe(JSON.stringify(exact)); + }); + + 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(); + }); +}); + +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)).toBe(strs); + expect(normalizeAttributeValue(nums)).toBe(nums); + expect(normalizeAttributeValue(bools)).toBe(bools); + const empty: unknown[] = []; + expect(normalizeAttributeValue(empty)).toBe(empty); + }); + + it('turns a mixed array, an array with null, or a nested array into a JSON string', () => { + expect(normalizeAttributeValue([1, 'a', true])).toBe('[1,"a",true]'); + expect(normalizeAttributeValue(['a', null])).toBe('["a",null]'); + expect(normalizeAttributeValue([[1], [2]])).toBe('[[1],[2]]'); + }); + + it('turns a primitive array past the length cap into a (truncated) JSON string', () => { + const long = Array.from({ length: MAX_ATTRIBUTE_ARRAY_LENGTH + 1 }, () => 'a'); + const out = normalizeAttributeValue(long); + expect(typeof out).toBe('string'); + const atCap = Array.from({ length: MAX_ATTRIBUTE_ARRAY_LENGTH }, () => 'a'); + expect(normalizeAttributeValue(atCap)).toBe(atCap); + }); + + it('turns an object into a JSON string and a byte array into a base64 string', () => { + expect(normalizeAttributeValue({ a: { b: [1, 'x'] } })).toBe('{"a":{"b":[1,"x"]}}'); + expect(normalizeAttributeValue(new Uint8Array([102, 111, 111]))).toBe('Zm9v'); + expect(normalizeAttributeValue(nodeBuffer.from('hi'))).toBe('aGk='); + }); + + 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('reads only own enumerable string keys', () => { + const inherited = Object.create({ inherited: 'no' }) as Record; + inherited.own = 'yes'; + expect(normalizeAttributes(inherited)).toEqual({ own: 'yes' }); + }); +}); diff --git a/packages/opentelemetry/src/attribute-value.ts b/packages/opentelemetry/src/attribute-value.ts new file mode 100644 index 000000000..711a44863 --- /dev/null +++ b/packages/opentelemetry/src/attribute-value.ts @@ -0,0 +1,239 @@ +// Complex attribute values (OpenTelemetry API 1.10 `AnyValue`, OTEP 4485). +// +// Before 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: it now also carries nested maps, arrays of mixed values, byte arrays +// and null, and (verified against sdk-trace@3.0.0) the SDK keeps all of them on `ReadableSpan.attributes` +// while dropping bigint/Date/function/symbol/cyclic values itself. A third-party or older SDK can still hand +// us anything at all, and `onEnd` runs inside the customer's `span.end()`. +// +// DECISION (the Bugsee attribute model is flat and its redaction runs on strings): +// - scalars, and homogeneous arrays of scalars, pass through UNCHANGED (a bigint, which JSON cannot carry, +// becomes a number when exact and decimal text otherwise); +// - everything else becomes ONE JSON STRING (a byte array becomes base64), bounded in depth, node count and +// length, and never throwing; +// - null/undefined/function/symbol have no value: the attribute is dropped. +// A string, not a nested object, because the span sanitizer/filter and the viewer all read attribute values +// as scalars: a `db.statement` that arrives as `{ text: 'SELECT ...' }` would otherwise sail past a +// string-keyed scrub. Flattening to dotted keys was rejected (key explosion, and arrays have no stable key +// form); dropping was rejected (silent data loss for the very attributes 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 serialized; 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 JSON (bounded) route. */ +export const MAX_ATTRIBUTE_ARRAY_LENGTH = 1024; +/** Appended when the JSON text had to be cut. */ +export const TRUNCATION_MARKER = '...[truncated]'; + +const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +/** RFC 4648 base64 with padding. Hand-rolled: `btoa`/`Buffer` are runtime-specific and this package 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) + + 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; +} + +/** OTLP AnyValue bytes: a `Uint8Array` (a Node `Buffer` is one). Other typed arrays are not AnyValue. */ +export function isByteArray(value: unknown): value is Uint8Array { + return value instanceof Uint8Array; +} + +const capText = (text: string): string => + text.length <= MAX_ATTRIBUTE_JSON_LENGTH + ? text + : text.slice(0, MAX_ATTRIBUTE_JSON_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER; + +/** 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; + +/** Base64 of a byte array, bounded (encodes at most what could fit, then cuts with the marker). */ +const boundedBase64 = (bytes: Uint8Array): string => + capText( + bytesToBase64(bytes.length > MAX_BYTES_ENCODED ? bytes.subarray(0, MAX_BYTES_ENCODED) : bytes), + ); + +const SKIP = Symbol('skip'); + +interface Budget { + nodes: number; +} + +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, + }); +}; + +/** Copy a value into a tree containing only JSON-safe values, within the depth/node budget. */ +function toSafe(value: unknown, depth: number, budget: Budget, ancestors: Set): unknown { + if (value === null) return null; + switch (typeof value) { + case 'string': + return value; + case 'boolean': + return value; + case 'number': + if (Number.isFinite(value)) return value; + return Number.isNaN(value) ? 'NaN' : value > 0 ? 'Infinity' : '-Infinity'; + case 'bigint': + return value.toString(); + case 'object': + break; + default: + return SKIP; // undefined, function, symbol + } + if (isByteArray(value)) return boundedBase64(value); + if (value instanceof Date) { + const time = value.getTime(); + return Number.isNaN(time) ? null : new Date(time).toISOString(); + } + if (depth >= MAX_ATTRIBUTE_DEPTH) return '[MaxDepth]'; + if (ancestors.has(value)) return '[Circular]'; + ancestors.add(value); + try { + if (Array.isArray(value)) return arrayToSafe(value, depth, budget, ancestors); + return objectToSafe(value as Record, depth, budget, ancestors); + } catch { + return '[Unreadable]'; + } finally { + ancestors.delete(value); + } +} + +function arrayToSafe( + items: unknown[], + depth: number, + budget: Budget, + ancestors: Set, +): unknown[] { + const out: unknown[] = []; + budget.nodes++; + for (let i = 0; i < items.length; i++) { + if (budget.nodes >= MAX_ATTRIBUTE_NODES) { + out.push('[Truncated]'); + break; + } + budget.nodes++; + 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 = {}; + budget.nodes++; + for (const key of Object.keys(source)) { + if (budget.nodes >= MAX_ATTRIBUTE_NODES) { + setOwn(out, '[Truncated]', true); + break; + } + budget.nodes++; + let member: unknown; + try { + member = toSafe(source[key], depth + 1, budget, ancestors); + } catch { + member = '[Unreadable]'; + } + if (member !== SKIP) setOwn(out, key, member); + } + return out; +} + +/** + * The JSON text of an AnyValue, bounded and never throwing. Byte arrays become base64, bigints decimal + * strings, non-finite numbers the OTLP spellings; a cycle, over-deep or over-wide structure is marked, not + * followed. Returns `undefined` when the value has no JSON form at all (undefined/function/symbol). + */ +export function stringifyAnyValue(value: unknown): string | undefined { + let safe: unknown; + try { + safe = toSafe(value, 0, { nodes: 0 }, new Set()); + } catch { + safe = '[Unreadable]'; + } + if (safe === SKIP) return undefined; + return capText(JSON.stringify(safe)); +} + +const isScalar = (v: unknown): v is string | number | boolean => + typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'; + +/** A non-empty-or-empty array whose elements are all strings, all numbers or all booleans (the pre-1.10 shape). */ +function isHomogeneousScalarArray(value: unknown[]): boolean { + if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return false; + if (value.length === 0) return true; + const kind = typeof value[0]; + if (!isScalar(value[0])) return false; + return value.every((item) => typeof item === kind); +} + +/** + * Normalize one OTel attribute value for the Bugsee attribute model (see the decision at the top of this + * file). `undefined` means the attribute has no representation and is dropped. + */ +export function normalizeAttributeValue(value: unknown): unknown { + if (value === null || value === undefined) return undefined; + if (isScalar(value)) return value; + // A bigint is not JSON-serializable (the transaction is, later): exact as a number when safe, else decimal text. + if (typeof value === 'bigint') { + return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) + ? Number(value) + : value.toString(); + } + if (isByteArray(value)) return boundedBase64(value); + if (Array.isArray(value) && isHomogeneousScalarArray(value)) return value; + return stringifyAnyValue(value); +} + +/** + * Normalize an OTel attributes record: own enumerable string keys only, each value normalized, an attribute + * whose value cannot be read (a throwing getter) skipped without losing its siblings. + */ +export function normalizeAttributes(attributes: Record): Record { + const out: Record = {}; + for (const key of Object.keys(attributes)) { + try { + const value = normalizeAttributeValue(attributes[key]); + if (value !== undefined) setOwn(out, key, value); + } catch { + // unreadable attribute: skip it, keep the rest + } + } + return out; +} diff --git a/packages/opentelemetry/src/index.ts b/packages/opentelemetry/src/index.ts index 597d4549c..003c85f11 100644 --- a/packages/opentelemetry/src/index.ts +++ b/packages/opentelemetry/src/index.ts @@ -5,6 +5,15 @@ // compatible); and the SpanProcessor consume bridge — `createBugseeSpanProcessor` below. // PLANNED: the interception-transformer propagation. +export { + MAX_ATTRIBUTE_ARRAY_LENGTH, + MAX_ATTRIBUTE_DEPTH, + MAX_ATTRIBUTE_JSON_LENGTH, + MAX_ATTRIBUTE_NODES, + normalizeAttributes, + normalizeAttributeValue, + stringifyAnyValue, +} from './attribute-value'; export { type ConsumedSpan, consumedRootToTransaction, 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.test.ts b/packages/opentelemetry/src/span-processor.test.ts index bd3e317c1..24d284e3d 100644 --- a/packages/opentelemetry/src/span-processor.test.ts +++ b/packages/opentelemetry/src/span-processor.test.ts @@ -58,6 +58,71 @@ 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('turns a nested map, a mixed array and a byte array into strings and keeps 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((consumed.attributes?.huge as string).length).toBeLessThanOrEqual(8192); + }); + + it('feeds a real transaction: the consumed attribute reaches the assembled transaction as a string', () => { + 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']).toBe('{"text":"SELECT 1"}'); + }); + }); + it('prefers the OTel 2.x parentSpanContext over the 1.x parentSpanId', () => { const consumed = readableSpanToConsumed( readable({ diff --git a/packages/opentelemetry/src/span-processor.ts b/packages/opentelemetry/src/span-processor.ts index 06efcff64..c1753a9e2 100644 --- a/packages/opentelemetry/src/span-processor.ts +++ b/packages/opentelemetry/src/span-processor.ts @@ -1,5 +1,6 @@ import { neverThrow } from '@bugsee/core'; import type { TransactionWire } from '@bugsee/performance'; +import { normalizeAttributes } from './attribute-value'; import type { ConsumedSpan } from './from-otlp'; import { createTraceAssembler } from './trace-assembler'; @@ -36,6 +37,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; } @@ -61,7 +63,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) } : {}), }; } diff --git a/packages/opentelemetry/src/to-otlp.test.ts b/packages/opentelemetry/src/to-otlp.test.ts index 2c6854bb5..33077eed5 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. @@ -45,6 +54,23 @@ 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.endsWith('...[truncated]')).toBe(true); + }); it('returns undefined for undefined/null (the key is dropped)', () => { expect(toAnyValue(undefined)).toBeUndefined(); expect(toAnyValue(null)).toBeUndefined(); diff --git a/packages/opentelemetry/src/to-otlp.ts b/packages/opentelemetry/src/to-otlp.ts index 2428ede8b..6587c3627 100644 --- a/packages/opentelemetry/src/to-otlp.ts +++ b/packages/opentelemetry/src/to-otlp.ts @@ -1,4 +1,5 @@ import type { SpanStatus, TransactionWire } from '@bugsee/performance'; +import { bytesToBase64, isByteArray, stringifyAnyValue } from './attribute-value'; import { OTLP_SPAN_FLAG_SAMPLED, type OtlpAnyValue, @@ -62,7 +63,9 @@ 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) + if (isByteArray(value)) return { bytesValue: bytesToBase64(value) }; + // objects/arrays → bounded JSON string that cannot throw (cycles, bigint, depth); functions/symbols → dropped + const json = stringifyAnyValue(value); return json !== undefined ? { stringValue: json } : undefined; } } From 7df17414f066ab60501b14798702bc0ea82f8c30 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 22:53:44 +0500 Subject: [PATCH 04/16] test(packaging-guard): fail on any @opentelemetry deep import, package.json read or node_modules path (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OTel JS 3.0 added exports maps everywhere. No Bugsee package reaches into OTel internals today (audited incl. browser/webworker/edge/bundler plugins); the guard keeps it that way. Documents the webpack >= 5.54 requirement for OTel 3 browser builds. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../src/otel-no-deep-imports.test.ts | 91 +++++++++++++++++++ docs/design/opentelemetry-integration.md | 10 ++ 2 files changed, 101 insertions(+) create mode 100644 dev-packages/packaging-guard/src/otel-no-deep-imports.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/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 35825c614..071eb77c5 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -202,6 +202,16 @@ OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix on `register()` either: call `trace.setGlobalTracerProvider(provider)` yourself. Verified against the real package in `dev-packages/otel3-compat`. +**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 From ca70e8d67b27c69ff7e0cad665f8c7fce031cf63 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 22:55:47 +0500 Subject: [PATCH 05/16] fix(nextjs): zero-config OTel provider falls back to sdk-trace on OpenTelemetry JS 3.x (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sdk-trace-base does not exist on OTel 3, so the zero-config provider reported 'unavailable' there. loadOtelModules prefers sdk-trace-base (unchanged for 1.x/2.x) and falls back to sdk-trace's TracerProvider. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- packages/nextjs/src/otel-provider.test.ts | 145 +++++++++++++++++++++- packages/nextjs/src/otel-provider.ts | 61 +++++++-- 2 files changed, 193 insertions(+), 13 deletions(-) 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..cfdc76a64 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 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 3.x (which 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` (OTel 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 From 8166650614507ea2d9bb98c633f9384685920600 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 22:55:47 +0500 Subject: [PATCH 06/16] docs(opentelemetry): OTel 3 compatibility notes, PROGRESS entry and changeset (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 14 ++++++++++++++ docs/PROGRESS.md | 18 +++++++++++++++++- docs/design/opentelemetry-integration.md | 6 ++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 .changeset/opentelemetry-3-support.md diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md new file mode 100644 index 000000000..28b053e91 --- /dev/null +++ b/.changeset/opentelemetry-3-support.md @@ -0,0 +1,14 @@ +--- +'@bugsee/opentelemetry': minor +'@bugsee/nextjs': 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`. Both packages now declare `@opentelemetry/sdk-trace` (`>=3`) as an optional peer next to `@opentelemetry/sdk-trace-base` (now `>=1.0.0 <3`). Both stay optional: produce-only users install neither. On OpenTelemetry 3 register the processor with `new TracerProvider({ spanProcessors: [processor] })` from `@opentelemetry/sdk-trace` (the class was renamed from `BasicTracerProvider`). 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. + +`@bugsee/nextjs` zero-config provider now falls back to `@opentelemetry/sdk-trace` when `sdk-trace-base` is not installed. Before, an OpenTelemetry 3 install silently left the zero-config provider `unavailable`. + +Consumed span attributes that are complex `AnyValue`s are now mapped deliberately instead of being passed through raw: scalars and homogeneous scalar arrays are unchanged, and nested maps, mixed or nested arrays and byte arrays become one bounded JSON string (bytes as base64), so span redaction (`setSpanFilter`, the `db.statement` scrub) keeps seeing strings. `null`, `undefined`, functions and symbols drop the attribute. A `bigint` attribute becomes a number when exact and decimal text otherwise (it used to reach the transaction as a value JSON cannot serialize). The serializer never throws and caps depth (8), visited nodes (1024) and length (8192 characters). On OTLP export a byte array is now sent as `bytesValue` (base64), and an object attribute with a cycle or a bigint no longer throws while it is encoded. + +New exports from `@bugsee/opentelemetry`: `normalizeAttributes`, `normalizeAttributeValue`, `stringifyAnyValue` and the `MAX_ATTRIBUTE_*` limits. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 7a723b43c..9fb026b22 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -595,7 +595,23 @@ 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.** -- **T — DONE (`main`):** the interception-transformer seam in `@bugsee/capture`. Capture interceptors +- **OTel JS 3.x compatibility — DONE (2026-10-21, issue #94)** → `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` `>=3` (3.x, which REMOVED sdk-trace-base and renamed + `BasicTracerProvider` to `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: `attribute-value.ts` — scalars/homogeneous scalar arrays unchanged, anything else one + bounded JSON string (bytes base64, `bytesValue` on OTLP produce), never throws; fast-check fuzz. Found+fixed a + real bug on the way: 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`). `pnpm-workspace.yaml` carries 4 temporary `minimumReleaseAgeExclude` entries for + the OTel 3.0 GA versions; delete them once they are a day old. NOT verified: OTel 3 on Node < 22.15 (unsupported + upstream; the suite skips), a real Next.js app on OTel 3 end to end. + 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` on BOTH fetch (rebuilds `init.headers`) and xhr (original `setRequestHeader` at send). The "interceptors diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 071eb77c5..e226baf52 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -202,6 +202,12 @@ OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix on `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`, 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 From c78c34558160b0bf39a40379cb7bb8a2538fbef6 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 23:32:23 +0500 Subject: [PATCH 07/16] fix(opentelemetry,performance,nextjs): bounded total attribute serializer, late normalization with nested redaction, sdk-trace >=2.9.0 peer (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - attribute-value moves to @bugsee/performance; bounded in work (leaf/key/char/node/depth caps, typed arrays by index), total (JSON.stringify inside the try, per-attribute containment on the produce path, Proxy ownKeys), scalar strings capped at 32 KiB. - consume keeps a bounded tree; the default sanitizer redacts nested keys; the performance extension flattens to JSON strings at the wire after the filter. - sdk-trace peer is >=2.9.0 (exists since 2.9); drop the minimumReleaseAgeExclude entries; dev dep sdk-trace ^2.12 so no peer-violating sdk-trace@3 lands in opentelemetry/nextjs. - processor ignores onEnd after shutdown; BUGSEE_REQUIRE_OTEL3 turns the 3.x skip into a failure (CI). - repair PROGRESS.md and nextjs README; separate nextjs changeset. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/nextjs-otel3-provider-fallback.md | 7 + .changeset/opentelemetry-3-support.md | 10 +- .github/workflows/ci.yml | 4 + .../otel3-compat/src/node-gate.test.ts | 22 +- dev-packages/otel3-compat/src/node-gate.ts | 10 + .../otel3-compat/src/provider.test.ts | 22 +- .../packaging-guard/src/otel-peers.test.ts | 4 +- docs/PROGRESS.md | 26 +- docs/design/opentelemetry-integration.md | 91 +++-- packages/nextjs/README.md | 2 +- packages/nextjs/package.json | 3 +- packages/nextjs/src/otel-provider.ts | 6 +- packages/opentelemetry/README.md | 2 +- packages/opentelemetry/package.json | 3 +- .../src/attribute-mapping.fuzz.test.ts | 75 ++++ packages/opentelemetry/src/attribute-value.ts | 239 ------------- packages/opentelemetry/src/index.ts | 6 +- .../opentelemetry/src/otlp-exporter.test.ts | 41 +++ .../opentelemetry/src/span-processor.test.ts | 28 +- packages/opentelemetry/src/span-processor.ts | 6 +- packages/opentelemetry/src/to-otlp.test.ts | 112 +++++- packages/opentelemetry/src/to-otlp.ts | 67 +++- .../src/attribute-value.fuzz.test.ts | 74 ++-- .../src/attribute-value.test.ts | 193 ++++++++++- packages/performance/src/attribute-value.ts | 328 ++++++++++++++++++ packages/performance/src/extension.test.ts | 66 ++++ packages/performance/src/extension.ts | 9 +- packages/performance/src/index.ts | 18 + .../performance/src/span-sanitizer.test.ts | 73 ++++ packages/performance/src/span-sanitizer.ts | 65 +++- .../src/transaction-attributes.test.ts | 54 +++ .../performance/src/transaction-attributes.ts | 22 ++ pnpm-lock.yaml | 30 +- pnpm-workspace.yaml | 7 - turbo.json | 3 +- 35 files changed, 1315 insertions(+), 413 deletions(-) create mode 100644 .changeset/nextjs-otel3-provider-fallback.md create mode 100644 packages/opentelemetry/src/attribute-mapping.fuzz.test.ts delete mode 100644 packages/opentelemetry/src/attribute-value.ts rename packages/{opentelemetry => performance}/src/attribute-value.fuzz.test.ts (69%) rename packages/{opentelemetry => performance}/src/attribute-value.test.ts (58%) create mode 100644 packages/performance/src/attribute-value.ts create mode 100644 packages/performance/src/transaction-attributes.test.ts create mode 100644 packages/performance/src/transaction-attributes.ts 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 index 28b053e91..11438ed86 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -1,14 +1,14 @@ --- '@bugsee/opentelemetry': minor -'@bugsee/nextjs': minor +'@bugsee/performance': 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`. Both packages now declare `@opentelemetry/sdk-trace` (`>=3`) as an optional peer next to `@opentelemetry/sdk-trace-base` (now `>=1.0.0 <3`). Both stay optional: produce-only users install neither. On OpenTelemetry 3 register the processor with `new TracerProvider({ spanProcessors: [processor] })` from `@opentelemetry/sdk-trace` (the class was renamed from `BasicTracerProvider`). 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. +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` (the class was renamed from `BasicTracerProvider`). 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. -`@bugsee/nextjs` zero-config provider now falls back to `@opentelemetry/sdk-trace` when `sdk-trace-base` is not installed. Before, an OpenTelemetry 3 install silently left the zero-config provider `unavailable`. +Complex span attributes (OpenTelemetry API 1.10 `AnyValue`) are now handled deliberately. 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). On OTLP export a byte array is sent as `bytesValue` (base64), and one hostile attribute (a Proxy that throws, a cycle, an enormous string) no longer rejects the whole export batch. -Consumed span attributes that are complex `AnyValue`s are now mapped deliberately instead of being passed through raw: scalars and homogeneous scalar arrays are unchanged, and nested maps, mixed or nested arrays and byte arrays become one bounded JSON string (bytes as base64), so span redaction (`setSpanFilter`, the `db.statement` scrub) keeps seeing strings. `null`, `undefined`, functions and symbols drop the attribute. A `bigint` attribute becomes a number when exact and decimal text otherwise (it used to reach the transaction as a value JSON cannot serialize). The serializer never throws and caps depth (8), visited nodes (1024) and length (8192 characters). On OTLP export a byte array is now sent as `bytesValue` (base64), and an object attribute with a cycle or a bigint no longer throws while it is encoded. +`createBugseeSpanProcessor` now ignores `onEnd` after `shutdown()`. -New exports from `@bugsee/opentelemetry`: `normalizeAttributes`, `normalizeAttributeValue`, `stringifyAnyValue` and the `MAX_ATTRIBUTE_*` limits. +New exports from `@bugsee/performance` (also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue` 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/src/node-gate.test.ts b/dev-packages/otel3-compat/src/node-gate.test.ts index 30a2ec9f4..133e7f8a2 100644 --- a/dev-packages/otel3-compat/src/node-gate.test.ts +++ b/dev-packages/otel3-compat/src/node-gate.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { nodeAtLeast, OTEL3_MIN_NODE, otel3Supported } from './node-gate'; +import { + nodeAtLeast, + OTEL3_MIN_NODE, + otel3Required, + otel3Supported, + skipIsForbidden, +} from './node-gate'; describe('nodeAtLeast', () => { it.each([ @@ -31,3 +37,17 @@ describe('nodeAtLeast', () => { 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 index 6732cfa75..3e9cee4ae 100644 --- a/dev-packages/otel3-compat/src/node-gate.ts +++ b/dev-packages/otel3-compat/src/node-gate.ts @@ -23,3 +23,13 @@ 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 index 49589b516..a62a2ac19 100644 --- a/dev-packages/otel3-compat/src/provider.test.ts +++ b/dev-packages/otel3-compat/src/provider.test.ts @@ -3,10 +3,10 @@ import { readableSpanToConsumed, toOtlpExportRequest, } from '@bugsee/opentelemetry'; -import type { TransactionWire } from '@bugsee/performance'; +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, otel3Supported } from './node-gate'; +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 @@ -55,6 +55,14 @@ async function boot(): Promise<{ }; } +// 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})`, () => { @@ -146,7 +154,7 @@ describe.skipIf(!otel3Supported)( }); }); - it('keeps complex AnyValue attributes the 3.x SDK retains: nested map, mixed array, bytes become strings', async () => { + 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({ @@ -165,7 +173,15 @@ describe.skipIf(!otel3Supported)( 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', diff --git a/dev-packages/packaging-guard/src/otel-peers.test.ts b/dev-packages/packaging-guard/src/otel-peers.test.ts index e8b06d9df..d98e4a287 100644 --- a/dev-packages/packaging-guard/src/otel-peers.test.ts +++ b/dev-packages/packaging-guard/src/otel-peers.test.ts @@ -29,8 +29,8 @@ describe.each([ expect(manifest.peerDependencies?.['@opentelemetry/sdk-trace-base']).toBe('>=1.0.0 <3'); }); - it('sdk-trace covers OTel 3.x', () => { - expect(manifest.peerDependencies?.['@opentelemetry/sdk-trace']).toBe('>=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', () => { diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 9fb026b22..54e60d401 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -595,23 +595,29 @@ 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)** → `docs/design/opentelemetry-integration.md` +- **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` `>=3` (3.x, which REMOVED sdk-trace-base and renamed - `BasicTracerProvider` to `TracerProvider`), all optional; guard `packaging-guard/src/otel-peers.test.ts`. + `>=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: `attribute-value.ts` — scalars/homogeneous scalar arrays unchanged, anything else one - bounded JSON string (bytes base64, `bytesValue` on OTLP produce), never throws; fast-check fuzz. Found+fixed a - real bug on the way: a `bigint` attribute reached the transaction as a value `JSON.stringify` throws on. + (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. Bounded in WORK (leaf, key and total-character budgets, typed + arrays read by index) 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`). `pnpm-workspace.yaml` carries 4 temporary `minimumReleaseAgeExclude` entries for - the OTel 3.0 GA versions; delete them once they are a day old. NOT verified: OTel 3 on Node < 22.15 (unsupported - upstream; the suite skips), a real Next.js app on OTel 3 end to end. - in `@bugsee/capture`. Capture interceptors + `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` on BOTH fetch (rebuilds `init.headers`) and xhr (original `setRequestHeader` at send). The "interceptors diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index e226baf52..0c161d96d 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -99,7 +99,7 @@ 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` (OTel JS 1.x/2.x) or `@opentelemetry/sdk-trace` (3.x) — see + `@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 @@ -139,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` on OTel 1.x/2.x, `sdk-trace` on 3.x), **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. @@ -181,7 +181,7 @@ and replaced them with the single `@opentelemetry/sdk-trace`. Both `@bugsee/open | --- | --- | --- | | `@opentelemetry/api` | `>=1.0.0` | every major | | `@opentelemetry/sdk-trace-base` | `>=1.0.0 <3` | OTel 1.x / 2.x | -| `@opentelemetry/sdk-trace` | `>=3` | OTel 3.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`. @@ -194,7 +194,9 @@ Guard: `dev-packages/packaging-guard/src/otel-peers.test.ts`. **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 Node 18+ (it never loads -OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix only. +OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix only. It skips below 22.15 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 2.x, but the class was renamed from @@ -204,7 +206,7 @@ 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`, 3.x). Before this, an OTel 3 install reported `unavailable` +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. @@ -223,31 +225,62 @@ edge and bundler-plugin packages). 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/opentelemetry/src/attribute-value.ts`. - -| input | consume (`readableSpanToConsumed`) | produce (`toAnyValue` -> OTLP) | +`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: + +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`, string leaves are scanned for secret shapes, 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 +and a bounded JSON `stringValue` for maps/arrays. + +| input | after consume | at the wire / OTLP produce | | --- | --- | --- | -| string / boolean / number | unchanged | `stringValue` / `boolValue` / `intValue` or `doubleValue` | -| homogeneous array of scalars (<= 1024) | unchanged (same array) | JSON `stringValue` (unchanged behaviour) | -| nested map, mixed/nested array, longer scalar array | one JSON string | JSON `stringValue` | -| byte array | base64 string | `bytesValue` (base64, per the proto3 JSON mapping) | -| bigint | number if exact, else decimal string | `intValue` (decimal string) | -| null, undefined, function, symbol | attribute dropped | attribute dropped | - -Why a JSON string and not a nested value, flattened keys, or a drop: Bugsee's attribute model is flat and its -redaction (`setSpanFilter`, the span sanitizer's `db.statement` scrub) reads values as strings, so a nested -`{ text: 'SELECT ...' }` would pass a string-keyed scrub; a string keeps it inside every existing redaction -path. Flattening to dotted keys explodes key counts and has no stable form for arrays. Dropping silently loses -exactly the attributes OTEP 4485 exists to carry. Native OTLP `arrayValue`/`kvlistValue` on produce is -possible (the wire supports it) but would change the existing exported shape of array attributes; deferred. - -The serializer never throws and is bounded: depth 8 (deeper containers become `"[MaxDepth]"`), 1024 visited -nodes (the rest becomes `"[Truncated]"`), 8192 characters of text (cut with `...[truncated]`), cycles become -`"[Circular]"` (a shared acyclic reference is not a cycle), non-finite numbers become the OTLP spellings -(`"NaN"`, `"Infinity"`, `"-Infinity"`), `toJSON` and other user code is never called, and a throwing -getter/Proxy yields `"[Unreadable]"` for that value (one unreadable attribute never costs its siblings or the -span). Covered by example tests, fast-check properties (`attribute-value.fuzz.test.ts`) and a real -`sdk-trace@3` test. +| string / boolean / number | unchanged (string capped at 32 KiB) | `stringValue` / `boolValue` / `intValue` or `doubleValue` | +| homogeneous scalar array | unchanged | unchanged; OTLP: JSON `stringValue` (existing behaviour) | +| nested map, mixed/nested array | bounded tree (redactable) | one bounded JSON string | +| byte array | base64 string | string; `toAnyValue`: `bytesValue` (base64, bounded) | +| bigint | number if exact, else decimal string | `intValue` | +| null, undefined, function, symbol | dropped | dropped | + +*Bounds and totality.* Never throws, and bounded in WORK, not only output: every string leaf and key is cut at +8128 characters before it is copied, a tree stops at 1024 visited nodes or 32768 copied characters (the rest is +`"[Truncated]"`), 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. Known limit: `Object.keys` on a plain object with millions of +keys still allocates its key list before the node budget stops the copy. + +**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), so nested +`context.with` spans on it come out parented to the root only. --- diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index e6acafb39..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/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 3.x). 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 cbc08e8de..68a215cf0 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -53,7 +53,7 @@ "peerDependencies": { "@opentelemetry/api": ">=1.0.0", "@opentelemetry/sdk-trace-base": ">=1.0.0 <3", - "@opentelemetry/sdk-trace": ">=3", + "@opentelemetry/sdk-trace": ">=2.9.0", "react": ">=18" }, "peerDependenciesMeta": { @@ -73,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.ts b/packages/nextjs/src/otel-provider.ts index cfdc76a64..058f8f698 100644 --- a/packages/nextjs/src/otel-provider.ts +++ b/packages/nextjs/src/otel-provider.ts @@ -41,7 +41,7 @@ export interface AttachOtelProviderOptions { load?: () => Promise; } -/** A provider class: `BasicTracerProvider` (sdk-trace-base 1.x/2.x) or `TracerProvider` (sdk-trace 3.x). */ +/** 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. */ @@ -49,13 +49,13 @@ export interface OtelImporters { api(): Promise<{ trace: { setGlobalTracerProvider(provider: never): boolean } }>; /** OTel JS 1.x/2.x. */ sdkTraceBase(): Promise<{ BasicTracerProvider?: ProviderCtor }>; - /** OTel JS 3.x (which removed `sdk-trace-base` and renamed `BasicTracerProvider` to `TracerProvider`). */ + /** 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` (OTel 3.x). `undefined` when `@opentelemetry/api` or every + * 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( diff --git a/packages/opentelemetry/README.md b/packages/opentelemetry/README.md index 6ff342bcc..381317b72 100644 --- a/packages/opentelemetry/README.md +++ b/packages/opentelemetry/README.md @@ -15,7 +15,7 @@ Consuming spans also needs your own OpenTelemetry SDK, all optional peers of thi | 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 replaced `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 diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index ebe2549f2..717f4e773 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -34,12 +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 <3", - "@opentelemetry/sdk-trace": ">=3" + "@opentelemetry/sdk-trace": ">=2.9.0" }, "peerDependenciesMeta": { "@opentelemetry/api": { 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/attribute-value.ts b/packages/opentelemetry/src/attribute-value.ts deleted file mode 100644 index 711a44863..000000000 --- a/packages/opentelemetry/src/attribute-value.ts +++ /dev/null @@ -1,239 +0,0 @@ -// Complex attribute values (OpenTelemetry API 1.10 `AnyValue`, OTEP 4485). -// -// Before 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: it now also carries nested maps, arrays of mixed values, byte arrays -// and null, and (verified against sdk-trace@3.0.0) the SDK keeps all of them on `ReadableSpan.attributes` -// while dropping bigint/Date/function/symbol/cyclic values itself. A third-party or older SDK can still hand -// us anything at all, and `onEnd` runs inside the customer's `span.end()`. -// -// DECISION (the Bugsee attribute model is flat and its redaction runs on strings): -// - scalars, and homogeneous arrays of scalars, pass through UNCHANGED (a bigint, which JSON cannot carry, -// becomes a number when exact and decimal text otherwise); -// - everything else becomes ONE JSON STRING (a byte array becomes base64), bounded in depth, node count and -// length, and never throwing; -// - null/undefined/function/symbol have no value: the attribute is dropped. -// A string, not a nested object, because the span sanitizer/filter and the viewer all read attribute values -// as scalars: a `db.statement` that arrives as `{ text: 'SELECT ...' }` would otherwise sail past a -// string-keyed scrub. Flattening to dotted keys was rejected (key explosion, and arrays have no stable key -// form); dropping was rejected (silent data loss for the very attributes 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 serialized; 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 JSON (bounded) route. */ -export const MAX_ATTRIBUTE_ARRAY_LENGTH = 1024; -/** Appended when the JSON text had to be cut. */ -export const TRUNCATION_MARKER = '...[truncated]'; - -const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -/** RFC 4648 base64 with padding. Hand-rolled: `btoa`/`Buffer` are runtime-specific and this package 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) + - 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; -} - -/** OTLP AnyValue bytes: a `Uint8Array` (a Node `Buffer` is one). Other typed arrays are not AnyValue. */ -export function isByteArray(value: unknown): value is Uint8Array { - return value instanceof Uint8Array; -} - -const capText = (text: string): string => - text.length <= MAX_ATTRIBUTE_JSON_LENGTH - ? text - : text.slice(0, MAX_ATTRIBUTE_JSON_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER; - -/** 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; - -/** Base64 of a byte array, bounded (encodes at most what could fit, then cuts with the marker). */ -const boundedBase64 = (bytes: Uint8Array): string => - capText( - bytesToBase64(bytes.length > MAX_BYTES_ENCODED ? bytes.subarray(0, MAX_BYTES_ENCODED) : bytes), - ); - -const SKIP = Symbol('skip'); - -interface Budget { - nodes: number; -} - -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, - }); -}; - -/** Copy a value into a tree containing only JSON-safe values, within the depth/node budget. */ -function toSafe(value: unknown, depth: number, budget: Budget, ancestors: Set): unknown { - if (value === null) return null; - switch (typeof value) { - case 'string': - return value; - case 'boolean': - return value; - case 'number': - if (Number.isFinite(value)) return value; - return Number.isNaN(value) ? 'NaN' : value > 0 ? 'Infinity' : '-Infinity'; - case 'bigint': - return value.toString(); - case 'object': - break; - default: - return SKIP; // undefined, function, symbol - } - if (isByteArray(value)) return boundedBase64(value); - if (value instanceof Date) { - const time = value.getTime(); - return Number.isNaN(time) ? null : new Date(time).toISOString(); - } - if (depth >= MAX_ATTRIBUTE_DEPTH) return '[MaxDepth]'; - if (ancestors.has(value)) return '[Circular]'; - ancestors.add(value); - try { - if (Array.isArray(value)) return arrayToSafe(value, depth, budget, ancestors); - return objectToSafe(value as Record, depth, budget, ancestors); - } catch { - return '[Unreadable]'; - } finally { - ancestors.delete(value); - } -} - -function arrayToSafe( - items: unknown[], - depth: number, - budget: Budget, - ancestors: Set, -): unknown[] { - const out: unknown[] = []; - budget.nodes++; - for (let i = 0; i < items.length; i++) { - if (budget.nodes >= MAX_ATTRIBUTE_NODES) { - out.push('[Truncated]'); - break; - } - budget.nodes++; - 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 = {}; - budget.nodes++; - for (const key of Object.keys(source)) { - if (budget.nodes >= MAX_ATTRIBUTE_NODES) { - setOwn(out, '[Truncated]', true); - break; - } - budget.nodes++; - let member: unknown; - try { - member = toSafe(source[key], depth + 1, budget, ancestors); - } catch { - member = '[Unreadable]'; - } - if (member !== SKIP) setOwn(out, key, member); - } - return out; -} - -/** - * The JSON text of an AnyValue, bounded and never throwing. Byte arrays become base64, bigints decimal - * strings, non-finite numbers the OTLP spellings; a cycle, over-deep or over-wide structure is marked, not - * followed. Returns `undefined` when the value has no JSON form at all (undefined/function/symbol). - */ -export function stringifyAnyValue(value: unknown): string | undefined { - let safe: unknown; - try { - safe = toSafe(value, 0, { nodes: 0 }, new Set()); - } catch { - safe = '[Unreadable]'; - } - if (safe === SKIP) return undefined; - return capText(JSON.stringify(safe)); -} - -const isScalar = (v: unknown): v is string | number | boolean => - typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'; - -/** A non-empty-or-empty array whose elements are all strings, all numbers or all booleans (the pre-1.10 shape). */ -function isHomogeneousScalarArray(value: unknown[]): boolean { - if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return false; - if (value.length === 0) return true; - const kind = typeof value[0]; - if (!isScalar(value[0])) return false; - return value.every((item) => typeof item === kind); -} - -/** - * Normalize one OTel attribute value for the Bugsee attribute model (see the decision at the top of this - * file). `undefined` means the attribute has no representation and is dropped. - */ -export function normalizeAttributeValue(value: unknown): unknown { - if (value === null || value === undefined) return undefined; - if (isScalar(value)) return value; - // A bigint is not JSON-serializable (the transaction is, later): exact as a number when safe, else decimal text. - if (typeof value === 'bigint') { - return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) - ? Number(value) - : value.toString(); - } - if (isByteArray(value)) return boundedBase64(value); - if (Array.isArray(value) && isHomogeneousScalarArray(value)) return value; - return stringifyAnyValue(value); -} - -/** - * Normalize an OTel attributes record: own enumerable string keys only, each value normalized, an attribute - * whose value cannot be read (a throwing getter) skipped without losing its siblings. - */ -export function normalizeAttributes(attributes: Record): Record { - const out: Record = {}; - for (const key of Object.keys(attributes)) { - try { - const value = normalizeAttributeValue(attributes[key]); - if (value !== undefined) setOwn(out, key, value); - } catch { - // unreadable attribute: skip it, keep the rest - } - } - return out; -} diff --git a/packages/opentelemetry/src/index.ts b/packages/opentelemetry/src/index.ts index 003c85f11..a8caf08fb 100644 --- a/packages/opentelemetry/src/index.ts +++ b/packages/opentelemetry/src/index.ts @@ -5,15 +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 './attribute-value'; +} 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/span-processor.test.ts b/packages/opentelemetry/src/span-processor.test.ts index 24d284e3d..fe93932c3 100644 --- a/packages/opentelemetry/src/span-processor.test.ts +++ b/packages/opentelemetry/src/span-processor.test.ts @@ -59,7 +59,7 @@ describe('readableSpanToConsumed', () => { }); describe('complex attribute values (OTel API 1.10 AnyValue)', () => { - it('turns a nested map, a mixed array and a byte array into strings and keeps scalars as they are', () => { + 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: { @@ -76,8 +76,8 @@ describe('readableSpanToConsumed', () => { s: 'x', n: 3, tags: ['a', 'b'], - map: '{"a":{"b":[1,"x"]}}', - mixed: '[1,"a",true]', + map: { a: { b: [1, 'x'] } }, + mixed: [1, 'a', true], bytes: 'Zm9v', }); }); @@ -102,8 +102,8 @@ describe('readableSpanToConsumed', () => { }; const consumed = readableSpanToConsumed(readable({ attributes })); expect(consumed.attributes).toEqual({ - cyc: '{"a":1,"self":"[Circular]"}', - big: '{"n":"10"}', + cyc: { a: 1, self: '[Circular]' }, + big: { n: '10' }, after: 'still here', }); }); @@ -112,14 +112,14 @@ describe('readableSpanToConsumed', () => { const consumed = readableSpanToConsumed( readable({ attributes: { huge: { s: 'x'.repeat(1e6) } } }), ); - expect((consumed.attributes?.huge as string).length).toBeLessThanOrEqual(8192); + expect(JSON.stringify(consumed.attributes?.huge).length).toBeLessThanOrEqual(8192); }); - it('feeds a real transaction: the consumed attribute reaches the assembled transaction as a string', () => { + 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']).toBe('{"text":"SELECT 1"}'); + expect(txns[0]?.attributes?.['db.statement']).toEqual({ text: 'SELECT 1' }); }); }); @@ -174,17 +174,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 c1753a9e2..fb552fc74 100644 --- a/packages/opentelemetry/src/span-processor.ts +++ b/packages/opentelemetry/src/span-processor.ts @@ -1,6 +1,5 @@ import { neverThrow } from '@bugsee/core'; -import type { TransactionWire } from '@bugsee/performance'; -import { normalizeAttributes } from './attribute-value'; +import { normalizeAttributes, type TransactionWire } from '@bugsee/performance'; import type { ConsumedSpan } from './from-otlp'; import { createTraceAssembler } from './trace-assembler'; @@ -103,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 @@ -116,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 33077eed5..8a9cd8cce 100644 --- a/packages/opentelemetry/src/to-otlp.test.ts +++ b/packages/opentelemetry/src/to-otlp.test.ts @@ -69,7 +69,39 @@ describe('toAnyValue', () => { 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.endsWith('...[truncated]')).toBe(true); + expect(out.stringValue).toContain('...[truncated]'); + }); + it('caps a huge byte array (bytesValue is bounded like every other branch)', () => { + const out = toAnyValue(new Uint8Array(1_000_000)) as { bytesValue: string }; + expect(out.bytesValue.length).toBe(8192); + expect(out.bytesValue.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('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(); @@ -81,6 +113,84 @@ 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('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 6587c3627..ec8509c37 100644 --- a/packages/opentelemetry/src/to-otlp.ts +++ b/packages/opentelemetry/src/to-otlp.ts @@ -1,5 +1,10 @@ -import type { SpanStatus, TransactionWire } from '@bugsee/performance'; -import { bytesToBase64, isByteArray, stringifyAnyValue } from './attribute-value'; +import { + boundedBase64, + isByteArray, + type SpanStatus, + stringifyAnyValue, + type TransactionWire, +} from '@bugsee/performance'; import { OTLP_SPAN_FLAG_SAMPLED, type OtlpAnyValue, @@ -63,20 +68,56 @@ 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: { - if (isByteArray(value)) return { bytesValue: bytesToBase64(value) }; - // objects/arrays → bounded JSON string that cannot throw (cycles, bigint, depth); functions/symbols → dropped - const json = stringifyAnyValue(value); - return json !== undefined ? { stringValue: json } : undefined; + try { + if (isByteArray(value)) return { bytesValue: boundedBase64(value) }; + // objects/arrays → bounded JSON string that cannot throw (cycles, bigint, depth); functions/symbols → dropped + const json = stringifyAnyValue(value); + 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; @@ -140,7 +181,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, @@ -176,7 +217,7 @@ export function transactionToOtlpSpans(txn: TransactionWire): OtlpSpan[] { startTimeUnixNano: toUnixNanoString(s.startTimestampMs), endTimeUnixNano: toUnixNanoString(s.endTimestampMs ?? s.startTimestampMs), attributes: toKeyValues({ - ...s.attributes, + ...safeCopy(s.attributes), 'bugsee.operation': s.operation, 'bugsee.span.status': s.status, }), @@ -213,7 +254,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/opentelemetry/src/attribute-value.fuzz.test.ts b/packages/performance/src/attribute-value.fuzz.test.ts similarity index 69% rename from packages/opentelemetry/src/attribute-value.fuzz.test.ts rename to packages/performance/src/attribute-value.fuzz.test.ts index 390657d3f..49da66fdc 100644 --- a/packages/opentelemetry/src/attribute-value.fuzz.test.ts +++ b/packages/performance/src/attribute-value.fuzz.test.ts @@ -1,15 +1,16 @@ 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'; -import { readableSpanToConsumed } from './span-processor'; -import { toAnyValue, toKeyValues } from './to-otlp'; /** * Property tests for complex attribute values (OTel API 1.10 AnyValue). `onEnd` runs inside the customer's @@ -116,22 +117,22 @@ describe('stringifyAnyValue (fuzz)', () => { }); }); +const jsonLength = (value: unknown): number => JSON.stringify(value)?.length ?? 0; + describe('normalizeAttributeValue (fuzz)', () => { - it('returns a scalar, a homogeneous scalar array, a bounded string, or nothing', () => { + 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') { - // A string input is passed through untouched; any other input is bounded. - if (typeof value !== 'string') - expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); return; } - if (Array.isArray(out)) { - const kinds = new Set(out.map((v) => typeof v)); - expect(kinds.size).toBeLessThanOrEqual(1); - for (const kind of kinds) expect(['string', 'number', 'boolean']).toContain(kind); + 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); @@ -140,15 +141,15 @@ describe('normalizeAttributeValue (fuzz)', () => { ); }); - it('leaves every scalar and every homogeneous scalar array untouched', () => { - const scalar = fc.oneof(fc.string(), fc.boolean(), fc.double(), fc.integer()); + 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: 50 }), + fc.array(fc.string({ maxLength: 20 }), { maxLength: 50 }), fc.array(fc.boolean(), { maxLength: 50 }), fc.array(fc.double(), { maxLength: 50 }), ]; @@ -162,44 +163,39 @@ describe('normalizeAttributeValue (fuzz)', () => { }); }); -describe('the OTLP and consume mappings accept any attribute value (fuzz)', () => { - it('toAnyValue never throws and its result survives JSON serialization', () => { +describe('flattenAttributes (fuzz)', () => { + it('always yields scalars, small scalar arrays or bounded strings, and is JSON-serializable', () => { fc.assert( - fc.property(anyValue, (value) => { - const out = toAnyValue(value); - if (out === undefined) return; - expect(JSON.parse(JSON.stringify(out))).toEqual(out); + 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: 400 }, + { numRuns: 200 }, ); }); - it('toKeyValues and readableSpanToConsumed keep working with an exotic value among the attributes', () => { + it('is idempotent', () => { 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.parse(JSON.stringify(consumed.attributes))).toBeDefined(); + fc.property(fc.dictionary(fc.string({ maxLength: 8 }), anyValue, { maxKeys: 8 }), (attrs) => { + const once = flattenAttributes(attrs); + expect(flattenAttributes(once)).toEqual(once); }), - { numRuns: 300 }, + { numRuns: 100 }, ); }); +}); - it('normalizeAttributes output is always JSON-serializable', () => { +describe('normalizeAttributes (fuzz)', () => { + it('output is always JSON-serializable', () => { fc.assert( fc.property(fc.dictionary(fc.string({ maxLength: 8 }), anyValue, { maxKeys: 8 }), (attrs) => { - const out = normalizeAttributes(attrs); - expect(() => JSON.stringify(out)).not.toThrow(); + expect(() => JSON.stringify(normalizeAttributes(attrs))).not.toThrow(); }), { numRuns: 200 }, ); diff --git a/packages/opentelemetry/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts similarity index 58% rename from packages/opentelemetry/src/attribute-value.test.ts rename to packages/performance/src/attribute-value.test.ts index 32ffabd44..14504c7e4 100644 --- a/packages/opentelemetry/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -1,12 +1,18 @@ import { describe, expect, it } 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'; @@ -134,16 +140,74 @@ describe('stringifyAnyValue', () => { expect(Object.keys(parsed).length).toBeLessThan(MAX_ATTRIBUTE_NODES / 3); }); - it('caps the output length and ends with the truncation marker', () => { + it('caps the output length and marks the cut', () => { const out = stringifyAnyValue({ big: 'x'.repeat(50_000) }) as string; expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_JSON_LENGTH); - expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + expect(out).toContain(TRUNCATION_MARKER); expect(out.startsWith('{"big":"xxx')).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', () => { - const exact = 'y'.repeat(MAX_ATTRIBUTE_JSON_LENGTH - 2); // the two quotes make it exactly the cap - expect(stringifyAnyValue(exact)).toBe(JSON.stringify(exact)); + // `["",""]` 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 = 'x'.repeat(64 * 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 = 'x'.repeat(1_000_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', () => { @@ -219,26 +283,49 @@ describe('normalizeAttributeValue', () => { expect(normalizeAttributeValue(empty)).toBe(empty); }); - it('turns a mixed array, an array with null, or a nested array into a JSON string', () => { - expect(normalizeAttributeValue([1, 'a', true])).toBe('[1,"a",true]'); - expect(normalizeAttributeValue(['a', null])).toBe('["a",null]'); - expect(normalizeAttributeValue([[1], [2]])).toBe('[[1],[2]]'); + 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('turns a primitive array past the length cap into a (truncated) JSON string', () => { + 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); - expect(typeof out).toBe('string'); + 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)).toBe(atCap); }); - it('turns an object into a JSON string and a byte array into a base64 string', () => { - expect(normalizeAttributeValue({ a: { b: [1, 'x'] } })).toBe('{"a":{"b":[1,"x"]}}'); + 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 = 'x'.repeat(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).not.toBe(big); + const small = [ + 'a'.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 2), + 'b'.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 2), + ]; + expect(normalizeAttributeValue(small)).toBe(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(); @@ -267,7 +354,7 @@ describe('normalizeAttributes', () => { und: undefined, fn: () => 1, }), - ).toEqual({ s: 'x', n: 3, tags: ['a', 'b'], obj: '{"k":1}', mixed: '[1,"a"]', bytes: 'AQ==' }); + ).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', () => { @@ -289,9 +376,87 @@ describe('normalizeAttributes', () => { 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('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)).toBe(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, tags: ['a', 'b'] }; + 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..45df16573 --- /dev/null +++ b/packages/performance/src/attribute-value.ts @@ -0,0 +1,328 @@ +// 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; +} + +/** OTLP AnyValue bytes: a `Uint8Array` (a Node `Buffer` is one). Other typed arrays are not AnyValue. */ +export function isByteArray(value: unknown): value is Uint8Array { + return value instanceof Uint8Array; +} + +const capText = (text: string, max: number): string => + text.length <= max ? text : text.slice(0, max - TRUNCATION_MARKER.length) + TRUNCATION_MARKER; + +/** 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; + +/** 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'); + +interface Budget { + nodes: number; + chars: number; +} + +const exhausted = (budget: Budget): boolean => + budget.nodes >= MAX_ATTRIBUTE_NODES || budget.chars >= MAX_ATTRIBUTE_TREE_CHARS; + +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): string { + const cut = capText(text, MAX_LEAF_LENGTH); + budget.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 value.toString(); + case 'object': + break; + default: + return SKIP; // undefined, function, symbol + } + if (isByteArray(value)) return leafText(boundedBase64(value), budget); + if (value instanceof Date) { + const time = value.getTime(); + return Number.isNaN(time) ? null : new Date(time).toISOString(); + } + if (depth >= MAX_ATTRIBUTE_DEPTH) return '[MaxDepth]'; + 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[] = []; + budget.nodes++; + for (let i = 0; i < items.length; i++) { + if (exhausted(budget)) { + out.push('[Truncated]'); + break; + } + budget.nodes++; + 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 = {}; + budget.nodes++; + for (const key of Object.keys(source)) { + if (exhausted(budget)) { + setOwn(out, '[Truncated]', true); + break; + } + budget.nodes++; + let member: unknown; + 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): unknown { + let safe: unknown; + try { + safe = toSafe(value, 0, { nodes: 0, chars: 0 }, 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'; + +/** An array whose elements are all strings, all numbers or all booleans (the pre-1.10 shape), and small. */ +function isPassThroughArray(value: unknown[]): boolean { + if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return false; + if (value.length === 0) return true; + const kind = typeof value[0]; + if (!isScalar(value[0])) return false; + let chars = 0; + for (const item of value) { + if (typeof item !== kind) return false; + if (typeof item === 'string') { + chars += item.length; + if (chars > MAX_ATTRIBUTE_STRING_LENGTH) return false; + } + } + return true; +} + +/** + * 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): unknown { + if (value === null || value === undefined) return undefined; + 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 value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) + ? Number(value) + : value.toString(); + } + if (isByteArray(value)) return boundedBase64(value); + if (Array.isArray(value) && isPassThroughArray(value)) return value; + return safeAnyValue(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): 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]); + 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): unknown { + const normal = normalizeAttributeValue(value); + 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 when nothing needed changing. */ +export function flattenAttributes(attributes: Record): Record { + 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); + 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..1aff4cb0f 100644 --- a/packages/performance/src/extension.test.ts +++ b/packages/performance/src/extension.test.ts @@ -270,6 +270,72 @@ 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"]}'); + }); +}); + // `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..f39a18555 100644 --- a/packages/performance/src/extension.ts +++ b/packages/performance/src/extension.ts @@ -14,6 +14,7 @@ import { createPerformanceController, type PerformanceApi } from './controller'; import { stampDeviceIdOnWire } from './device-id-attribute'; import type { TransactionWire } from './span'; import { applySpanFilter } from './span-filter'; +import { flattenTransactionAttributes } from './transaction-attributes'; import { createTransactionStore, type TransactionStore } from './transaction-store'; // The @bugsee/performance extension shell. There is no addExtension lifecycle on the @@ -113,13 +114,17 @@ export function createPerformanceExtension( options.deviceId === undefined ? transaction : stampDeviceIdOnWire(transaction, options.deviceId); - const filterTransaction = (transaction: TransactionWire): TransactionWire | null => - applySpanFilter( + const filterTransaction = (transaction: TransactionWire): TransactionWire | null => { + const filtered = applySpanFilter( stampDeviceId(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..6ab10e8f8 100644 --- a/packages/performance/src/index.ts +++ b/packages/performance/src/index.ts @@ -7,6 +7,24 @@ // 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 { + boundedBase64, + bytesToBase64, + flattenAttributes, + flattenAttributeValue, + isByteArray, + 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'; 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..12d45b7df 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -113,3 +113,76 @@ 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 }); + }); +}); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index a92d869c1..b2f8d5848 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). @@ -68,6 +68,63 @@ 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): unknown { + if (typeof value === 'string') { + return redactShapes(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); + 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); + if (next !== member) changed = true; + out[key] = next; + } + return changed ? out : value; +} + +function sanitizeMember(key: string, value: unknown, depth: number): unknown { + if (STATEMENT_KEYS.has(key) && typeof value === 'string') { + return redactSqlLiterals(value); + } + if (CONTENT_KEYS.has(key) || isSensitiveKey(key)) { + return REDACTED; + } + return sanitizeNested(value, depth + 1); +} + 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') { @@ -85,5 +142,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..0fbb57d29 --- /dev/null +++ b/packages/performance/src/transaction-attributes.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest'; +import type { TransactionWire } from './span'; +import { flattenTransactionAttributes } 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 the SAME transaction when no attribute is complex (the common path copies nothing)', () => { + const plain = txn({ attributes: { a: 1, tags: ['x'] }, 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}' }); + }); +}); diff --git a/packages/performance/src/transaction-attributes.ts b/packages/performance/src/transaction-attributes.ts new file mode 100644 index 000000000..b21906f17 --- /dev/null +++ b/packages/performance/src/transaction-attributes.ts @@ -0,0 +1,22 @@ +import { flattenAttributes } 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, when nothing was complex, so the default path copies nothing. + */ +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 }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d4706b573..0cd998fa9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -904,9 +904,6 @@ importers: '@bugsee/vercel-edge': specifier: workspace:* version: link:../vercel-edge - '@opentelemetry/sdk-trace': - specifier: '>=3' - version: 3.0.0(@opentelemetry/api@1.9.1) devDependencies: '@bugsee/node': specifier: workspace:* @@ -914,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) @@ -1042,13 +1042,13 @@ importers: '@bugsee/performance': specifier: workspace:* version: link:../performance - '@opentelemetry/sdk-trace': - specifier: '>=3' - version: 3.0.0(@opentelemetry/api@1.9.1) devDependencies: '@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) @@ -13324,11 +13324,6 @@ snapshots: '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/core@3.0.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -13341,12 +13336,6 @@ snapshots: '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@3.0.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -13369,13 +13358,6 @@ snapshots: '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-trace@3.0.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/semantic-conventions@1.43.0': {} '@oslojs/encoding@1.1.0': {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 1c36d3d8a..2ce82d351 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -21,10 +21,3 @@ allowBuilds: minimumReleaseAgeExclude: - '@bugsee/bugsee-cli@0.7.11' - # OpenTelemetry JS 3.0 GA (2026-10-20): the lockfile pins these inside the minimum-release-age window, and a - # frozen install rejects them without an exclusion. Remove these four lines once the versions are a day old - # (the policy then accepts them on its own). - - '@opentelemetry/api@1.10.0' - - '@opentelemetry/core@3.0.0' - - '@opentelemetry/resources@3.0.0' - - '@opentelemetry/sdk-trace@3.0.0' 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"], From 3331ef878071e4bfa0a7f6155e548dbc58ffdcac Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 05:36:52 +0500 Subject: [PATCH 08/16] fix(performance,opentelemetry): null-tolerant scalar arrays, GenAI content keys, deliberate non-plain values, doc corrections (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - homogeneous scalar arrays with null entries pass through again; nested bigint matches top-level - redact gen_ai.input/output.messages, system_instructions, tool.* content by default - URL (credentials removed), Error (name+message), Date, ArrayBuffer/DataView/cross-realm bytes - toAnyValue: Date/URL as plain strings, invalid Date dropped - tests for the byte pre-encode bound and the object node boundary - reword the Node matrix, peer-range and bytesValue claims; note the zero-config context manager 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 4 +- dev-packages/otel3-compat/src/node-gate.ts | 5 +- docs/design/opentelemetry-integration.md | 27 ++++-- .../opentelemetry/src/span-processor.test.ts | 2 +- packages/opentelemetry/src/to-otlp.test.ts | 19 +++- packages/opentelemetry/src/to-otlp.ts | 14 ++- .../performance/src/attribute-value.test.ts | 88 ++++++++++++++++++- packages/performance/src/attribute-value.ts | 84 ++++++++++++++---- packages/performance/src/index.ts | 2 +- .../performance/src/span-sanitizer.test.ts | 16 ++++ packages/performance/src/span-sanitizer.ts | 8 ++ 11 files changed, 228 insertions(+), 41 deletions(-) diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md index 11438ed86..8b05b0973 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -5,9 +5,9 @@ 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` (the class was renamed from `BasicTracerProvider`). 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. +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. 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). On OTLP export a byte array is sent as `bytesValue` (base64), and one hostile attribute (a Proxy that throws, a cycle, an enormous string) no longer rejects the whole export batch. +Complex span attributes (OpenTelemetry API 1.10 `AnyValue`) are now handled deliberately. 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` (base64); 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()`. diff --git a/dev-packages/otel3-compat/src/node-gate.ts b/dev-packages/otel3-compat/src/node-gate.ts index 3e9cee4ae..9b3dd90c6 100644 --- a/dev-packages/otel3-compat/src/node-gate.ts +++ b/dev-packages/otel3-compat/src/node-gate.ts @@ -1,5 +1,6 @@ -// OpenTelemetry JS 3.x declares `engines.node >=22.15.0` on core / resources / sdk-trace. The repo's CI matrix -// is Node 18-24, so the OTel 3 suites must stand down below that floor instead of failing the old legs. +// 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; diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 0c161d96d..77a75a9ae 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -190,17 +190,20 @@ Guard: `dev-packages/packaging-guard/src/otel-peers.test.ts`. `>=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`), so a customer is bound only by their own SDK's peer range. +`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 Node 18+ (it never loads -OTel); the OTel 3 suite is meant to run on the 22/24 legs of the 18-24 matrix only. It skips below 22.15 with a stated -reason, unless `BUGSEE_REQUIRE_OTEL3=1` (set on the CI Node 22 job, passed through turbo `test:unit` env), which +`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 2.x, but the class was renamed from -`BasicTracerProvider` (which no longer exists), and `addSpanProcessor` has been gone since 2.0. There is no +`@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`. @@ -272,15 +275,21 @@ encoded only up to what could fit, a non-byte typed array (a Float32Array embedd 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. Known limit: `Object.keys` on a plain object with millions of +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. **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), so nested -`context.with` spans on it come out parented to the root only. +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. --- diff --git a/packages/opentelemetry/src/span-processor.test.ts b/packages/opentelemetry/src/span-processor.test.ts index fe93932c3..bf931a95c 100644 --- a/packages/opentelemetry/src/span-processor.test.ts +++ b/packages/opentelemetry/src/span-processor.test.ts @@ -103,7 +103,7 @@ describe('readableSpanToConsumed', () => { const consumed = readableSpanToConsumed(readable({ attributes })); expect(consumed.attributes).toEqual({ cyc: { a: 1, self: '[Circular]' }, - big: { n: '10' }, + big: { n: 10 }, after: 'still here', }); }); diff --git a/packages/opentelemetry/src/to-otlp.test.ts b/packages/opentelemetry/src/to-otlp.test.ts index 8a9cd8cce..a5333c7b9 100644 --- a/packages/opentelemetry/src/to-otlp.test.ts +++ b/packages/opentelemetry/src/to-otlp.test.ts @@ -32,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' }); @@ -63,7 +65,7 @@ describe('toAnyValue', () => { 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({ 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', () => { @@ -87,6 +89,21 @@ describe('toAnyValue', () => { 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( {}, diff --git a/packages/opentelemetry/src/to-otlp.ts b/packages/opentelemetry/src/to-otlp.ts index ec8509c37..e711029cf 100644 --- a/packages/opentelemetry/src/to-otlp.ts +++ b/packages/opentelemetry/src/to-otlp.ts @@ -1,7 +1,8 @@ import { + asBytes, boundedBase64, - isByteArray, type SpanStatus, + safeAnyValue, stringifyAnyValue, type TransactionWire, } from '@bugsee/performance'; @@ -69,9 +70,14 @@ export function toAnyValue(value: unknown): OtlpAnyValue | undefined { return Number.isSafeInteger(value) ? { intValue: String(value) } : toDoubleValue(value); default: { try { - if (isByteArray(value)) return { bytesValue: boundedBase64(value) }; - // objects/arrays → bounded JSON string that cannot throw (cycles, bigint, depth); functions/symbols → dropped - const json = stringifyAnyValue(value); + const bytes = asBytes(value); + if (bytes !== undefined) return { bytesValue: boundedBase64(bytes) }; + // 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 diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index 14504c7e4..c38f9a0ee 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { boundedBase64, bytesToBase64, @@ -68,8 +68,12 @@ describe('stringifyAnyValue', () => { expect(stringifyAnyValue([nodeBuffer.from('hi')])).toBe('["aGk="]'); }); - it('keeps a bigint exact as a decimal string (JSON.stringify would throw)', () => { + 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)', () => { @@ -260,6 +264,51 @@ describe('stringifyAnyValue', () => { }); }); +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]) { @@ -289,6 +338,17 @@ describe('normalizeAttributeValue', () => { expect(normalizeAttributeValue([[1], [2]])).toEqual([[1], [2]]); }); + it('passes a homogeneous scalar array that contains null/undefined entries through unchanged', () => { + const withNull = ['a', null, 'b']; + const nums = [1, undefined, 3]; + expect(normalizeAttributeValue(withNull)).toBe(withNull); + expect(normalizeAttributeValue(nums)).toBe(nums); + expect(flattenAttributeValue(withNull)).toBe(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.toBe(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[]; @@ -395,6 +455,30 @@ describe('normalizeAttributes', () => { }); }); +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]'); + }); +}); + describe('boundedBase64', () => { it('encodes small arrays whole and cuts a huge one with the marker', () => { expect(boundedBase64(new Uint8Array([102, 111, 111]))).toBe('Zm9v'); diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts index 45df16573..084de7369 100644 --- a/packages/performance/src/attribute-value.ts +++ b/packages/performance/src/attribute-value.ts @@ -65,17 +65,30 @@ export function bytesToBase64(bytes: Uint8Array): string { return out; } -/** OTLP AnyValue bytes: a `Uint8Array` (a Node `Buffer` is one). Other typed arrays are not AnyValue. */ -export function isByteArray(value: unknown): value is Uint8Array { - return value instanceof Uint8Array; +/** 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; } const capText = (text: string, max: number): string => text.length <= max ? text : text.slice(0, max - TRUNCATION_MARKER.length) + TRUNCATION_MARKER; -/** 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; - /** 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; @@ -84,6 +97,23 @@ export function boundedBase64(bytes: Uint8Array): string { const SKIP = Symbol('skip'); +/** 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; @@ -121,17 +151,33 @@ function toSafe(value: unknown, depth: number, budget: Budget, ancestors: Set 0 ? 'Infinity' : '-Infinity'; case 'bigint': - return value.toString(); + return bigintToJson(value); case 'object': break; default: return SKIP; // undefined, function, symbol } - if (isByteArray(value)) return leafText(boundedBase64(value), budget); + const bytes = asBytes(value); + if (bytes !== undefined) return leafText(boundedBase64(bytes), budget); 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 (ancestors.has(value)) return '[Circular]'; ancestors.add(value); @@ -232,14 +278,16 @@ export function stringifyAnyValue(value: unknown): string | undefined { const isScalar = (v: unknown): v is string | number | boolean => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'; -/** An array whose elements are all strings, all numbers or all booleans (the pre-1.10 shape), and small. */ +/** An array whose non-null elements are all strings, all numbers or all booleans (the pre-1.10 shape), and small. */ function isPassThroughArray(value: unknown[]): boolean { if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return false; - if (value.length === 0) return true; - const kind = typeof value[0]; - if (!isScalar(value[0])) return false; + let kind: string | undefined; let chars = 0; for (const item of value) { + // 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 false; + kind ??= typeof item; if (typeof item !== kind) return false; if (typeof item === 'string') { chars += item.length; @@ -260,14 +308,12 @@ export function normalizeAttributeValue(value: unknown): unknown { if (value === null || value === undefined) return undefined; 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 value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) - ? Number(value) - : value.toString(); - } - if (isByteArray(value)) return boundedBase64(value); + if (typeof value === 'bigint') return bigintToJson(value); + const bytes = asBytes(value); + if (bytes !== undefined) return boundedBase64(bytes); if (Array.isArray(value) && isPassThroughArray(value)) return value; - return safeAnyValue(value); + const safe = safeAnyValue(value); + return safe === null ? undefined : safe; // an invalid Date: no value } /** diff --git a/packages/performance/src/index.ts b/packages/performance/src/index.ts index 6ab10e8f8..55569e5f3 100644 --- a/packages/performance/src/index.ts +++ b/packages/performance/src/index.ts @@ -8,11 +8,11 @@ export { type ActiveSpanStore, createSingleSlotActiveSpanStore } from './active-span-store'; export { + asBytes, boundedBase64, bytesToBase64, flattenAttributes, flattenAttributeValue, - isByteArray, MAX_ATTRIBUTE_ARRAY_LENGTH, MAX_ATTRIBUTE_DEPTH, MAX_ATTRIBUTE_JSON_LENGTH, diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 12d45b7df..e7ff4188c 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -186,3 +186,19 @@ describe('sanitizeSpan on nested (AnyValue) attributes', () => { 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 }); + }); +}); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index b2f8d5848..c549db07a 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -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', From 069ae8f181368ec188ad9f3b71fb04b629f970fd Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 06:48:19 +0500 Subject: [PATCH 09/16] fix(performance,protocol): bound attributes of every span before redaction, per-span budget, truncated-key and statement-map redaction (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - normalizeTransactionAttributes runs first in filterTransaction, so the SDK's own raw setAttribute/recordChildSpan/recordExternal values (cycles, DAGs, throwing getters, node:http objects) are bounded before the redaction walk and any integrator filter - shared per-span node and character budget - a key too long to keep has its value redacted (a cut could drop 'password') - string leaves under a statement key given as a map/array get literals redacted - isSensitiveKey normalises its denylist once - docs and changeset aligned; prune non-needed exports 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 5 +- docs/PROGRESS.md | 4 +- docs/design/opentelemetry-integration.md | 25 ++++-- .../performance/src/attribute-value.test.ts | 17 ++++ packages/performance/src/attribute-value.ts | 82 ++++++++++++++---- packages/performance/src/extension.test.ts | 84 ++++++++++++++++++ packages/performance/src/extension.ts | 9 +- packages/performance/src/index.ts | 4 - .../performance/src/span-sanitizer.test.ts | 25 ++++++ packages/performance/src/span-sanitizer.ts | 29 ++++--- .../src/transaction-attributes.test.ts | 86 ++++++++++++++++++- .../performance/src/transaction-attributes.ts | 43 +++++++++- packages/protocol/src/sensitive.ts | 11 ++- 13 files changed, 379 insertions(+), 45 deletions(-) diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md index 8b05b0973..8fc26370f 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -1,6 +1,7 @@ --- '@bugsee/opentelemetry': minor '@bugsee/performance': minor +'@bugsee/protocol': patch --- Support OpenTelemetry JS 3.x (issue #94). @@ -11,4 +12,6 @@ Complex span attributes (OpenTelemetry API 1.10 `AnyValue`) are now handled deli `createBugseeSpanProcessor` now ignores `onEnd` after `shutdown()`. -New exports from `@bugsee/performance` (also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue` and the `MAX_ATTRIBUTE_*` limits. +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, 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/performance` (some also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue`, `safeAnyValue`, `asBytes`, `boundedBase64` and the `MAX_ATTRIBUTE_*` limits. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index f2eafd505..61ffe68ec 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -609,8 +609,8 @@ its first consumer. Design references (Sentry/Faro/Datadog/Honeycomb/Embrace) in 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. Bounded in WORK (leaf, key and total-character budgets, typed - arrays read by index) and total (never throws; produce path drops one bad attribute, never the batch). Native + remains to bounded JSON strings at the wire. 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. diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 77a75a9ae..167d79a9d 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -233,6 +233,12 @@ 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, hostile getters contained) before the redaction walk or an integrator filter sees them. + 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 @@ -240,7 +246,10 @@ that need it sit below `@bugsee/opentelemetry`; the OTel package re-exports it). 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`, string leaves are scanned for secret shapes, depth-limited), so + 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 leaves INSIDE maps and arrays-of-maps only, + exactly as on main a top-level string attribute or a flat string array is not shape-scanned; 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): @@ -267,9 +276,11 @@ and a bounded JSON `stringValue` for maps/arrays. | bigint | number if exact, else decimal string | `intValue` | | null, undefined, function, symbol | dropped | dropped | -*Bounds and totality.* Never throws, and bounded in WORK, not only output: every string leaf and key is cut at -8128 characters before it is copied, a tree stops at 1024 visited nodes or 32768 copied characters (the rest is -`"[Truncated]"`), depth 8 (`"[MaxDepth]"`), the JSON text at 8192 characters (`...[truncated]`), cycles become +*Bounds and totality.* Never throws, and bounded in WORK per ATTRIBUTE and per SPAN: 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), 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 @@ -281,7 +292,11 @@ credentials removed, an Error its `name` and `message` (never the stack), a 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. +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 60 ms for a span. `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 diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index c38f9a0ee..efd1b27f1 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -479,6 +479,23 @@ describe('work bounds that output alone cannot show', () => { }); }); +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'); diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts index 084de7369..19ed80e18 100644 --- a/packages/performance/src/attribute-value.ts +++ b/packages/performance/src/attribute-value.ts @@ -1,3 +1,5 @@ +import { REDACTED } 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 @@ -97,6 +99,23 @@ export function boundedBase64(bytes: Uint8Array): string { 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) @@ -117,10 +136,20 @@ const UrlClass = (): 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.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. @@ -136,6 +165,7 @@ const setOwn = (target: Record, key: string, value: unknown): v function leafText(text: string, budget: Budget): string { const cut = capText(text, MAX_LEAF_LENGTH); budget.chars += cut.length; + if (budget.span !== undefined) budget.span.chars += cut.length; return cut; } @@ -179,6 +209,7 @@ function toSafe(value: unknown, depth: number, budget: Budget, ancestors: Set= MAX_ATTRIBUTE_DEPTH) return '[MaxDepth]'; + if (exhausted(budget)) return '[Truncated]'; if (ancestors.has(value)) return '[Circular]'; ancestors.add(value); try { @@ -202,13 +233,13 @@ function listToSafe( ancestors: Set, ): unknown[] { const out: unknown[] = []; - budget.nodes++; + countNode(budget); for (let i = 0; i < items.length; i++) { if (exhausted(budget)) { out.push('[Truncated]'); break; } - budget.nodes++; + countNode(budget); let item: unknown; try { item = toSafe(items[i], depth + 1, budget, ancestors); @@ -227,18 +258,24 @@ function objectToSafe( ancestors: Set, ): Record { const out: Record = {}; - budget.nodes++; + countNode(budget); for (const key of Object.keys(source)) { if (exhausted(budget)) { setOwn(out, '[Truncated]', true); break; } - budget.nodes++; + countNode(budget); let member: unknown; - try { - member = toSafe(source[key], depth + 1, budget, ancestors); - } catch { - member = '[Unreadable]'; + 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); } @@ -250,10 +287,15 @@ function objectToSafe( * (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): unknown { +export function safeAnyValue(value: unknown, span?: SpanBudget): unknown { let safe: unknown; try { - safe = toSafe(value, 0, { nodes: 0, chars: 0 }, new Set()); + safe = toSafe( + value, + 0, + { nodes: 0, chars: 0, ...(span !== undefined ? { span } : {}) }, + new Set(), + ); } catch { safe = '[Unreadable]'; } @@ -304,7 +346,7 @@ function isPassThroughArray(value: unknown[]): boolean { * base64; everything else becomes a bounded JSON-safe tree. `undefined` means no representation: the * attribute is dropped. */ -export function normalizeAttributeValue(value: unknown): unknown { +export function normalizeAttributeValue(value: unknown, span?: SpanBudget): unknown { if (value === null || value === undefined) return undefined; if (typeof value === 'string') return capText(value, MAX_ATTRIBUTE_STRING_LENGTH); if (typeof value === 'number' || typeof value === 'boolean') return value; @@ -312,7 +354,7 @@ export function normalizeAttributeValue(value: unknown): unknown { const bytes = asBytes(value); if (bytes !== undefined) return boundedBase64(bytes); if (Array.isArray(value) && isPassThroughArray(value)) return value; - const safe = safeAnyValue(value); + const safe = safeAnyValue(value, span); return safe === null ? undefined : safe; // an invalid Date: no value } @@ -321,7 +363,10 @@ export function normalizeAttributeValue(value: unknown): unknown { * 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): Record { +export function normalizeAttributes( + attributes: Record, + span: SpanBudget = createSpanBudget(), +): Record { const out: Record = {}; let keys: string[]; try { @@ -331,7 +376,7 @@ export function normalizeAttributes(attributes: Record): Record } for (const key of keys) { try { - const value = normalizeAttributeValue(attributes[key]); + const value = normalizeAttributeValue(attributes[key], span); if (value !== undefined) setOwn(out, key, value); } catch { // unreadable attribute: skip it, keep the rest @@ -344,14 +389,15 @@ export function normalizeAttributes(attributes: Record): Record * 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): unknown { - const normal = normalizeAttributeValue(value); +export function flattenAttributeValue(value: unknown, span?: SpanBudget): unknown { + 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 when nothing needed changing. */ export function flattenAttributes(attributes: Record): Record { + const span = createSpanBudget(); let changed = false; const out: Record = {}; let keys: string[]; @@ -363,7 +409,7 @@ export function flattenAttributes(attributes: Record): Record { + 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('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]' }); + }); +}); + // `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 f39a18555..d49d45ed3 100644 --- a/packages/performance/src/extension.ts +++ b/packages/performance/src/extension.ts @@ -14,7 +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 } from './transaction-attributes'; +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 @@ -116,7 +119,9 @@ export function createPerformanceExtension( : stampDeviceIdOnWire(transaction, options.deviceId); const filterTransaction = (transaction: TransactionWire): TransactionWire | null => { const filtered = applySpanFilter( - stampDeviceId(transaction), + // 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, diff --git a/packages/performance/src/index.ts b/packages/performance/src/index.ts index 55569e5f3..86f22748d 100644 --- a/packages/performance/src/index.ts +++ b/packages/performance/src/index.ts @@ -10,20 +10,16 @@ export { type ActiveSpanStore, createSingleSlotActiveSpanStore } from './active- export { asBytes, 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'; export { createPerformanceController, diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index e7ff4188c..c8bf41d04 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -202,3 +202,28 @@ describe('sanitizeSpan: current GenAI content conventions', () => { 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); + }); +}); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index c549db07a..a353a33c9 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -58,6 +58,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; @@ -94,9 +98,10 @@ const isComplex = (value: unknown): boolean => * 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): unknown { +function sanitizeNested(value: unknown, depth: number, statement = false): unknown { if (typeof value === 'string') { - return redactShapes(value); + // 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; @@ -107,7 +112,7 @@ function sanitizeNested(value: unknown, depth: number): unknown { if (Array.isArray(value)) { let changed = false; const items = value.map((item) => { - const next = sanitizeNested(item, depth + 1); + const next = sanitizeNested(item, depth + 1, statement); if (next !== item) changed = true; return next; }); @@ -116,27 +121,31 @@ function sanitizeNested(value: unknown, depth: number): unknown { let changed = false; const out: Record = Object.create(null); for (const [key, member] of Object.entries(value)) { - const next = sanitizeMember(key, member, depth); + 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): unknown { - if (STATEMENT_KEYS.has(key) && typeof value === 'string') { - return redactSqlLiterals(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); + 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)) { diff --git a/packages/performance/src/transaction-attributes.test.ts b/packages/performance/src/transaction-attributes.test.ts index 0fbb57d29..384f7f5a2 100644 --- a/packages/performance/src/transaction-attributes.test.ts +++ b/packages/performance/src/transaction-attributes.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest'; import type { TransactionWire } from './span'; -import { flattenTransactionAttributes } from './transaction-attributes'; +import { + flattenTransactionAttributes, + normalizeTransactionAttributes, +} from './transaction-attributes'; const txn = (over: Partial = {}): TransactionWire => ({ traceId: 't'.repeat(32), @@ -52,3 +55,84 @@ describe('flattenTransactionAttributes', () => { 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 the SAME 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)).toBe(plain); + const bare = txn(); + expect(normalizeTransactionAttributes(bare)).toBe(bare); + }); + + 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 index b21906f17..b507fd9ae 100644 --- a/packages/performance/src/transaction-attributes.ts +++ b/packages/performance/src/transaction-attributes.ts @@ -1,4 +1,4 @@ -import { flattenAttributes } from './attribute-value'; +import { flattenAttributes, normalizeAttributes } from './attribute-value'; import type { TransactionWire } from './span'; /** @@ -20,3 +20,44 @@ export function flattenTransactionAttributes(transaction: TransactionWire): Tran if (!changed) return transaction; return { ...transaction, ...(root !== undefined ? { attributes: root } : {}), spans }; } + +/** + * `normalizeAttributes`, but returning the SAME record when it was already normal (scalars and scalar arrays + * only, nothing dropped), so the common path copies nothing. A record whose keys or values cannot be read + * (a Proxy trap, a throwing getter) counts as changed and yields the normalized copy. + */ +function normalizedRecord(attributes: Record): Record { + const normal = normalizeAttributes(attributes); + try { + const keys = Object.keys(attributes); + const same = + keys.length === Object.keys(normal).length && + keys.every((key) => normal[key] === attributes[key]); + return same ? attributes : normal; + } catch { + return normal; + } +} + +/** + * 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. Returns the SAME transaction when nothing needed changing. + */ +export function normalizeTransactionAttributes(transaction: TransactionWire): TransactionWire { + const root = + transaction.attributes === undefined ? undefined : normalizedRecord(transaction.attributes); + let changed = root !== transaction.attributes; + const spans = transaction.spans.map((span) => { + if (span.attributes === undefined) return span; + const attributes = normalizedRecord(span.attributes); + if (attributes === span.attributes) return span; + changed = true; + return { ...span, attributes }; + }); + if (!changed) return transaction; + return { ...transaction, ...(root !== undefined ? { attributes: root } : {}), spans }; +} 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); From 519f4334a46e792c3a0f3005df19d6572049274b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 06:50:31 +0500 Subject: [PATCH 10/16] fix(opentelemetry): derive child span kind from the safe attribute copy; native-path size test (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- packages/opentelemetry/src/to-otlp.test.ts | 32 +++++++++++++++++ packages/opentelemetry/src/to-otlp.ts | 41 ++++++++++++---------- packages/performance/src/extension.test.ts | 19 ++++++++++ 3 files changed, 74 insertions(+), 18 deletions(-) diff --git a/packages/opentelemetry/src/to-otlp.test.ts b/packages/opentelemetry/src/to-otlp.test.ts index a5333c7b9..dd1ad7644 100644 --- a/packages/opentelemetry/src/to-otlp.test.ts +++ b/packages/opentelemetry/src/to-otlp.test.ts @@ -155,6 +155,38 @@ describe('toKeyValues is total (one bad attribute never costs the batch)', () => ); 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), diff --git a/packages/opentelemetry/src/to-otlp.ts b/packages/opentelemetry/src/to-otlp.ts index e711029cf..fa936144f 100644 --- a/packages/opentelemetry/src/to-otlp.ts +++ b/packages/opentelemetry/src/to-otlp.ts @@ -212,24 +212,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({ - ...safeCopy(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]; } diff --git a/packages/performance/src/extension.test.ts b/packages/performance/src/extension.test.ts index cccf65ddf..bd2b7a08e 100644 --- a/packages/performance/src/extension.test.ts +++ b/packages/performance/src/extension.test.ts @@ -380,6 +380,25 @@ describe("createPerformanceExtension — raw attribute values on the SDK's own s 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(); From 9d46782198312ee982d663ed4df960abf955e6d8 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 07:07:05 +0500 Subject: [PATCH 11/16] fix(performance,opentelemetry): length caps no longer defeat redaction; carry normalized copies; copy arrays (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - redactSqlLiterals replaces a literal left open by a length cap (scalar, map, array, consume, SDK paths) - a cut inside a token drops the unfinished token (partial JWT / ghp_), blobs without a boundary go to the marker - normalizeTransactionAttributes always carries the normalized copy forward (a getter cannot flip after normalization) - scalar arrays are read by index once and stored as copies (no Symbol.iterator trick, no aliasing) - docs: bigint row, cost figure, copy/alias notes; killable-mutant test 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 2 +- docs/PROGRESS.md | 2 +- docs/design/opentelemetry-integration.md | 19 ++- .../opentelemetry/src/span-processor.test.ts | 17 ++- .../src/attribute-value.fuzz.test.ts | 2 +- .../performance/src/attribute-value.test.ts | 119 +++++++++++++++--- packages/performance/src/attribute-value.ts | 68 +++++++--- packages/performance/src/extension.test.ts | 53 ++++++++ .../performance/src/span-sanitizer.test.ts | 21 ++++ packages/performance/src/span-sanitizer.ts | 4 + .../src/transaction-attributes.test.ts | 39 +++++- .../performance/src/transaction-attributes.ts | 51 +++----- 12 files changed, 320 insertions(+), 77 deletions(-) diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md index 8fc26370f..d11018b1d 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -12,6 +12,6 @@ Complex span attributes (OpenTelemetry API 1.10 `AnyValue`) are now handled deli `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, and a statement carried as a map or array has its string leaves' literals redacted. `isSensitiveKey` (`@bugsee/protocol`) now normalises its denylist once. +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 or secret cut by a length cap no longer leaves an open SQL literal or a partial token (a JWT after its payload, a `ghp_` prefix) in the clear; 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/performance` (some also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue`, `safeAnyValue`, `asBytes`, `boundedBase64` and the `MAX_ATTRIBUTE_*` limits. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 61ffe68ec..815424407 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -609,7 +609,7 @@ its first consumer. Design references (Sentry/Faro/Datadog/Honeycomb/Embrace) in 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. Bounded in WORK per attribute AND per span (leaf, key, node and character budgets, a span-level + 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 diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 167d79a9d..4e52ff474 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -236,7 +236,9 @@ that need it sit below `@bugsee/opentelemetry`; the OTel package re-exports it). 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, hostile getters contained) before the redaction walk or an integrator filter sees them. + 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 @@ -269,13 +271,20 @@ and a bounded JSON `stringValue` for maps/arrays. | input | after consume | at the wire / OTLP produce | | --- | --- | --- | -| string / boolean / number | unchanged (string capped at 32 KiB) | `stringValue` / `boolValue` / `intValue` or `doubleValue` | -| homogeneous scalar array | unchanged | unchanged; OTLP: JSON `stringValue` (existing behaviour) | +| 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 | string; `toAnyValue`: `bytesValue` (base64, bounded) | -| bigint | number if exact, else decimal string | `intValue` | +| 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 `'`/`"`), and a text 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 text with no token boundary at all (a single blob past the cap) is dropped to the marker. Byte +arrays (base64) are not text and are only cut. + *Bounds and totality.* Never throws, and bounded in WORK per ATTRIBUTE and per SPAN: 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 @@ -294,7 +303,7 @@ other class instance is read by own enumerable properties (so a Map or Set is `{ 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 60 ms for a span. `isSensitiveKey` now +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). diff --git a/packages/opentelemetry/src/span-processor.test.ts b/packages/opentelemetry/src/span-processor.test.ts index bf931a95c..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, @@ -115,6 +115,21 @@ describe('readableSpanToConsumed', () => { 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) }); diff --git a/packages/performance/src/attribute-value.fuzz.test.ts b/packages/performance/src/attribute-value.fuzz.test.ts index 49da66fdc..7296124d8 100644 --- a/packages/performance/src/attribute-value.fuzz.test.ts +++ b/packages/performance/src/attribute-value.fuzz.test.ts @@ -156,7 +156,7 @@ describe('normalizeAttributeValue (fuzz)', () => { for (const arb of arrays) { fc.assert( fc.property(arb, (arr) => { - expect(normalizeAttributeValue(arr)).toBe(arr); + expect(normalizeAttributeValue(arr)).toEqual(arr); }), ); } diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index efd1b27f1..d18e4f474 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -145,10 +145,10 @@ describe('stringifyAnyValue', () => { }); it('caps the output length and marks the cut', () => { - const out = stringifyAnyValue({ big: 'x'.repeat(50_000) }) as string; + 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":"xxx')).toBe(true); + 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); @@ -175,7 +175,7 @@ describe('stringifyAnyValue', () => { }); it('bounds WORK by size, not just count: a huge nested leaf is cut before it is copied or encoded', () => { - const huge = 'x'.repeat(64 * 1024 * 1024); + 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 }] }); @@ -183,7 +183,7 @@ describe('stringifyAnyValue', () => { }); it('stops copying string leaves after the character budget, however many leaves there are', () => { - const megabyte = 'x'.repeat(1_000_000); + 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]'); @@ -325,11 +325,10 @@ describe('normalizeAttributeValue', () => { const strs = ['a', 'b']; const nums = [1, 2.5]; const bools = [true, false]; - expect(normalizeAttributeValue(strs)).toBe(strs); - expect(normalizeAttributeValue(nums)).toBe(nums); - expect(normalizeAttributeValue(bools)).toBe(bools); - const empty: unknown[] = []; - expect(normalizeAttributeValue(empty)).toBe(empty); + 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', () => { @@ -338,15 +337,15 @@ describe('normalizeAttributeValue', () => { expect(normalizeAttributeValue([[1], [2]])).toEqual([[1], [2]]); }); - it('passes a homogeneous scalar array that contains null/undefined entries through unchanged', () => { + 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)).toBe(withNull); - expect(normalizeAttributeValue(nums)).toBe(nums); - expect(flattenAttributeValue(withNull)).toBe(withNull); + 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.toBe(withNull); + expect(normalizeAttributeValue(['a', 1, null])).not.toEqual(withNull); }); it('routes a primitive array past the length cap through the bounded tree (truncated)', () => { @@ -355,7 +354,7 @@ describe('normalizeAttributeValue', () => { expect(out).not.toBe(long); expect(out.at(-1)).toBe('[Truncated]'); const atCap = Array.from({ length: MAX_ATTRIBUTE_ARRAY_LENGTH }, () => 'a'); - expect(normalizeAttributeValue(atCap)).toBe(atCap); + expect(normalizeAttributeValue(atCap)).toEqual(atCap); }); it('keeps an object as a safe copy (nested keys still visible to redaction) and bytes as base64', () => { @@ -368,22 +367,24 @@ describe('normalizeAttributeValue', () => { }); it('caps a scalar string at the documented limit, marked, and leaves one at the limit alone', () => { - const atLimit = 'x'.repeat(MAX_ATTRIBUTE_STRING_LENGTH); + 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.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); + expect(over.length).toBeGreaterThan(MAX_ATTRIBUTE_STRING_LENGTH - 100); 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).not.toBe(big); + 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)).toBe(small); + expect(normalizeAttributeValue(small)).toEqual(small); }); it('drops the attribute for the OTel empty value and for values with no JSON form', () => { @@ -479,6 +480,86 @@ describe('work bounds that output alone cannot show', () => { }); }); +describe('a cut never leaves a PARTIAL secret-shaped token behind', () => { + const filler = 'lorem ipsum '.repeat(10_000); + + it('drops the unfinished final token of a scalar string cut by the cap', () => { + const jwtPrefix = 'eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InBhdGllbnRAeC5leGFtcGxlIn0'; + const text = `${filler.slice(0, MAX_ATTRIBUTE_STRING_LENGTH - 40 - TRUNCATION_MARKER.length)} ${jwtPrefix}.sig`; + const out = normalizeAttributeValue(text) as string; + expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); + expect(out).toContain(TRUNCATION_MARKER); + expect(out).not.toContain('eyJ'); + }); + + it('drops a GitHub-token prefix cut at a nested leaf', () => { + const cut = MAX_ATTRIBUTE_JSON_LENGTH - 64 - TRUNCATION_MARKER.length; + const text = `${'word '.repeat(2000).slice(0, cut - 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); + }); + + it('keeps a token that ends exactly at the cut (it is complete, not partial)', () => { + const end = MAX_ATTRIBUTE_STRING_LENGTH - TRUNCATION_MARKER.length; + const make = (pad: number): string => + `${'z'.repeat(pad)}${'tok '.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 4 + 5)}`; + const pad = [0, 1, 2, 3].find((p) => make(p)[end] === ' ') as number; + const out = normalizeAttributeValue(make(pad)) as string; + expect(out.endsWith(`tok${TRUNCATION_MARKER}`)).toBe(true); + expect(out.length).toBe(MAX_ATTRIBUTE_STRING_LENGTH); + }); + + 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 string without any token boundary is dropped to the marker, never kept as a partial blob', () => { + const out = normalizeAttributeValue('x'.repeat(MAX_ATTRIBUTE_STRING_LENGTH + 1)) as string; + expect(out).toBe(TRUNCATION_MARKER); + }); +}); + +describe('arrays are copied, not aliased', () => { + 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`; diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts index 19ed80e18..edece0c5b 100644 --- a/packages/performance/src/attribute-value.ts +++ b/packages/performance/src/attribute-value.ts @@ -88,8 +88,32 @@ export function asBytes(value: unknown): Uint8Array | undefined { return undefined; } -const capText = (text: string, max: number): string => - text.length <= max ? text : text.slice(0, max - TRUNCATION_MARKER.length) + TRUNCATION_MARKER; +/** 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))) { + while (end > 0 && isTokenChar(text.charCodeAt(end - 1))) end--; + } + 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 { @@ -162,8 +186,8 @@ const setOwn = (target: Record, key: string, value: unknown): v }; /** A string leaf or key, cut at the leaf cap and counted against the tree's character budget. */ -function leafText(text: string, budget: Budget): string { - const cut = capText(text, MAX_LEAF_LENGTH); +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; @@ -188,7 +212,7 @@ function toSafe(value: unknown, depth: number, budget: Budget, ancestors: Set typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'; -/** An array whose non-null elements are all strings, all numbers or all booleans (the pre-1.10 shape), and small. */ -function isPassThroughArray(value: unknown[]): boolean { - if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return false; +/** + * 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 { + if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return undefined; + const copy: unknown[] = []; let kind: string | undefined; let chars = 0; - for (const item of value) { + for (let i = 0; i < value.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 false; + if (!isScalar(item)) return undefined; kind ??= typeof item; - if (typeof item !== kind) return false; + if (typeof item !== kind) return undefined; if (typeof item === 'string') { chars += item.length; - if (chars > MAX_ATTRIBUTE_STRING_LENGTH) return false; + if (chars > MAX_ATTRIBUTE_STRING_LENGTH) return undefined; } } - return true; + 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 @@ -348,12 +382,15 @@ function isPassThroughArray(value: unknown[]): boolean { */ export function normalizeAttributeValue(value: unknown, span?: SpanBudget): unknown { if (value === null || value === undefined) return undefined; - if (typeof value === 'string') return capText(value, MAX_ATTRIBUTE_STRING_LENGTH); + if (typeof value === 'string') return capText(value, MAX_ATTRIBUTE_STRING_LENGTH, true); 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) && isPassThroughArray(value)) return value; + 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 } @@ -390,6 +427,7 @@ export function normalizeAttributes( * one bounded JSON string. Total: never throws. `undefined` = drop the attribute. */ export function flattenAttributeValue(value: unknown, span?: SpanBudget): unknown { + if (Array.isArray(value) && isPassThroughArray(value)) return value; // already a normalized copy here const normal = normalizeAttributeValue(value, span); if (normal === null || typeof normal !== 'object') return normal; return Array.isArray(normal) && isPassThroughArray(normal) ? normal : stringifyAnyValue(normal); diff --git a/packages/performance/src/extension.test.ts b/packages/performance/src/extension.test.ts index bd2b7a08e..42fca56b7 100644 --- a/packages/performance/src/extension.test.ts +++ b/packages/performance/src/extension.test.ts @@ -439,6 +439,59 @@ describe("createPerformanceExtension — raw attribute values on the SDK's own s }); }); +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/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index c8bf41d04..f6efb0a41 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -227,3 +227,24 @@ describe('sanitizeSpan: a statement key whose value is not a plain string', () = 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 a353a33c9..c3ea4e9e8 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -50,6 +50,10 @@ 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. + .replace(/'(?:[^']|'')*$/, '?') + .replace(/"(?:[^"]|"")*$/, '?') // numeric literals, but never the digits inside an identifier like `column2` .replace(/\b\d+(?:\.\d+)?\b/g, '?') ); diff --git a/packages/performance/src/transaction-attributes.test.ts b/packages/performance/src/transaction-attributes.test.ts index 384f7f5a2..73f90e6f0 100644 --- a/packages/performance/src/transaction-attributes.test.ts +++ b/packages/performance/src/transaction-attributes.test.ts @@ -67,11 +67,44 @@ const dag = (levels: number, fanout: number): unknown => { }; describe('normalizeTransactionAttributes (SDK-produced spans carry RAW values too)', () => { - it('returns the SAME transaction when every attribute is already a scalar or scalar array', () => { + 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)).toBe(plain); + expect(normalizeTransactionAttributes(plain)).toEqual(plain); const bare = txn(); - expect(normalizeTransactionAttributes(bare)).toBe(bare); + 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', () => { diff --git a/packages/performance/src/transaction-attributes.ts b/packages/performance/src/transaction-attributes.ts index b507fd9ae..7e4f8d720 100644 --- a/packages/performance/src/transaction-attributes.ts +++ b/packages/performance/src/transaction-attributes.ts @@ -21,43 +21,32 @@ export function flattenTransactionAttributes(transaction: TransactionWire): Tran return { ...transaction, ...(root !== undefined ? { attributes: root } : {}), spans }; } -/** - * `normalizeAttributes`, but returning the SAME record when it was already normal (scalars and scalar arrays - * only, nothing dropped), so the common path copies nothing. A record whose keys or values cannot be read - * (a Proxy trap, a throwing getter) counts as changed and yields the normalized copy. - */ -function normalizedRecord(attributes: Record): Record { - const normal = normalizeAttributes(attributes); - try { - const keys = Object.keys(attributes); - const same = - keys.length === Object.keys(normal).length && - keys.every((key) => normal[key] === attributes[key]); - return same ? attributes : normal; - } catch { - return normal; - } -} - /** * 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. Returns the SAME transaction when nothing needed changing. + * 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 { - const root = - transaction.attributes === undefined ? undefined : normalizedRecord(transaction.attributes); - let changed = root !== transaction.attributes; - const spans = transaction.spans.map((span) => { - if (span.attributes === undefined) return span; - const attributes = normalizedRecord(span.attributes); - if (attributes === span.attributes) return span; - changed = true; - return { ...span, attributes }; - }); - if (!changed) return transaction; - return { ...transaction, ...(root !== undefined ? { attributes: root } : {}), spans }; + 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) }, + ), + }; } From 6ab9b591a2c2539b123d4918a7c8c7ff9bef2b0f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 07:19:39 +0500 Subject: [PATCH 12/16] fix(performance): single length read, copy arrays on flatten, token-drop only where shape scanning applies; docs and SQL-quote known limitation (#94, #109) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 4 +- docs/design/opentelemetry-integration.md | 29 +++-- .../performance/src/attribute-value.test.ts | 112 ++++++++++++++---- packages/performance/src/attribute-value.ts | 20 +++- packages/performance/src/span-sanitizer.ts | 7 +- .../src/transaction-attributes.test.ts | 2 +- 6 files changed, 130 insertions(+), 44 deletions(-) diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md index d11018b1d..95750914e 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -8,10 +8,10 @@ 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. 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` (base64); 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. +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` (base64); 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 or secret cut by a length cap no longer leaves an open SQL literal or a partial token (a JWT after its payload, a `ghp_` prefix) in the clear; 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. +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 (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/performance` (some also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue`, `safeAnyValue`, `asBytes`, `boundedBase64` and the `MAX_ATTRIBUTE_*` limits. diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 4e52ff474..9e90317b0 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -249,9 +249,9 @@ that need it sit below `@bugsee/opentelemetry`; the OTel package re-exports it). 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 leaves INSIDE maps and arrays-of-maps only, - exactly as on main a top-level string attribute or a flat string array is not shape-scanned; depth-limited), - so + 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): @@ -280,16 +280,25 @@ and a bounded JSON `stringValue` for maps/arrays. *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 `'`/`"`), and a text 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 text with no token boundary at all (a single blob past the cap) is dropped to the marker. Byte -arrays (base64) are not text and are only cut. - -*Bounds and totality.* Never throws, and bounded in WORK per ATTRIBUTE and per SPAN: every string leaf and key is +(`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 (a hash, a URL path) keeps its cut prefix, except one that begins `eyJ` (JWT-shaped), which is +dropped to the marker. 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), depth 8 (`"[MaxDepth]"`), the JSON text at 8192 characters (`...[truncated]`), cycles become +`"[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 diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index d18e4f474..bf303bcf5 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -370,8 +370,7 @@ describe('normalizeAttributeValue', () => { 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).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); - expect(over.length).toBeGreaterThan(MAX_ATTRIBUTE_STRING_LENGTH - 100); + expect(over.length).toBe(MAX_ATTRIBUTE_STRING_LENGTH); expect(over.endsWith(TRUNCATION_MARKER)).toBe(true); }); @@ -480,34 +479,68 @@ describe('work bounds that output alone cannot show', () => { }); }); -describe('a cut never leaves a PARTIAL secret-shaped token behind', () => { - const filler = 'lorem ipsum '.repeat(10_000); +describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape scanning applies)', () => { + const MAX_LEAF = MAX_ATTRIBUTE_JSON_LENGTH - 64; + const leafEnd = MAX_LEAF - TRUNCATION_MARKER.length; + const spaced = (length: number): string => 'ab '.repeat(length).slice(0, length); - it('drops the unfinished final token of a scalar string cut by the cap', () => { + it('drops a JWT cut after its payload from a map leaf', () => { const jwtPrefix = 'eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InBhdGllbnRAeC5leGFtcGxlIn0'; - const text = `${filler.slice(0, MAX_ATTRIBUTE_STRING_LENGTH - 40 - TRUNCATION_MARKER.length)} ${jwtPrefix}.sig`; - const out = normalizeAttributeValue(text) as string; - expect(out.length).toBeLessThanOrEqual(MAX_ATTRIBUTE_STRING_LENGTH); - expect(out).toContain(TRUNCATION_MARKER); - expect(out).not.toContain('eyJ'); + 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 cut = MAX_ATTRIBUTE_JSON_LENGTH - 64 - TRUNCATION_MARKER.length; - const text = `${'word '.repeat(2000).slice(0, cut - 21)} ghp_abcdefghijklmnopqrstuvwxyz0123456789AB`; + 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 end = MAX_ATTRIBUTE_STRING_LENGTH - TRUNCATION_MARKER.length; - const make = (pad: number): string => - `${'z'.repeat(pad)}${'tok '.repeat(MAX_ATTRIBUTE_STRING_LENGTH / 4 + 5)}`; - const pad = [0, 1, 2, 3].find((p) => make(p)[end] === ' ') as number; - const out = normalizeAttributeValue(make(pad)) as string; - expect(out.endsWith(`tok${TRUNCATION_MARKER}`)).toBe(true); - expect(out.length).toBe(MAX_ATTRIBUTE_STRING_LENGTH); + 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); + }); + + it('keeps a long boundary-less leaf (a hash, a URL) cut, but drops one that begins like a JWT', () => { + const hash = safeAnyValue({ h: 'f'.repeat(9000) }) as { h: string }; + expect(hash.h.length).toBe(MAX_LEAF); + expect(hash.h.startsWith('ffff')).toBe(true); + const jwt = safeAnyValue({ j: `eyJ${'a'.repeat(9000)}` }) as { j: string }; + expect(jwt.j).toBe(TRUNCATION_MARKER); }); it('does not touch base64 of a byte array (not text)', () => { @@ -517,13 +550,44 @@ describe('a cut never leaves a PARTIAL secret-shaped token behind', () => { expect(nested.b.length).toBeGreaterThan(MAX_ATTRIBUTE_JSON_LENGTH - 200); }); - it('a string without any token boundary is dropped to the marker, never kept as a partial blob', () => { - const out = normalizeAttributeValue('x'.repeat(MAX_ATTRIBUTE_STRING_LENGTH + 1)) as string; - expect(out).toBe(TRUNCATION_MARKER); + 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[]; @@ -591,7 +655,7 @@ describe('flattenAttributeValue (the wire form)', () => { const arr = ['a', 'b']; expect(flattenAttributeValue('s')).toBe('s'); expect(flattenAttributeValue(3)).toBe(3); - expect(flattenAttributeValue(arr)).toBe(arr); + expect(flattenAttributeValue(arr)).toEqual(arr); }); it('turns any remaining complex value into one bounded JSON string', () => { @@ -614,7 +678,7 @@ describe('flattenAttributeValue (the wire form)', () => { describe('flattenAttributes', () => { it('returns the SAME record when nothing needed changing', () => { - const attrs = { a: 'x', n: 1, tags: ['a', 'b'] }; + const attrs = { a: 'x', n: 1, ok: true }; expect(flattenAttributes(attrs)).toBe(attrs); }); diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts index edece0c5b..b89267e01 100644 --- a/packages/performance/src/attribute-value.ts +++ b/packages/performance/src/attribute-value.ts @@ -110,7 +110,11 @@ 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 blob (a hash, a URL path). Keep its prefix, which carries the data that + // matters, unless it is JWT-shaped, where the prefix IS the readable header and claims. + if (end === 0 && !text.startsWith('eyJ')) end = cut; } return text.slice(0, end) + TRUNCATION_MARKER; }; @@ -351,11 +355,14 @@ const isScalar = (v: unknown): v is string | number | boolean => * result does not alias the caller's array (a later `push({ password })` must not reach the store). */ function scalarArrayCopy(value: unknown[]): unknown[] | undefined { - if (value.length > MAX_ATTRIBUTE_ARRAY_LENGTH) return 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 < value.length; i++) { + 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. @@ -382,7 +389,8 @@ const isPassThroughArray = (value: unknown[]): boolean => scalarArrayCopy(value) */ export function normalizeAttributeValue(value: unknown, span?: SpanBudget): unknown { if (value === null || value === undefined) return undefined; - if (typeof value === 'string') return capText(value, MAX_ATTRIBUTE_STRING_LENGTH, true); + // 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); @@ -427,7 +435,11 @@ export function normalizeAttributes( * one bounded JSON string. Total: never throws. `undefined` = drop the attribute. */ export function flattenAttributeValue(value: unknown, span?: SpanBudget): unknown { - if (Array.isArray(value) && isPassThroughArray(value)) return value; // already a normalized copy here + 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); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index c3ea4e9e8..d35befeb6 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -51,9 +51,10 @@ export function redactSqlLiterals(statement: string): string { .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. - .replace(/'(?:[^']|'')*$/, '?') - .replace(/"(?:[^"]|"")*$/, '?') + // 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, '?') ); diff --git a/packages/performance/src/transaction-attributes.test.ts b/packages/performance/src/transaction-attributes.test.ts index 73f90e6f0..b27f4cc2d 100644 --- a/packages/performance/src/transaction-attributes.test.ts +++ b/packages/performance/src/transaction-attributes.test.ts @@ -28,7 +28,7 @@ const child = (attributes?: Record): TransactionWire['spans'][n describe('flattenTransactionAttributes', () => { it('returns the SAME transaction when no attribute is complex (the common path copies nothing)', () => { - const plain = txn({ attributes: { a: 1, tags: ['x'] }, spans: [child({ b: 'y' }), child()] }); + 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); From 2c165184700ebad6148b7d83e163a51b875d62f4 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 07:21:52 +0500 Subject: [PATCH 13/16] fix(opentelemetry): never put the truncation marker inside bytesValue (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- packages/opentelemetry/src/to-otlp.test.ts | 13 +++++++++---- packages/opentelemetry/src/to-otlp.ts | 10 +++++++++- packages/performance/src/index.ts | 1 + 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/packages/opentelemetry/src/to-otlp.test.ts b/packages/opentelemetry/src/to-otlp.test.ts index dd1ad7644..1fbb48006 100644 --- a/packages/opentelemetry/src/to-otlp.test.ts +++ b/packages/opentelemetry/src/to-otlp.test.ts @@ -73,10 +73,15 @@ describe('toAnyValue', () => { expect(out.stringValue.length).toBeLessThanOrEqual(8192); expect(out.stringValue).toContain('...[truncated]'); }); - it('caps a huge byte array (bytesValue is bounded like every other branch)', () => { - const out = toAnyValue(new Uint8Array(1_000_000)) as { bytesValue: string }; - expect(out.bytesValue.length).toBe(8192); - expect(out.bytesValue.endsWith('...[truncated]')).toBe(true); + 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('never throws: an unencodable object yields no value instead of an exception', () => { const original = JSON.stringify; diff --git a/packages/opentelemetry/src/to-otlp.ts b/packages/opentelemetry/src/to-otlp.ts index fa936144f..679693fe1 100644 --- a/packages/opentelemetry/src/to-otlp.ts +++ b/packages/opentelemetry/src/to-otlp.ts @@ -4,6 +4,7 @@ import { type SpanStatus, safeAnyValue, stringifyAnyValue, + TRUNCATION_MARKER, type TransactionWire, } from '@bugsee/performance'; import { @@ -71,7 +72,14 @@ export function toAnyValue(value: unknown): OtlpAnyValue | undefined { default: { try { const bytes = asBytes(value); - if (bytes !== undefined) return { bytesValue: boundedBase64(bytes) }; + 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 }; diff --git a/packages/performance/src/index.ts b/packages/performance/src/index.ts index 86f22748d..d577450c3 100644 --- a/packages/performance/src/index.ts +++ b/packages/performance/src/index.ts @@ -20,6 +20,7 @@ export { normalizeAttributeValue, safeAnyValue, stringifyAnyValue, + TRUNCATION_MARKER, } from './attribute-value'; export { createPerformanceController, From 63196be38a3abb472b862137b0fc39f59bd215e1 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 07:35:05 +0500 Subject: [PATCH 14/16] fix(performance,protocol): boundary-less leaves back off before the last secret-shaped start; byte boundary tests; honest docs (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lastSecretShapeStart in @bugsee/protocol, next to the shape patterns, with a sample per shape - a cut of an unbroken run (id_token=, ghp_/AKIA after filler) no longer keeps a half-written secret - pin 6144/6145-byte bytesValue boundary; docs/docstrings/changeset corrected 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 8 +-- docs/design/opentelemetry-integration.md | 24 +++++--- packages/opentelemetry/src/to-otlp.test.ts | 9 +++ .../performance/src/attribute-value.test.ts | 61 ++++++++++++++++--- packages/performance/src/attribute-value.ts | 17 ++++-- .../src/transaction-attributes.test.ts | 8 +++ .../performance/src/transaction-attributes.ts | 3 +- packages/protocol/src/index.ts | 2 +- packages/protocol/src/shapes.test.ts | 43 ++++++++++++- packages/protocol/src/shapes.ts | 24 ++++++++ 10 files changed, 171 insertions(+), 28 deletions(-) diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md index 95750914e..91f440814 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -1,17 +1,17 @@ --- '@bugsee/opentelemetry': minor '@bugsee/performance': minor -'@bugsee/protocol': patch +'@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` (base64); 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. +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 (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. +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 the last secret-shaped start (a long map-leaf URL is therefore cut back to `https:`; 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/performance` (some also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue`, `safeAnyValue`, `asBytes`, `boundedBase64` and the `MAX_ATTRIBUTE_*` limits. +New exports from `@bugsee/protocol`: `lastSecretShapeStart`. 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/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 9e90317b0..aa4b4ddf6 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -266,7 +266,8 @@ Rejected: flattening to dotted keys (key explosion, no stable form for arrays) a 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 +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 | @@ -274,7 +275,7 @@ and a bounded JSON `stringValue` for maps/arrays. | 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 | string; `toAnyValue`: `bytesValue` (base64, bounded) | +| 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 | @@ -282,13 +283,18 @@ and a bounded JSON `stringValue` for maps/arrays. 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 (a hash, a URL path) keeps its cut prefix, except one that begins `eyJ` (JWT-shaped), which is -dropped to the marker. 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). +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 the LAST place a secret shape begins in it (`lastSecretShapeStart` in +`@bugsee/protocol`, kept next to the shape patterns and guarded by a sample per shape): a JWT that begins the +leaf collapses to the marker, `id_token=` is kept without the token, and a JWT's header segment, which carries +no personal data, may remain while its payload does not. `:` is not a token character, so a long map-leaf URL +(`https://host/...` past the cap) is cut back to `https:` plus the marker: that is 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 diff --git a/packages/opentelemetry/src/to-otlp.test.ts b/packages/opentelemetry/src/to-otlp.test.ts index 1fbb48006..2145840a1 100644 --- a/packages/opentelemetry/src/to-otlp.test.ts +++ b/packages/opentelemetry/src/to-otlp.test.ts @@ -83,6 +83,15 @@ describe('toAnyValue', () => { 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 = () => { diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index bf303bcf5..081a9ff29 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -479,8 +479,9 @@ describe('work bounds that output alone cannot show', () => { }); }); +const MAX_LEAF = MAX_ATTRIBUTE_JSON_LENGTH - 64; + describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape scanning applies)', () => { - const MAX_LEAF = MAX_ATTRIBUTE_JSON_LENGTH - 64; const leafEnd = MAX_LEAF - TRUNCATION_MARKER.length; const spaced = (length: number): string => 'ab '.repeat(length).slice(0, length); @@ -535,12 +536,58 @@ describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape s expect(out.note.endsWith(`tok${TRUNCATION_MARKER}`)).toBe(true); }); - it('keeps a long boundary-less leaf (a hash, a URL) cut, but drops one that begins like a JWT', () => { - const hash = safeAnyValue({ h: 'f'.repeat(9000) }) as { h: string }; - expect(hash.h.length).toBe(MAX_LEAF); - expect(hash.h.startsWith('ffff')).toBe(true); - const jwt = safeAnyValue({ j: `eyJ${'a'.repeat(9000)}` }) as { j: string }; - expect(jwt.j).toBe(TRUNCATION_MARKER); + describe('a leaf with no token boundary keeps its cut prefix, but never a half-written secret', () => { + const payload = (globalThis as unknown as { btoa(input: string): string }) + .btoa('{"email":"patient@clinic.example","ssn":"123-45-6789"}') + .replace(/=+$/, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); + const jwt = `eyJhbGciOiJIUzI1NiJ9.${payload}.${'S'.repeat(9000)}`; + 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('drops a JWT that begins the leaf, and one placed after other token characters', () => { + expect(leaf(jwt)).not.toContain(payload); + for (const prefix of ['id_token=', '/auth/callback/', 'token.', 'a_b-c']) { + const out = leaf(`${prefix}${jwt}`); + expect(out).toContain(prefix); + expect(out).not.toContain(payload); // the claims are gone + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + } + }); + + 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('drops a JWT that follows a space (the space is the boundary, the JWT is the unfinished run)', () => { + const out = leaf(`${'word '.repeat(10)} ${jwt}`); + expect(out).not.toContain(payload); + expect(out.startsWith('word word')).toBe(true); + expect(leaf(` ${jwt}`)).toBe(` ${TRUNCATION_MARKER}`); + }); + + it.each([ + ['ghp_', 'ghp_abcdefghijklmnopqrstuvwxyz0123456789'], + ['AKIA', 'AKIAIOSFODNN7EXAMPLE'], + ['ASIA', 'ASIAIOSFODNN7EXAMPLE'], + // Built from pieces so the repository's secret scanning does not take a fixture for a live key. + ['sk_live_', ['sk', 'live', 'abcdefghijklmnopqrstuvwx'].join('_')], + ['whsec_', ['whsec', 'abcdefghijklmnopqrstuvwx'].join('_')], + ])('drops a %s secret the cut leaves half-written', (needle, secret) => { + const filler = 'a'.repeat(MAX_LEAF - TRUNCATION_MARKER.length - 9); // 9 characters of the secret survive + const out = leaf(`${filler}${secret}${'b'.repeat(200)}`); + expect(out).not.toContain(needle); + expect(out.startsWith('aaaa')).toBe(true); + expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + }); }); it('does not touch base64 of a byte array (not text)', () => { diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts index b89267e01..184b168ad 100644 --- a/packages/performance/src/attribute-value.ts +++ b/packages/performance/src/attribute-value.ts @@ -1,4 +1,4 @@ -import { REDACTED } from '@bugsee/protocol'; +import { lastSecretShapeStart, REDACTED } from '@bugsee/protocol'; // Span attribute values: bounding, safe copying and the wire flattening of complex values. // @@ -112,9 +112,13 @@ const capText = (text: string, max: number, dropPartialToken = false): string => if (dropPartialToken && isTokenChar(text.charCodeAt(end))) { const cut = end; while (end > 0 && isTokenChar(text.charCodeAt(end - 1))) end--; - // No boundary at all: one long blob (a hash, a URL path). Keep its prefix, which carries the data that - // matters, unless it is JWT-shaped, where the prefix IS the readable header and claims. - if (end === 0 && !text.startsWith('eyJ')) end = cut; + // 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 the LAST place a secret shape begins in it: a secret + // the cut leaves half-written no longer matches `redactShapes`, so its readable part would ship as is. + if (end === 0) { + const start = lastSecretShapeStart(text.slice(0, cut)); + end = start === -1 ? cut : start; + } } return text.slice(0, end) + TRUNCATION_MARKER; }; @@ -445,7 +449,10 @@ export function flattenAttributeValue(value: unknown, span?: SpanBudget): unknow return Array.isArray(normal) && isPassThroughArray(normal) ? normal : stringifyAnyValue(normal); } -/** Flatten an attributes record for the wire. Returns the SAME record when nothing needed changing. */ +/** + * 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; diff --git a/packages/performance/src/transaction-attributes.test.ts b/packages/performance/src/transaction-attributes.test.ts index b27f4cc2d..8e75567aa 100644 --- a/packages/performance/src/transaction-attributes.test.ts +++ b/packages/performance/src/transaction-attributes.test.ts @@ -27,6 +27,14 @@ const child = (attributes?: Record): TransactionWire['spans'][n }); 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); diff --git a/packages/performance/src/transaction-attributes.ts b/packages/performance/src/transaction-attributes.ts index 7e4f8d720..a727a693b 100644 --- a/packages/performance/src/transaction-attributes.ts +++ b/packages/performance/src/transaction-attributes.ts @@ -4,7 +4,8 @@ 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, when nothing was complex, so the default path copies nothing. + * 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 = diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index c24d78e4f..1ea187678 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 { lastSecretShapeStart, redactShapes, type ShapeRedactionOptions } from './shapes'; export { bytesToMegabytes } from './units'; export { sanitizeErrorMessage, sanitizeUrl } from './url'; export type { diff --git a/packages/protocol/src/shapes.test.ts b/packages/protocol/src/shapes.test.ts index 85e19c488..3cf8d79d9 100644 --- a/packages/protocol/src/shapes.test.ts +++ b/packages/protocol/src/shapes.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { redactShapes } from './index'; +import { lastSecretShapeStart, redactShapes } from './index'; const R = ''; @@ -298,3 +298,44 @@ describe('the JWT bound sits at 8 KB, where the reachable window is', () => { expect(redactShapes(`${'x'.repeat(8000)} ${jwt}`)).toContain(''); }); }); + +describe('lastSecretShapeStart', () => { + // One COMPLETE secret per shape redactShapes knows. The start finder must locate the beginning of each, so + // a caller that has to cut text can back off before a secret that the cut would leave half-written (a + // partial secret no longer matches redactShapes, so it would ship in the clear). A new pattern in + // SHAPE_PATTERNS needs a sample here: this is the drift guard. + 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)}`, + }; + + it.each( + Object.entries(SAMPLES), + )('finds the start of a %s secret, and redactShapes agrees it is one', (_name, secret) => { + expect(redactShapes(secret)).not.toBe(secret); + // A JWT's payload segment (`{"...` base64url) also begins `eyJ`, so its LAST start is the payload's. + const start = secret.startsWith('eyJ') ? secret.lastIndexOf('eyJ') : 0; + expect(lastSecretShapeStart(secret)).toBe(start); + expect(lastSecretShapeStart(`prefix-${secret}`)).toBe(7 + start); + expect(lastSecretShapeStart(`id_token=${secret.slice(0, 8)}`)).toBe(9); // a half-written one too + }); + + it('returns the LAST start when several are present, and -1 when there is none', () => { + const text = `${SAMPLES.jwt}/${SAMPLES['github ghp']}/plain`; + expect(lastSecretShapeStart(text)).toBe((SAMPLES.jwt?.length ?? 0) + 1); + expect(lastSecretShapeStart('nothing secret here, just words and AKI')).toBe(-1); + expect(lastSecretShapeStart('')).toBe(-1); + }); +}); diff --git a/packages/protocol/src/shapes.ts b/packages/protocol/src/shapes.ts index fde012963..da353f0ee 100644 --- a/packages/protocol/src/shapes.ts +++ b/packages/protocol/src/shapes.ts @@ -80,6 +80,30 @@ const SHAPE_PATTERNS: readonly RegExp[] = [ /gh[posu]_[A-Za-z0-9]{36,}/g, // GitHub personal access / OAuth / user / server token ]; +/** + * Where a secret shape BEGINS: the opening of each pattern in {@link SHAPE_PATTERNS} plus the JWT header. + * Kept next to those patterns (and guarded by a sample per shape in the tests) so the two cannot drift. + */ +const SECRET_SHAPE_START = /eyJ|A(?:KIA|SIA|GPA|IDA|ROA)|(?:sk|pk|rk)_live_|whsec_|gh[posu]_/g; + +/** + * The offset of the LAST place in `text` where a secret shape begins, or -1. 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 it would reach the wire in the clear. + */ +export function lastSecretShapeStart(text: string): number { + let last = -1; + SECRET_SHAPE_START.lastIndex = 0; + for ( + let match = SECRET_SHAPE_START.exec(text); + match !== null; + match = SECRET_SHAPE_START.exec(text) + ) { + last = match.index; + } + return last; +} + function isLuhnValid(digits: string): boolean { let sum = 0; let double = false; From 7ef9e089d5577a7c7dfd6396a71b15374a62cc2b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 07:51:09 +0500 Subject: [PATCH 15/16] fix(performance,protocol): back off to the secret the cut lands in, not the last shape start (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit unfinishedSecretStart walks shape starts left to right and advances only past a complete secret, so a nested eyJ in a JWT payload or an ASIA inside an AWS key cannot move the cut into the middle of the outer secret; a JWT cut inside its signature is left whole for redaction. Shape starts and redaction patterns now come from one table. Exact-output tests, nested-claim JWT fixtures, docs corrected. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/opentelemetry-3-support.md | 4 +- docs/design/opentelemetry-integration.md | 19 ++- .../performance/src/attribute-value.test.ts | 96 +++++++++---- packages/performance/src/attribute-value.ts | 9 +- packages/protocol/src/index.ts | 2 +- packages/protocol/src/shapes.test.ts | 132 +++++++++++++----- packages/protocol/src/shapes.ts | 69 ++++++--- 7 files changed, 235 insertions(+), 96 deletions(-) diff --git a/.changeset/opentelemetry-3-support.md b/.changeset/opentelemetry-3-support.md index 91f440814..edb2a647e 100644 --- a/.changeset/opentelemetry-3-support.md +++ b/.changeset/opentelemetry-3-support.md @@ -12,6 +12,6 @@ Complex span attributes (OpenTelemetry API 1.10 `AnyValue`) are now handled deli `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 the last secret-shaped start (a long map-leaf URL is therefore cut back to `https:`; 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. +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`: `lastSecretShapeStart`. New exports from `@bugsee/performance` (some also re-exported from `@bugsee/opentelemetry`): `normalizeAttributes`, `normalizeAttributeValue`, `flattenAttributes`, `stringifyAnyValue`, `safeAnyValue`, `asBytes`, `boundedBase64` and the `MAX_ATTRIBUTE_*` limits. +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/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index aa4b4ddf6..9e5bc6698 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -285,12 +285,19 @@ longer recognise: a SQL statement cut inside a string literal has its open trail 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 the LAST place a secret shape begins in it (`lastSecretShapeStart` in -`@bugsee/protocol`, kept next to the shape patterns and guarded by a sample per shape): a JWT that begins the -leaf collapses to the marker, `id_token=` is kept without the token, and a JWT's header segment, which carries -no personal data, may remain while its payload does not. `:` is not a token character, so a long map-leaf URL -(`https://host/...` past the cap) is cut back to `https:` plus the marker: that is accepted data loss, a -scheme-and-host-keeping rule was not worth another heuristic. A TOP-LEVEL string attribute is only cut (it is +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). Stripe-style keys are never "unfinished", because their patterns match a partial +key. 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 at most 16 starts per call and past that +backs off to the current candidate (more dropped, never less). `:` 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 diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index 081a9ff29..c70b1f85a 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -1,3 +1,4 @@ +import { redactShapes } from '@bugsee/protocol'; import { describe, expect, it, vi } from 'vitest'; import { boundedBase64, @@ -537,12 +538,27 @@ describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape s }); describe('a leaf with no token boundary keeps its cut prefix, but never a half-written secret', () => { - const payload = (globalThis as unknown as { btoa(input: string): string }) - .btoa('{"email":"patient@clinic.example","ssn":"123-45-6789"}') - .replace(/=+$/, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); - const jwt = `eyJhbGciOiJIUzI1NiJ9.${payload}.${'S'.repeat(9000)}`; + 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', () => { @@ -551,42 +567,72 @@ describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape s expect(hash.startsWith('ffff')).toBe(true); }); - it('drops a JWT that begins the leaf, and one placed after other token characters', () => { - expect(leaf(jwt)).not.toContain(payload); + 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']) { - const out = leaf(`${prefix}${jwt}`); - expect(out).toContain(prefix); - expect(out).not.toContain(payload); // the claims are gone - expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + expect(leaf(`${prefix}${jwtOf(payload)}`)).toBe(`${prefix}${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('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)} ${jwt}`); - expect(out).not.toContain(payload); + 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(` ${jwt}`)).toBe(` ${TRUNCATION_MARKER}`); + 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'], - // Built from pieces so the repository's secret scanning does not take a fixture for a live key. + ])('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('_')], - ])('drops a %s secret the cut leaves half-written', (needle, secret) => { - const filler = 'a'.repeat(MAX_LEAF - TRUNCATION_MARKER.length - 9); // 9 characters of the secret survive + ])('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(out).not.toContain(needle); - expect(out.startsWith('aaaa')).toBe(true); - expect(out.endsWith(TRUNCATION_MARKER)).toBe(true); + 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}`); }); }); diff --git a/packages/performance/src/attribute-value.ts b/packages/performance/src/attribute-value.ts index 184b168ad..fe5bd5f24 100644 --- a/packages/performance/src/attribute-value.ts +++ b/packages/performance/src/attribute-value.ts @@ -1,4 +1,4 @@ -import { lastSecretShapeStart, REDACTED } from '@bugsee/protocol'; +import { REDACTED, unfinishedSecretStart } from '@bugsee/protocol'; // Span attribute values: bounding, safe copying and the wire flattening of complex values. // @@ -113,10 +113,11 @@ const capText = (text: string, max: number, dropPartialToken = false): string => 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 the LAST place a secret shape begins in it: a secret - // the cut leaves half-written no longer matches `redactShapes`, so its readable part would ship as is. + // 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 = lastSecretShapeStart(text.slice(0, cut)); + const start = unfinishedSecretStart(text.slice(0, cut)); end = start === -1 ? cut : start; } } diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index 1ea187678..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 { lastSecretShapeStart, 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/shapes.test.ts b/packages/protocol/src/shapes.test.ts index 3cf8d79d9..a905789ae 100644 --- a/packages/protocol/src/shapes.test.ts +++ b/packages/protocol/src/shapes.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { lastSecretShapeStart, redactShapes } from './index'; +import { redactShapes, unfinishedSecretStart } from './index'; const R = ''; @@ -299,43 +299,101 @@ describe('the JWT bound sits at 8 KB, where the reachable window is', () => { }); }); -describe('lastSecretShapeStart', () => { - // One COMPLETE secret per shape redactShapes knows. The start finder must locate the beginning of each, so - // a caller that has to cut text can back off before a secret that the cut would leave half-written (a - // partial secret no longer matches redactShapes, so it would ship in the clear). A new pattern in - // SHAPE_PATTERNS needs a sample here: this is the drift guard. - 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)}`, +// 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.each( - Object.entries(SAMPLES), - )('finds the start of a %s secret, and redactShapes agrees it is one', (_name, secret) => { - expect(redactShapes(secret)).not.toBe(secret); - // A JWT's payload segment (`{"...` base64url) also begins `eyJ`, so its LAST start is the payload's. - const start = secret.startsWith('eyJ') ? secret.lastIndexOf('eyJ') : 0; - expect(lastSecretShapeStart(secret)).toBe(start); - expect(lastSecretShapeStart(`prefix-${secret}`)).toBe(7 + start); - expect(lastSecretShapeStart(`id_token=${secret.slice(0, 8)}`)).toBe(9); // a half-written one too - }); - - it('returns the LAST start when several are present, and -1 when there is none', () => { - const text = `${SAMPLES.jwt}/${SAMPLES['github ghp']}/plain`; - expect(lastSecretShapeStart(text)).toBe((SAMPLES.jwt?.length ?? 0) + 1); - expect(lastSecretShapeStart('nothing secret here, just words and AKI')).toBe(-1); - expect(lastSecretShapeStart('')).toBe(-1); + 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('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); }); }); diff --git a/packages/protocol/src/shapes.ts b/packages/protocol/src/shapes.ts index da353f0ee..7c3ccf6d6 100644 --- a/packages/protocol/src/shapes.ts +++ b/packages/protocol/src/shapes.ts @@ -73,35 +73,62 @@ 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 ]; +const SHAPE_PATTERNS: readonly RegExp[] = SHAPES.map( + ({ start, rest }) => new RegExp(`${start}${rest}`, 'g'), +); + +/** 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'); + /** - * Where a secret shape BEGINS: the opening of each pattern in {@link SHAPE_PATTERNS} plus the JWT header. - * Kept next to those patterns (and guarded by a sample per shape in the tests) so the two cannot drift. + * 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 SECRET_SHAPE_START = /eyJ|A(?:KIA|SIA|GPA|IDA|ROA)|(?:sk|pk|rk)_live_|whsec_|gh[posu]_/g; +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 of the LAST place in `text` where a secret shape begins, or -1. 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 it would reach the wire in the clear. + * 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 lastSecretShapeStart(text: string): number { - let last = -1; - SECRET_SHAPE_START.lastIndex = 0; - for ( - let match = SECRET_SHAPE_START.exec(text); - match !== null; - match = SECRET_SHAPE_START.exec(text) - ) { - last = match.index; +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 last; + return current === -1 || beginsWithSecret(text.slice(current)) ? -1 : current; } function isLuhnValid(digits: string): boolean { From b3ad7a8a3ba0775975e0972b0f1294ca0364dc0b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 22 Oct 2026 08:10:31 +0500 Subject: [PATCH 16/16] test(protocol,performance): pin the start-check cap, the JWT-with-embedded-secret case and shape grouping; doc corrections (#94) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- docs/design/opentelemetry-integration.md | 12 +++-- .../performance/src/attribute-value.test.ts | 8 ++++ packages/protocol/src/shapes.test.ts | 44 +++++++++++++++++++ packages/protocol/src/shapes.ts | 13 ++++-- 4 files changed, 70 insertions(+), 7 deletions(-) diff --git a/docs/design/opentelemetry-integration.md b/docs/design/opentelemetry-integration.md index 9e5bc6698..0da8fc508 100644 --- a/docs/design/opentelemetry-integration.md +++ b/docs/design/opentelemetry-integration.md @@ -292,10 +292,14 @@ contains `eyJ` because it holds a nested `{"` claim, an `ASIA` inside an AWS key 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). Stripe-style keys are never "unfinished", because their patterns match a partial -key. 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 at most 16 starts per call and past that -backs off to the current candidate (more dropped, never less). `:` is not a token character, so a long map-leaf +`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 diff --git a/packages/performance/src/attribute-value.test.ts b/packages/performance/src/attribute-value.test.ts index c70b1f85a..e6b914d94 100644 --- a/packages/performance/src/attribute-value.test.ts +++ b/packages/performance/src/attribute-value.test.ts @@ -577,6 +577,14 @@ describe('a cut never leaves a PARTIAL secret-shaped token behind (where shape s } }); + 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)}`; diff --git a/packages/protocol/src/shapes.test.ts b/packages/protocol/src/shapes.test.ts index a905789ae..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, unfinishedSecretStart } from './index'; +import { compileShapePattern } from './shapes'; const R = ''; @@ -390,6 +391,42 @@ describe('unfinishedSecretStart', () => { 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(); @@ -397,3 +434,10 @@ describe('unfinishedSecretStart', () => { 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 7c3ccf6d6..00a72afae 100644 --- a/packages/protocol/src/shapes.ts +++ b/packages/protocol/src/shapes.ts @@ -85,12 +85,19 @@ const SHAPES: readonly { start: string; rest: string }[] = [ { start: 'gh[posu]_', rest: '[A-Za-z0-9]{36,}' }, // GitHub personal access / OAuth / user / server token ]; -const SHAPE_PATTERNS: readonly RegExp[] = SHAPES.map( - ({ start, rest }) => new RegExp(`${start}${rest}`, 'g'), +/** 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'); +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