From bb5b51bc52f64aafc99da4d860915c6c5749be1d Mon Sep 17 00:00:00 2001 From: RiyaSunil27 Date: Fri, 20 Nov 2026 17:02:43 +0530 Subject: [PATCH 1/2] fix: Bound span exports, keep API key off non-Netra hosts, isolate request scopes, and fix stream, payload, scrubbing, API-client and lifecycle issues --- CHANGELOG.md | 47 +++ README.md | 26 +- package-lock.json | 8 +- package.json | 3 +- src/api/dashboard/api.ts | 9 + src/api/evaluation/api.ts | 8 +- src/api/evaluation/utils.ts | 16 +- src/api/http-client.ts | 139 ++++--- src/api/prompts/api.ts | 46 ++- src/config.ts | 135 ++++--- src/decorators.ts | 26 +- src/exporters/filteringSpanExporter.ts | 2 + src/exporters/trialAwareOtlpExporter.ts | 369 +++++++++++++++---- src/exporters/utils.ts | 41 ++- src/index.ts | 15 +- src/instrumentation/google-genai/wrappers.ts | 5 +- src/instrumentation/groq/wrappers.ts | 15 +- src/instrumentation/index.ts | 220 ++++++++--- src/instrumentation/langgraph/utils.ts | 24 +- src/instrumentation/langgraph/wrappers.ts | 3 +- src/instrumentation/mistralai/index.ts | 7 +- src/instrumentation/mistralai/utils.ts | 14 + src/instrumentation/mistralai/wrappers.ts | 20 +- src/instrumentation/openai/wrappers.ts | 9 +- src/instrumentation/typeorm/utils.ts | 23 +- src/instrumentation/utils.ts | 40 +- src/netraLogger.test.ts | 3 +- src/processors/root-span-processor.ts | 12 + src/processors/scrubbing-span-processor.ts | 108 ++++-- src/processors/span-io-processor.ts | 74 +++- src/session-manager.ts | 139 +++---- src/simulation/api.ts | 31 +- src/simulation/client.ts | 10 + src/simulation/download-guard.ts | 110 ++++++ src/simulation/utils.ts | 16 + src/utils/response-handler.ts | 169 ++++++++- src/utils/serialization/safe-stringify.ts | 95 ++++- 37 files changed, 1628 insertions(+), 409 deletions(-) create mode 100644 src/simulation/download-guard.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index eb86ea7..f656515 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,53 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- **`Netra.withSession()` and `Netra.clearSession()`**: `Netra.withSession({ userId, sessionId, tenantId }, fn)` applies the identity to every span started inside `fn`. `Netra.clearSession()` clears the identity set for the current request or async flow. + +### Changed + +- **Identity Stays in Your Process**: `setSessionId`, `setUserId` and `setTenantId` no longer write W3C baggage, so the values are no longer sent in the `baggage` header of every outgoing HTTP and `fetch` request, for example to AI providers (JS-SEC-002). The values apply to the current request or async flow only. A value set in one request no longer shows up on later requests that set none (JS-SEC-003). Calling a setter before `Netra.init()`, or with a context manager other than Netra's registered first, now prints a one-time warning, and the value applies only to the active span. +- **Incoming Baggage Is No Longer Trusted**: `user_id`, `session_id`, `tenant_id` and `custom_keys` in an incoming `baggage` header no longer set the identity or custom attributes of the request's spans. `netra.*` baggage keys are dropped on incoming and outgoing requests, so a caller can no longer hide its requests by sending `netra.local_blocked_spans` (JS-SEC-001). `withBlockedSpansLocal` and `startSpan`'s `blockedSpans` still work, and their patterns are no longer sent to downstream services. +- **`traceContent: false` Applies Everywhere**: Function arguments and return values from `@workflow`, `@agent`, `@task` and `@span`, LangGraph graph state, node and tool input and output, and OpenAI Agents prompts, instructions, completions, tool input and output, MCP data and custom span data are no longer recorded when content tracing is off. Explicit `setInput`, `setOutput`, `setRootInput`, `setRootOutput` and `addConversation` calls are also dropped. Content keys are filtered centrally, so no integration can record them. This includes the OpenTelemetry GenAI keys (`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.call.arguments`/`result`) that Traceloop's LangChain integration kept writing with content off (JS-SEC-004). +- **Tool Definitions Are Redacted**: Credentials in tool definitions, such as remote MCP `headers`, connector `authorization` and `authorization_token`, are recorded as `[REDACTED]`. With content tracing off, only each tool's type and name are recorded (JS-SEC-005). +- **Database Query Parameters Are Opt-In**: TypeORM spans no longer record query parameter values such as emails and reset tokens. They record `db.statement.parameters.count` instead. Set `NETRA_TRACE_DB_PARAMETERS=true` to record the values; it takes effect only while content capture is on (JS-SEC-016). +- **The API Key Only Goes to Netra**: Whether an endpoint belongs to Netra is now decided by its host (`getnetra.ai` and its subdomains), not by `getnetra` appearing anywhere in the URL. When the endpoint comes only from `OTEL_EXPORTER_OTLP_ENDPOINT` and is not a Netra host, `NETRA_API_KEY` is no longer sent to it, by the span exporter or the API clients, and a warning says so. An explicit `NETRA_OTLP_ENDPOINT`, including a self-hosted Netra, still receives the key (JS-SEC-006). +- **No Secrets or Shared Settings in `process.env`**: `Netra.init()` no longer copies the API key, the export headers or the endpoint into `TRACELOOP_API_KEY`, `TRACELOOP_HEADERS` and `TRACELOOP_BASE_URL`, which every child process inherited, and no longer overwrites `TRACELOOP_TRACE_CONTENT`. `OTEL_RESOURCE_ATTRIBUTES` is set only while the tracer starts and is then restored. The `headers` object passed to `Netra.init()` is no longer modified (JS-SEC-007, JS-SEC-022). +- **Span Uploads Are Bounded and Retried**: Each batch has a time limit of 10 s, retries included, set with `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` or `OTEL_EXPORTER_OTLP_TIMEOUT`. Connection errors, timeouts, 408, 429 and 502/503/504 are retried up to 5 times with jittered backoff, honouring `Retry-After`. At most 16 uploads run at once; further batches wait in a queue of up to 1,024 and are dropped only when it is full. Only the first 64 KiB of an error response is read (JS-MEM-002, JS-PERF-006). +- **Only `QUOTA_EXCEEDED` Pauses Uploads**: The 15-minute export pause now starts only when the backend reports exhausted quota (`errorCode: "QUOTA_EXCEEDED"`, or a "usage quota exceeded" message). An ordinary 429 rate limit is retried instead. Trace ids remembered during a pause now expire after 30 minutes, at most 10,000 are kept, and they are cleared on shutdown (JS-MEM-004). +- **Faster Startup**: The Traceloop SDK and its dependency tree now load on the first `Netra.init()` instead of when `netra-sdk` is imported. Loading the package took about 610 ms and now takes about 140 ms (JS-PERF-007). +- **Nothing Global Until `Netra.init()`**: Importing the SDK no longer registers a global propagator. Netra's propagator is registered when tracing starts. If the app registered its own `TracerProvider` first, Netra now prints a warning and leaves that provider alone, instead of adding its processors to it and rewriting the app's own spans (JS-SEC-011). +- **Lazy Query Builders Are Not Run Early**: A traced function that returns a thenable that is not a real Promise, such as a Knex, Prisma or Mongoose query builder, gets it back untouched; the SDK no longer calls `then()`, which ran the query early and outside the caller's transaction. Such spans end without an output (JS-SEC-010). +- **Scrubbing Covers More and Matches Keys Exactly**: With `enableScrubbing`, attributes passed when a span starts, span events (including recorded exceptions), status messages and span names are scrubbed too. Sensitive attribute names are matched by whole name parts, so keys such as `netra.span.type` or `gen_ai.request.max_tokens` are no longer replaced. The email pattern no longer backtracks on crafted input, which could block the app for seconds (JS-SEC-009, JS-SEC-021). +- **Per-Chunk Stream Events Only in Debug Mode**: OpenAI, Groq and Mistral streams record an `llm.content.completion.chunk` event per chunk only in debug mode, as Anthropic and Google GenAI already did (JS-PERF-014). +- **Bounded Simulations and Evaluations**: A simulated conversation stops after 100 turns (`NETRA_SIMULATION_MAX_TURNS`). Simulation attachments must use https, may not point to private or local addresses, follow at most 3 redirects and are limited to 50 MiB (`NETRA_SIMULATION_MAX_FILE_BYTES`). Evaluator runs share the test run's `maxConcurrency` instead of all starting at once. Session-stats iteration stops when a page reports more results without a new cursor (JS-SEC-017, JS-PERF-010, JS-PERF-011). +- **More Robust API Clients**: Netra API calls have one time limit covering the response body, read at most 10 MiB, retry GET requests on network errors, 429 and 502/503/504, and follow redirects only within the API's own origin, so `x-api-key` is never sent to another host (JS-PERF-009, JS-SEC-017). +- **Smaller Package and Dependency Upkeep**: The published package no longer includes source maps (765 kB to 255 kB packed). A CI workflow type-checks, tests and builds every change, checks that `require("netra-sdk")` works on Node 18, 20.18 and 22.11, and reports `npm audit` results; Dependabot keeps dependencies and actions current. `follow-redirects` and `zod` are updated past their advisories (JS-SEC-020, JS-SEC-026). + +### Fixed + +- **Memory Leak Behind Gateways and Service Meshes**: Every request that arrived with a `traceparent` header and made an LLM call left a trace id in memory that was never freed. The first span of a trace in this process now counts as its root even when its parent is remote. As a result, `netra.trace.llm.call` and `setRootInput`/`setRootOutput` now also work for such requests (JS-MEM-001). +- **No Crash or API Key Leak Without an Endpoint**: Without `NETRA_OTLP_ENDPOINT`, the underlying Traceloop SDK fetched prompts from `api.traceloop.com` in the background, sending the Netra API key there. If the host could not be reached, the app crashed with an unhandled rejection. This prompt sync is now off (JS-PERF-001). +- **CommonJS on Node 18, 20 < 20.19 and 22 < 22.12**: `require("netra-sdk")` threw `ERR_REQUIRE_ESM` because of the ESM-only `p-limit` dependency. It is replaced by an internal concurrency limiter (JS-PERF-004). +- **Concurrent Requests No Longer Share Workflow, Agent and Task Names**: Decorated functions pushed their names onto one process-wide stack, so under concurrency spans got another request's `netra.workflow.name`, `netra.agent.name` and `netra.task.name`. Each decorated call now runs in its own entity scope (JS-SEC-018). +- **Unfinished Spans No Longer Stay in Memory**: The span-name registry is kept per entity scope instead of in a module global, and at most 10,000 root spans are tracked, so spans that never end are no longer held for the life of the process (JS-MEM-005). +- **Scripts Exit When Netra Hangs**: When the flush in `Netra.shutdown()` does not finish within 5 s, uploads still in flight are aborted, so an endpoint that accepts connections but never answers no longer keeps a finished script, job or serverless handler running (JS-PERF-003). +- **Streams Read Other Ways End Their Span**: The span of an Anthropic `create({ stream: true })` call now ends when the stream comes from `.withResponse()`, and when the raw response is read through `.asResponse()`. A LangGraph `stream()` read with `getReader()`, or cancelled, ends its span too. A stream the app drops without reading or cancelling has its span ended once the stream is garbage-collected. These spans were never exported and stayed in memory (JS-MEM-003). +- **`%` in `OTEL_RESOURCE_ATTRIBUTES` No Longer Breaks `init()`**: A raw `%`, as in `team=R%D`, made `Netra.init()` throw `URIError`. The value is now kept as written (JS-PERF-008). +- **Long Chat Histories No Longer Block the App**: Each prompt or completion message used to rebuild and re-stringify the whole history; a 1,000-message prompt took about 2.7 s and over 3,700 `JSON.stringify` calls. The history is now rebuilt once, and each stored message is cut to `NETRA_SPAN_ATTRIBUTE_MAX_SIZE` (JS-PERF-002, JS-MEM-006). +- **Large Inputs Are Not Serialized in Full**: Traced function arguments and results, and LangGraph state, are serialized up to twice the attribute size limit instead of in full before truncation. Buffers and typed arrays are recorded as `[Buffer N bytes]` instead of an array with one number per byte (JS-MEM-007, JS-PERF-012). +- **Recording Never Breaks the App's Call**: LangGraph state, Groq and Mistral requests, and request `reasoning` settings that cannot be turned into JSON (circular, `BigInt`) no longer make the call fail (JS-PERF-005). +- **Re-initializing Replaces Netra's Processors**: Each `Netra.init()` after `Netra.shutdown()` added another full set of span processors. The previous set is now replaced. The `LocalFilteringSpanProcessor` registered on the provider is now the one configured with `blockedSpans` and shared with the exporter, so blocked spans' children are reparented as intended (JS-MEM-008). +- **Bounded Streamed Choices**: A streamed `choice.index` of 128 or more, or an invalid one, is ignored instead of growing the choices array up to it (JS-MEM-009). +- **Google GenAI Chat History Read Only With Content Tracing**: `Chat.getHistory()`, which may copy the whole history, is no longer called when content tracing is off (JS-PERF-013). +- **Prompt Cache**: Names and labels containing `:` no longer share a cache entry, and concurrent `getPrompt` calls for a missing entry share one request (JS-SEC-023, JS-PERF-015). +- **Safe Export Error Logs**: Error text from the trace endpoint is capped at 200 characters and its control characters are escaped, so a collector cannot inject or flood log lines (JS-SEC-024). +- **Fewer Side Effects in Other Libraries**: The filter that removes Traceloop's LangChain callback is installed only when Traceloop patched LangChain, and the Mistral instrumentation no longer passes the app's `MISTRAL_API_KEY` to the throwaway client it builds to find constructors (JS-SEC-025). +- **Evaluation Session ID**: `Evaluation.runTestSuite` reads the session id from the value set with `Netra.setSessionId()`/`Netra.withSession()`, now that session values are no longer kept in baggage. + ## [1.12.2] - 2026-11-04 ### Changed diff --git a/README.md b/README.md index 93c8a25..7001989 100644 --- a/README.md +++ b/README.md @@ -300,10 +300,34 @@ You can configure the SDK using environment variables: | Variable | Description | |----------|-------------| | `NETRA_OTLP_ENDPOINT` | Netra endpoint: `https://api.getnetra.ai/telemetry` (US) or `https://api.eu.getnetra.ai/telemetry` (EU). Required to send traces to Netra; falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`, and if neither is set, spans are printed to the console | -| `NETRA_API_KEY` | API Key for Netra Platform | +| `NETRA_API_KEY` | API Key for Netra Platform. Not sent to an endpoint that comes only from `OTEL_EXPORTER_OTLP_ENDPOINT` unless it is a Netra host (`*.getnetra.ai`) | | `NETRA_APP_NAME` | Name of your application | | `NETRA_ENV` | Environment (e.g., prod, dev) | | `NETRA_TRACE_CONTENT` | Capture prompt/completion content (default: true) | +| `NETRA_TRACE_DB_PARAMETERS` | Record database query parameter values on TypeORM spans (default: false). Takes effect only while content capture is on; otherwise only the parameter count is recorded | +| `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` | Time limit in ms for sending one batch of spans, retries included (default: 10000; falls back to `OTEL_EXPORTER_OTLP_TIMEOUT`) | +| `NETRA_SIMULATION_MAX_TURNS` | Most turns one simulated conversation may take before it is marked failed (default: 100) | +| `NETRA_SIMULATION_MAX_FILE_BYTES` | Largest simulation attachment downloaded, in bytes (default: 52428800, 50 MiB). Attachments must use https and may not point to private or local addresses | + +## 🔒 Security Notes + +**Pin patched OpenTelemetry packages in your app.** `@traceloop/node-server-sdk` (a dependency of this SDK) still depends on `@opentelemetry/sdk-node` 0.203, which brings in OpenTelemetry packages with published advisories. npm does not apply a library's own `overrides` to your install, so add them to your application's `package.json`: + +```json +{ + "overrides": { + "@opentelemetry/sdk-node": "^0.222.0", + "@opentelemetry/core": "^2.11.0", + "@opentelemetry/propagator-jaeger": "^2.11.0", + "@opentelemetry/exporter-prometheus": "^0.222.0" + } +} +``` + +**Call `Netra.init()` before other OpenTelemetry setup.** If another `TracerProvider` is registered first, Netra prints a warning, does not add its processors to that provider, and receives no spans. + +**OpenAI Agents native tracing.** By default (`netra-strict`), Netra replaces the Agents SDK's trace processors so traces are not also sent to OpenAI. Processors your app adds with `addTraceProcessor()` before `Netra.init()` are replaced too; add them after `Netra.init()`, or set `NATIVE_TRACING_MODE=netra` or `both` to keep them. + ## 🤝 License diff --git a/package-lock.json b/package-lock.json index dbd9e44..3408235 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3753,7 +3753,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.16.1", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", "funding": [ { "type": "individual", @@ -5676,7 +5678,9 @@ } }, "node_modules/zod": { - "version": "4.3.5", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/package.json b/package.json index a25d963..badcba9 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ } }, "files": [ - "dist" + "dist", + "!dist/**/*.map" ], "scripts": { "build": "tsup", diff --git a/src/api/dashboard/api.ts b/src/api/dashboard/api.ts index afd9535..911a66f 100644 --- a/src/api/dashboard/api.ts +++ b/src/api/dashboard/api.ts @@ -167,6 +167,15 @@ async getSessionStats( break; } + // A page that claims more without a new cursor would request the same + // page again forever (JS-PERF-011). + if (!result.nextCursor || result.nextCursor === cursor) { + NetraLogger.warn( + "netra.dashboard: session stats reported more pages without a new cursor; stopping", + ); + break; + } + cursor = result.nextCursor; } } diff --git a/src/api/evaluation/api.ts b/src/api/evaluation/api.ts index 36f5239..b2aa7b9 100644 --- a/src/api/evaluation/api.ts +++ b/src/api/evaluation/api.ts @@ -6,6 +6,7 @@ import { Config } from "../../config"; import { NetraLogger } from "../../netraLogger"; import { SpanWrapper } from "../../span-wrapper"; +import { createLimit, LimitFunction } from "../../utils/concurrency-limit"; import { EvaluationHttpClient } from "./client"; import { AddDatasetItemResponse, @@ -288,6 +289,9 @@ export class Evaluation { NetraLogger.info("netra.evaluation: Initiated test run"); const semaphore = new Semaphore(Math.max(1, maxConcurrency)); + // Evaluator runs (each polls for span ingestion for up to 60 s) share the + // run's concurrency limit instead of all starting at once (JS-PERF-010). + const evalLimit = createLimit(Math.max(1, maxConcurrency)); const results: Array> = []; const bgEvalTasks: Promise[] = []; let completedItems = 0; @@ -304,6 +308,7 @@ export class Evaluation { evaluators, results, bgEvalTasks, + evalLimit, ); completedItems += 1; @@ -380,6 +385,7 @@ export class Evaluation { evaluators: any[] | undefined, results: Array>, bgEvalTasks: Promise[], + evalLimit: LimitFunction, ): Promise<{ status: string }> { const spanName = `TestRun.${runName}`; @@ -410,7 +416,7 @@ export class Evaluation { ); if (evaluators && ctx.status === "completed") { - const evalTask = this.runEvaluatorsForItem(runId, ctx, evaluators); + const evalTask = evalLimit(() => this.runEvaluatorsForItem(runId, ctx, evaluators)); bgEvalTasks.push(evalTask); } diff --git a/src/api/evaluation/utils.ts b/src/api/evaluation/utils.ts index 89b9f11..ad720fc 100644 --- a/src/api/evaluation/utils.ts +++ b/src/api/evaluation/utils.ts @@ -2,21 +2,19 @@ * Evaluation Utility Functions */ -import { propagation, context as otelContext } from "@opentelemetry/api"; import { NetraLogger } from "../../netraLogger"; +import { getSessionValue } from "../../processors/session-span-processor"; import { DatasetRecord, EvaluatorConfig, ItemContext } from "./models"; /** - * Get the session ID from the OpenTelemetry baggage + * The session id the app set with `Netra.setSessionId()` or + * `Netra.withSession()` for the current async context. Session values are no + * longer kept in W3C baggage, where a caller could forge them (JS-SEC-001), + * so they are read from the SDK's private context value. */ export function getSessionIdFromBaggage(): string | undefined { - const ctx = otelContext.active(); - const baggageObj = propagation.getBaggage(ctx); - const sessionId = baggageObj?.getEntry("session_id")?.value; - if (typeof sessionId === "string" && sessionId) { - return sessionId; - } - return undefined; + const sessionId = getSessionValue("session_id"); + return typeof sessionId === "string" && sessionId ? sessionId : undefined; } /** diff --git a/src/api/http-client.ts b/src/api/http-client.ts index 7213bd5..39c9daf 100644 --- a/src/api/http-client.ts +++ b/src/api/http-client.ts @@ -19,6 +19,37 @@ export interface HttpResponse { ok: boolean; } +const MAX_GET_ATTEMPTS = 3; +const RETRY_BASE_MS = 500; +const MAX_REDIRECTS = 3; +/** API responses larger than this are rejected rather than buffered. */ +const MAX_RESPONSE_BYTES = 10 * 1024 * 1024; +const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]); + +/** Read a response body as text, failing once it passes `maxBytes`. */ +async function readBodyCapped(response: Response, maxBytes: number): Promise { + const declared = Number(response.headers.get("content-length")); + if (Number.isFinite(declared) && declared > maxBytes) { + await response.body?.cancel().catch(() => {}); + throw new Error(`response of ${declared} bytes exceeds the ${maxBytes}-byte limit`); + } + if (!response.body) return ""; + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => {}); + throw new Error(`response exceeds the ${maxBytes}-byte limit`); + } + chunks.push(value); + } + return Buffer.concat(chunks).toString("utf8"); +} + export class NetraHttpClient { private baseUrl: string; private headers: Record; @@ -120,26 +151,7 @@ export class NetraHttpClient { } try { - const controller = new AbortController(); - const timeoutId = setTimeout( - () => controller.abort(), - this.timeout * 1000 - ); - - const response = await fetch(url.toString(), { - method: "GET", - headers: injectTraceContextHeaders(this.headers), - signal: controller.signal, - }); - - clearTimeout(timeoutId); - - const data = await response.json(); - return { - data, - status: response.status, - ok: response.ok, - }; + return await this.request("GET", url); } catch (error) { NetraLogger.notice("error", `netra: GET ${path} failed:`, error); return { data: {} as T, status: 0, ok: false }; @@ -161,33 +173,78 @@ export class NetraHttpClient { const url = new URL(path, this.baseUrl); try { - const controller = new AbortController(); - const timeoutId = setTimeout( - () => controller.abort(), - this.timeout * 1000 - ); - - const response = await fetch(url.toString(), { - method: "POST", - headers: injectTraceContextHeaders(this.headers), - body: body ? JSON.stringify(body) : undefined, - signal: controller.signal, - }); - - clearTimeout(timeoutId); - - const data = await response.json(); - return { - data, - status: response.status, - ok: response.ok, - }; + return await this.request("POST", url, body ? JSON.stringify(body) : undefined); } catch (error) { NetraLogger.notice("error", `netra: POST ${path} failed:`, error); return { data: {} as T, status: 0, ok: false }; } } + /** + * One API call within `this.timeout` seconds, body read included + * (JS-PERF-009). GETs are retried on network errors, 429 and 502/503/504; + * POSTs are not, since they may not be idempotent. Redirects are followed + * only within the API's own origin, so `x-api-key` never reaches another + * host (JS-SEC-017). + */ + private async request(method: "GET" | "POST", url: URL, body?: string): Promise> { + const deadline = Date.now() + this.timeout * 1000; + const maxAttempts = method === "GET" ? MAX_GET_ATTEMPTS : 1; + let lastError: unknown; + + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + const remaining = deadline - Date.now(); + if (remaining <= 0) break; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), remaining); + try { + const response = await this.fetchSameOrigin(url, { + method, + headers: injectTraceContextHeaders(this.headers), + body, + signal: controller.signal, + }); + const text = await readBodyCapped(response, MAX_RESPONSE_BYTES); + if (method === "GET" && RETRYABLE_STATUSES.has(response.status) && attempt < maxAttempts) { + lastError = new Error(`HTTP ${response.status}`); + } else { + return { + data: (text ? JSON.parse(text) : {}) as T, + status: response.status, + ok: response.ok, + }; + } + } catch (error) { + lastError = error; + if (controller.signal.aborted || attempt >= maxAttempts) break; + } finally { + // Always cleared: a timer left armed after a failed request kept the + // process alive for up to the full timeout. + clearTimeout(timeoutId); + } + const wait = Math.round(RETRY_BASE_MS * 2 ** (attempt - 1) * (0.8 + Math.random() * 0.4)); + if (Date.now() + wait >= deadline) break; + await new Promise((resolve) => setTimeout(resolve, wait)); + } + throw lastError ?? new Error(`timed out after ${this.timeout}s`); + } + + private async fetchSameOrigin(url: URL, init: RequestInit): Promise { + let current = url; + for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { + const response = await fetch(current.toString(), { ...init, redirect: "manual" }); + if (response.status < 300 || response.status >= 400) return response; + const location = response.headers.get("location"); + if (!location) return response; + const next = new URL(location, current); + if (next.origin !== current.origin) { + throw new Error(`refusing to follow a redirect to another origin (${next.origin})`); + } + current = next; + } + throw new Error("too many redirects"); + } + /** * Extract data from nested response format * Netra API typically returns { data: { data: actualData } } diff --git a/src/api/prompts/api.ts b/src/api/prompts/api.ts index 2fe6b8e..001aa3e 100644 --- a/src/api/prompts/api.ts +++ b/src/api/prompts/api.ts @@ -12,6 +12,7 @@ export class Prompts { private config: Config; private client: PromptsHttpClient; private cache: TTLCache; + private readonly inFlight = new Map>(); constructor(config: Config) { this.config = config; @@ -40,27 +41,42 @@ export class Prompts { const label = params.label ?? "production"; const useCache = params.useCache === true; - const cacheKey = `prompt:${params.name}:${label}`; + // JSON keeps name and label apart: with a ":" join, name "a:b" + label + // "c" and name "a" + label "b:c" shared one entry (JS-SEC-023). + const cacheKey = `prompt:${JSON.stringify([params.name, label])}`; - if (useCache) { - const cached = this.cache.get(cacheKey); - if (cached !== undefined) { - return cached; - } + if (!useCache) { + return this.fetchPrompt(params.name, label); } - const result = await this.client.getPromptVersion(params.name, label); - - if (!result) { - return null; + const cached = this.cache.get(cacheKey); + if (cached !== undefined) { + return cached; } - const data = result.data ?? null; - - if (data !== null && useCache) { - this.cache.set(cacheKey, data, params.cacheTtl); + // Concurrent misses for the same key share one request instead of each + // fetching the prompt (JS-PERF-015). + let pending = this.inFlight.get(cacheKey); + if (!pending) { + pending = this.fetchPrompt(params.name, label) + .then((data) => { + if (data !== null) this.cache.set(cacheKey, data, params.cacheTtl); + return data; + }) + .finally(() => this.inFlight.delete(cacheKey)); + this.inFlight.set(cacheKey, pending); } + const data = await pending; + if (data === null) return null; + // Each caller gets its own copy from the cache, as a cache hit does. + return this.cache.get(cacheKey) ?? structuredClone(data); + } - return data; + private async fetchPrompt(name: string, label: string): Promise { + const result = await this.client.getPromptVersion(name, label); + if (!result) { + return null; + } + return result.data ?? null; } } diff --git a/src/config.ts b/src/config.ts index 8ca6e40..9f7ea0a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -2,11 +2,37 @@ * Configuration management for Netra SDK */ +import { setTraceContentEnabled } from "./instrumentation/utils"; import { NetraLogger } from "./netraLogger"; import { SDK_VERSION } from "./version"; // The only header the Netra backend's API-key guard reads. Lowercase, for case-insensitive matching. const NETRA_API_KEY_HEADER = "x-api-key"; +const NETRA_HOST_SUFFIX = "getnetra.ai"; + +/** + * True when `endpoint` is a Netra-hosted URL (`getnetra.ai` or a subdomain). + * Decided on the parsed hostname: a substring test on the whole URL would + * also match `https://collector.example/getnetra` (JS-SEC-006). + */ +export function isNetraHost(endpoint: string | undefined): boolean { + if (!endpoint) return false; + try { + const host = new URL(endpoint.trim()).hostname.toLowerCase(); + return host === NETRA_HOST_SUFFIX || host.endsWith(`.${NETRA_HOST_SUFFIX}`); + } catch { + return false; + } +} + +/** decodeURIComponent that returns the input unchanged on malformed escapes (JS-PERF-008). */ +function safeDecodeURIComponent(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} export interface NetraConfig { appName?: string; @@ -163,6 +189,8 @@ export class Config { appName: string; otlpEndpoint?: string; + /** Which variable `otlpEndpoint` came from. */ + otlpEndpointSource?: "NETRA_OTLP_ENDPOINT" | "OTEL_EXPORTER_OTLP_ENDPOINT"; apiKey?: string; headers: Record; disableBatch: boolean; @@ -176,7 +204,7 @@ export class Config { constructor(config: NetraConfig = {}) { this.appName = this._getAppName(config.appName); this.otlpEndpoint = this._getOtlpEndpoint(); - this.apiKey = process.env.NETRA_API_KEY; + this.apiKey = this._getApiKey(); this.headers = this._parseHeaders(config.headers); this.disableBatch = this._getBoolConfig( config.disableBatch, @@ -206,7 +234,10 @@ export class Config { this._validateApiKey(); this._setupAuthentication(); - this._setTraceContentEnv(); + // Kept in-process, not in TRACELOOP_TRACE_CONTENT: overwriting that shared + // env var changed other tracing tools' behaviour and leaked into child + // processes (JS-SEC-007). + setTraceContentEnabled(this.traceContent); } private _getAppName(appName?: string): string { @@ -220,9 +251,41 @@ export class Config { } private _getOtlpEndpoint(): string | undefined { - return ( - process.env.NETRA_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT - ); + if (process.env.NETRA_OTLP_ENDPOINT) { + this.otlpEndpointSource = "NETRA_OTLP_ENDPOINT"; + return process.env.NETRA_OTLP_ENDPOINT; + } + if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) { + this.otlpEndpointSource = "OTEL_EXPORTER_OTLP_ENDPOINT"; + return process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + } + return undefined; + } + + /** + * NETRA_API_KEY, unless the endpoint only came from the generic + * OTEL_EXPORTER_OTLP_ENDPOINT and is not a Netra host. That variable usually + * points at another vendor or a shared collector, which must not receive a + * working Netra key (JS-SEC-006). An explicit NETRA_OTLP_ENDPOINT, including + * a self-hosted Netra, keeps receiving it. + */ + private _getApiKey(): string | undefined { + const key = process.env.NETRA_API_KEY; + if ( + key && + this.otlpEndpointSource === "OTEL_EXPORTER_OTLP_ENDPOINT" && + !isNetraHost(this.otlpEndpoint) + ) { + let host = "that endpoint"; + try { host = new URL(String(this.otlpEndpoint).trim()).host; } catch { /* keep generic */ } + NetraLogger.notice( + "warn", + `NETRA_API_KEY is not sent to ${host}: it comes from OTEL_EXPORTER_OTLP_ENDPOINT and is not a Netra endpoint. ` + + "Fix: set NETRA_OTLP_ENDPOINT to https://api.getnetra.ai/telemetry (or your Netra endpoint).", + ); + return undefined; + } + return key; } private _parseHeaders( @@ -240,7 +303,9 @@ export class Config { return this._parseEnvHeaders(headers); } - return headers; + // A copy: authentication headers are added below, and must not be written + // into the object the application passed in (JS-SEC-022). + return { ...headers }; } private _parseEnvHeaders(headers: string): Record { @@ -261,11 +326,7 @@ export class Config { * (through `headers` or NETRA_HEADERS); header names match case-insensitively. */ private _validateApiKey(): void { - if ( - !this.otlpEndpoint || - !this.otlpEndpoint.toLowerCase().includes("getnetra") || - this.apiKey - ) { + if (!this.otlpEndpoint || !isNetraHost(this.otlpEndpoint) || this.apiKey) { return; } const hasApiKeyHeader = Object.keys(this.headers).some( @@ -285,7 +346,7 @@ export class Config { return; } - const isNetra = this.otlpEndpoint.toLowerCase().includes("getnetra"); + const isNetra = isNetraHost(this.otlpEndpoint); const authKey = isNetra ? "x-api-key" : "Authorization"; const authValue = isNetra ? this.apiKey : `Bearer ${this.apiKey}`; @@ -331,10 +392,6 @@ export class Config { } } - private _setTraceContentEnv(): void { - process.env.TRACELOOP_TRACE_CONTENT = this.traceContent ? "true" : "false"; - } - /** * Format the OTLP endpoint URL by appending /v1/traces if not already present */ @@ -357,34 +414,24 @@ export class Config { } /** - * Set Traceloop environment variables based on Netra config. - * This ensures the Traceloop SDK picks up our configuration. + * Prepare the environment for Traceloop's `initialize()` and return a + * function that restores it. Call the restore function right after + * `initialize()` returns. + * + * Only OTEL_RESOURCE_ATTRIBUTES is set: Traceloop's NodeSDK reads it while + * starting, which is how service.name, deployment.environment and custom + * resource attributes reach the Resource. Restoring it afterwards keeps it + * out of child processes. The endpoint, API key and headers are passed to + * Traceloop directly and are no longer copied into TRACELOOP_* variables, + * which every child process inherited (JS-SEC-007). */ - public setTraceloopEnv(): void { - // Set TRACELOOP_BASE_URL so Traceloop SDK uses our endpoint - if (this.otlpEndpoint && !process.env.TRACELOOP_BASE_URL) { - process.env.TRACELOOP_BASE_URL = this.otlpEndpoint; - } - - // Set TRACELOOP_API_KEY if we have one - if (this.apiKey && !process.env.TRACELOOP_API_KEY) { - process.env.TRACELOOP_API_KEY = this.apiKey; - } - - // Set headers for Traceloop - if ( - Object.keys(this.headers).length > 0 && - !process.env.TRACELOOP_HEADERS - ) { - const headerStr = Object.entries(this.headers) - .map(([k, v]) => `${k}=${v}`) - .join(","); - process.env.TRACELOOP_HEADERS = headerStr; - } - - // Set OTEL_RESOURCE_ATTRIBUTES so the TracerProvider Resource carries - // service.name and deployment.environment attributes. + public setTraceloopEnv(): () => void { + const previous = process.env.OTEL_RESOURCE_ATTRIBUTES; this._setResourceAttributesEnv(); + return () => { + if (previous === undefined) delete process.env.OTEL_RESOURCE_ATTRIBUTES; + else process.env.OTEL_RESOURCE_ATTRIBUTES = previous; + }; } private _setResourceAttributesEnv(): void { @@ -405,9 +452,9 @@ export class Config { for (const pair of existing.split(",")) { const eqIdx = pair.indexOf("="); if (eqIdx <= 0) continue; - const key = decodeURIComponent(pair.slice(0, eqIdx).trim()); + const key = safeDecodeURIComponent(pair.slice(0, eqIdx).trim()); if (key) { - attrs[key] = decodeURIComponent(pair.slice(eqIdx + 1).trim()); + attrs[key] = safeDecodeURIComponent(pair.slice(eqIdx + 1).trim()); } } } diff --git a/src/decorators.ts b/src/decorators.ts index 6feec9d..b1fe47a 100644 --- a/src/decorators.ts +++ b/src/decorators.ts @@ -6,7 +6,7 @@ import { context, trace, Span, SpanStatusCode } from "@opentelemetry/api"; import { Config } from "./config"; import { isTraceContentEnabled } from "./instrumentation/utils"; import { NetraLogger } from "./netraLogger"; -import { SessionManager } from "./session-manager"; +import { runWithEntity, SessionManager } from "./session-manager"; import { SpanType, DecoratorOptions } from "./types"; import { wrapResponse } from "./utils/response-handler"; import { safeStringify } from "./utils/serialization"; @@ -39,11 +39,18 @@ function spanHasOutput(span: Span): boolean { return false; } +/** + * Serialize at most twice the attribute limit: enough for the serialization + * layer to cut the value as valid JSON, without stringifying huge arguments + * or results in full first (JS-MEM-007, JS-PERF-012). + */ +const serializeBudget = (): number => Config.SPAN_ATTRIBUTE_MAX_SIZE * 2; + function addInputAttributes(span: Span, args: any[], entityType: string): void { span.setAttribute(`${Config.LIBRARY_NAME}.entity.type`, entityType); // traceContent: false must keep function arguments out of the trace (JS-SEC-004). if (args.length > 0 && isTraceContentEnabled()) { - span.setAttribute("input", safeStringify(args)); + span.setAttribute("input", safeStringify(args, { maxLength: serializeBudget() })); } } @@ -51,7 +58,7 @@ function addOutputAttributes(span: Span, result: any): void { // Skip if the user already set output explicitly inside the decorated function if (result === undefined || !isTraceContentEnabled() || spanHasOutput(span)) return; try { - span.setAttribute("output", safeStringify(result)); + span.setAttribute("output", safeStringify(result, { maxLength: serializeBudget() })); } catch (e) { span.setAttribute("output_error", String(e)); } @@ -97,14 +104,14 @@ function createFunctionWrapper( const cleanup = (span: Span) => { span.end(); SessionManager.unregisterSpan(spanName, span); - SessionManager.popEntity(entityType); }; const wrapperFn = isAsync ? async function (this: any, ...args: any[]) { - SessionManager.pushEntity(entityType, spanName); const tracer = trace.getTracer(moduleName); - return tracer.startActiveSpan(spanName, async (span) => { + // Each call gets its own entity scope, so concurrent calls cannot see + // or pop each other's workflow/agent/task names (JS-SEC-018). + return runWithEntity(entityType, spanName, () => tracer.startActiveSpan(spanName, async (span) => { try { initSpan(span); addInputAttributes(span, args, entityType); @@ -121,12 +128,11 @@ function createFunctionWrapper( cleanup(span); throw e; } - }); + })); } : function (this: any, ...args: any[]) { - SessionManager.pushEntity(entityType, spanName); const tracer = trace.getTracer(moduleName); - return tracer.startActiveSpan(spanName, (span) => { + return runWithEntity(entityType, spanName, () => tracer.startActiveSpan(spanName, (span) => { try { initSpan(span); addInputAttributes(span, args, entityType); @@ -143,7 +149,7 @@ function createFunctionWrapper( cleanup(span); throw e; } - }); + })); }; return wrapperFn as T; } diff --git a/src/exporters/filteringSpanExporter.ts b/src/exporters/filteringSpanExporter.ts index 7addcc4..579f048 100644 --- a/src/exporters/filteringSpanExporter.ts +++ b/src/exporters/filteringSpanExporter.ts @@ -8,6 +8,7 @@ import { } from "../utils/pattern-matching"; import { addBlockedTraceId, + clearBlockedTraceIds, findRootSpansBlocked, getTraceId, isTraceIdBlocked, @@ -153,6 +154,7 @@ export class FilteringSpanExporter implements SpanExporter { shutdown(): Promise { this.rememberedBlockedParentMap.clear(); this.localPatternCache.clear(); + clearBlockedTraceIds(); return this.exporter.shutdown(); } diff --git a/src/exporters/trialAwareOtlpExporter.ts b/src/exporters/trialAwareOtlpExporter.ts index f889d7f..4859538 100644 --- a/src/exporters/trialAwareOtlpExporter.ts +++ b/src/exporters/trialAwareOtlpExporter.ts @@ -16,19 +16,32 @@ const PAYLOAD_TOO_LARGE_HINT = * What the backend said, quoted: `error.message` from its error envelope (joined when it is a list * of validation messages), else an excerpt of the raw body. */ +/** + * Text from the endpoint, made safe to print: control characters (newlines, + * ANSI escape sequences) are escaped and the length is capped, whether it came + * from a JSON error message or a raw body. The endpoint may be any collector, + * so its text must not be able to forge or flood log lines (JS-SEC-024). + */ +export function sanitizeForLog(text: string, maxChars = RESPONSE_EXCERPT_MAX_CHARS): string { + const cut = text.length > maxChars ? `${text.slice(0, maxChars)}…` : text; + return cut.replace(/[\u0000-\u001f\u007f-\u009f]/g, (c) => + c === "\n" ? "\\n" : c === "\r" ? "\\r" : c === "\t" ? "\\t" : `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); +} + function describeServerMessage(responseBody: string): string { try { const parsed: unknown = JSON.parse(responseBody); const message = (parsed as { error?: { message?: unknown } } | null)?.error ?.message; - if (typeof message === "string") return `"${message}"`; + if (typeof message === "string") return `"${sanitizeForLog(message)}"`; if (Array.isArray(message) && message.every((m) => typeof m === "string")) { - return `"${message.join("; ")}"`; + return `"${sanitizeForLog(message.join("; "))}"`; } } catch { // Not JSON: quote the raw body below. } - const excerpt = responseBody.trim().slice(0, RESPONSE_EXCERPT_MAX_CHARS); + const excerpt = sanitizeForLog(responseBody.trim()); return excerpt ? `"${excerpt}"` : "(empty response body)"; } @@ -43,7 +56,7 @@ function formatExportFailure( spanCount: number, requestBytes: number, ): string { - const status = [statusCode ?? "unknown", statusMessage] + const status = [statusCode ?? "unknown", statusMessage ? sanitizeForLog(statusMessage, 80) : undefined] .filter(Boolean) .join(" "); const hint = @@ -59,16 +72,102 @@ function formatExportFailure( interface ExporterConfig { url: string; headers?: Record; + /** Overall deadline for one batch, all attempts included. */ + timeoutMillis?: number; + /** Most exports sending at once; further batches wait in a bounded queue. */ + maxConcurrentExports?: number; + /** Most batches allowed to wait for a free slot; beyond this they are dropped. */ + maxQueuedExports?: number; +} + +const DEFAULT_EXPORT_TIMEOUT_MS = 10_000; +const DEFAULT_MAX_CONCURRENT_EXPORTS = 16; +const DEFAULT_MAX_QUEUED_EXPORTS = 1024; +const MAX_ATTEMPTS = 5; +const INITIAL_BACKOFF_MS = 1_000; +const MAX_BACKOFF_MS = 5_000; +/** Error responses are only read for diagnostics; anything past this is ignored. */ +const MAX_RESPONSE_BODY_BYTES = 64 * 1024; +/** Statuses worth retrying: the batch was not processed and may be next time. */ +const RETRYABLE_STATUSES = new Set([408, 429, 502, 503, 504]); +/** At most one "too many exports in flight" warning per interval. */ +const SATURATION_NOTICE_INTERVAL_MS = 10_000; + +/** Reads OTEL_EXPORTER_OTLP_TRACES_TIMEOUT / OTEL_EXPORTER_OTLP_TIMEOUT (ms). */ +function timeoutFromEnv(): number | undefined { + for (const name of ["OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "OTEL_EXPORTER_OTLP_TIMEOUT"]) { + const value = Number(process.env[name]); + if (Number.isFinite(value) && value > 0) return value; + } + return undefined; +} + +/** `Retry-After` in ms (delta-seconds or HTTP date), or undefined. */ +function parseRetryAfter(header: string | string[] | undefined): number | undefined { + const raw = Array.isArray(header) ? header[0] : header; + if (!raw) return undefined; + const seconds = Number(raw); + if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000; + const date = Date.parse(raw); + return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined; +} + +function backoffMs(attempt: number): number { + const base = Math.min(MAX_BACKOFF_MS, INITIAL_BACKOFF_MS * 2 ** (attempt - 1)); + return Math.round(base * (0.8 + Math.random() * 0.4)); +} + +/** + * The backend reports exhausted quota as `error.errorCode: "QUOTA_EXCEEDED"` + * (combat-ai-core HttpExceptionFilter); netra-sdk-py checks + * `error.error.code`. A plain 429 is a rate limit, not a quota block (JS-MEM-004). + */ +export function isQuotaExceededResponse(body: string): boolean { + try { + const error = (JSON.parse(body) as { error?: any } | null)?.error; + if (!error || typeof error !== "object") return false; + if (error.errorCode === "QUOTA_EXCEEDED" || error.code === "QUOTA_EXCEEDED") return true; + if (error.error && typeof error.error === "object" && error.error.code === "QUOTA_EXCEEDED") return true; + const message = Array.isArray(error.message) ? error.message.join(" ") : String(error.message ?? ""); + return message.toLowerCase().includes("usage quota exceeded"); + } catch { + return false; + } +} + +interface AttemptResult { + statusCode?: number; + statusMessage?: string; + body: string; + retryAfterMs?: number; + error?: Error; } export class TrialAwareOTLPExporter implements SpanExporter { private _url: string; private _headers: Record; private _isShutdown = false; + private readonly _timeoutMillis: number; + private readonly _maxConcurrentExports: number; + private readonly _maxQueuedExports: number; + /** Every accepted batch until its callback has run (sending or queued). */ + private readonly _inFlight = new Set>(); + private _sending = 0; + private readonly _queue: Array<() => void> = []; + private readonly _activeRequests = new Set(); + private readonly _sleepers = new Set<() => void>(); + /** Bumped by abortPending(); exports started before it stop retrying. */ + private _abortEpoch = 0; + private _droppedSinceNotice = 0; + private _lastSaturationNotice = 0; constructor(config: ExporterConfig) { this._url = config.url; - this._headers = config.headers || {}; + // Copied so later changes to the caller's object do not leak into exports. + this._headers = { ...(config.headers || {}) }; + this._timeoutMillis = config.timeoutMillis ?? timeoutFromEnv() ?? DEFAULT_EXPORT_TIMEOUT_MS; + this._maxConcurrentExports = config.maxConcurrentExports ?? DEFAULT_MAX_CONCURRENT_EXPORTS; + this._maxQueuedExports = config.maxQueuedExports ?? DEFAULT_MAX_QUEUED_EXPORTS; } export( @@ -79,7 +178,27 @@ export class TrialAwareOTLPExporter implements SpanExporter { return resultCallback({ code: ExportResultCode.SUCCESS }); } - let data: Uint8Array | string; + if (this._sending >= this._maxConcurrentExports && this._queue.length >= this._maxQueuedExports) { + // The endpoint is not keeping up (or hangs) and the queue is full. + // Holding more batches would grow memory without bound (JS-MEM-002). + this._droppedSinceNotice += spans.length; + const now = Date.now(); + if (now - this._lastSaturationNotice >= SATURATION_NOTICE_INTERVAL_MS) { + NetraLogger.notice( + "warn", + `Span export skipped: ${this._sending} exports in flight and ${this._queue.length} waiting. ` + + `Dropped ${this._droppedSinceNotice} spans since the last warning.`, + ); + this._lastSaturationNotice = now; + this._droppedSinceNotice = 0; + } + return resultCallback({ + code: ExportResultCode.FAILED, + error: new Error("Too many exports in flight"), + }); + } + + let data: Uint8Array; try { const serialized = ProtobufTraceSerializer.serializeRequest(spans); if (!serialized) throw new Error("Serialization failed"); @@ -91,86 +210,194 @@ export class TrialAwareOTLPExporter implements SpanExporter { }); } - const requestBytes = - typeof data === "string" ? Buffer.byteLength(data) : data.byteLength; - const url = new URL(this._url); - const options: https.RequestOptions = { - hostname: url.hostname, - port: url.port, - path: url.pathname, - method: "POST", - headers: { - ...this._headers, - host: url.host, - "Content-Type": "application/x-protobuf", - "Content-Length": requestBytes, - }, - }; - - const lib = url.protocol === "https:" ? https : http; - - const req = lib.request(options, (res) => { - let body = ""; - res.on("data", (chunk) => (body += chunk)); - res.on("end", () => { - if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { - resultCallback({ code: ExportResultCode.SUCCESS }); - } else { - // The batch is not retried, so it is gone: always shown. - NetraLogger.notice( - "warn", - formatExportFailure( - res.statusCode, - res.statusMessage, - body, - spans.length, - requestBytes, - ), - ); - this.checkErrorBody(body, res.statusCode); - resultCallback({ - code: ExportResultCode.FAILED, - error: new Error(`Status ${res.statusCode}`), - }); - } - }); - }); + // The deadline starts now, so time spent queued counts against it. + const deadline = Date.now() + this._timeoutMillis; + const task = this._acquireSlot() + .then(() => this._send(data, spans.length, deadline)) + .finally(() => this._releaseSlot()) + .then(resultCallback, (err) => + resultCallback({ code: ExportResultCode.FAILED, error: err instanceof Error ? err : new Error(String(err)) }), + ); + this._inFlight.add(task); + task.finally(() => this._inFlight.delete(task)); + } + + private _acquireSlot(): Promise { + if (this._sending < this._maxConcurrentExports) { + this._sending++; + return Promise.resolve(); + } + return new Promise((resolve) => this._queue.push(() => { this._sending++; resolve(); })); + } + + private _releaseSlot(): void { + this._sending--; + const next = this._queue.shift(); + if (next) next(); + } - req.on("error", (err) => { - // No response (connection refused, DNS, TLS, socket reset): nothing else logs this. + /** + * Send one batch with retries, all within `_timeoutMillis` (JS-PERF-003, + * JS-PERF-006). Always settles. + */ + private async _send(data: Uint8Array, spanCount: number, deadline: number): Promise { + let last: AttemptResult = { body: "" }; + let attempt = 0; + const epoch = this._abortEpoch; + const stopped = () => this._isShutdown || this._abortEpoch !== epoch; + + while (attempt < MAX_ATTEMPTS && !stopped()) { + attempt++; + const remaining = deadline - Date.now(); + if (remaining <= 0) break; + last = await this._attempt(data, remaining); + + const status = last.statusCode; + if (status !== undefined && status >= 200 && status < 300) { + return { code: ExportResultCode.SUCCESS }; + } + if (status !== undefined && isQuotaExceededResponse(last.body)) { + setTrialBlocked(true); + break; + } + const retryable = status === undefined || RETRYABLE_STATUSES.has(status); + if (!retryable || attempt >= MAX_ATTEMPTS || stopped()) break; + + const wait = Math.max(backoffMs(attempt), last.retryAfterMs ?? 0); + if (Date.now() + wait >= deadline) break; + await this._sleep(wait); + } + + const requestBytes = data.byteLength; + const tries = attempt > 1 ? ` after ${attempt} attempts` : ""; + if (last.statusCode !== undefined) { + // The batch is not retried further, so it is gone: always shown. NetraLogger.notice( "warn", - `Span export failed: ${err.message}. ` + - `Dropped a batch of ${spans.length} spans (${requestBytes} bytes).`, + formatExportFailure(last.statusCode, last.statusMessage, last.body, spanCount, requestBytes) + + (tries ? ` (gave up${tries})` : ""), ); - resultCallback({ code: ExportResultCode.FAILED, error: err }); + return { code: ExportResultCode.FAILED, error: new Error(`Status ${last.statusCode}`) }; + } + const error = last.error ?? new Error(stopped() ? "Export aborted" : "Export deadline exceeded"); + // No response (connection refused, DNS, TLS, socket reset, timeout): nothing else logs this. + NetraLogger.notice( + "warn", + `Span export failed${tries}: ${error.message}. ` + + `Dropped a batch of ${spanCount} spans (${requestBytes} bytes).`, + ); + return { code: ExportResultCode.FAILED, error }; + } + + /** Backoff wait that ends early when the exporter shuts down. */ + private _sleep(ms: number): Promise { + return new Promise((resolve) => { + const wake = () => { + clearTimeout(timer); + this._sleepers.delete(wake); + resolve(); + }; + const timer = setTimeout(wake, ms); + this._sleepers.add(wake); }); - req.write(data); - req.end(); } - private checkErrorBody(bodyString: string, statusCode?: number) { - try { - const jsonBody = JSON.parse(bodyString); - const errorCode = jsonBody?.error?.code || statusCode; - const errorMessage = jsonBody?.error?.message || ""; + /** One HTTP attempt, bounded by `timeoutMs`. Always settles exactly once. */ + private _attempt(data: Uint8Array, timeoutMs: number): Promise { + return new Promise((resolve) => { + const url = new URL(this._url); + const options: https.RequestOptions = { + hostname: url.hostname, + port: url.port, + path: `${url.pathname}${url.search}`, + method: "POST", + headers: { + ...this._headers, + host: url.host, + "Content-Type": "application/x-protobuf", + "Content-Length": data.byteLength, + }, + }; + const lib = url.protocol === "https:" ? https : http; - if (errorCode === 429 || errorMessage.includes("usage quota exceeded")) { - setTrialBlocked(true); - } - } catch (e) { - if (statusCode === 429 || bodyString.includes("quota exceeded")) { - setTrialBlocked(true); + let settled = false; + let req: http.ClientRequest | undefined; + const finish = (result: AttemptResult) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (req) this._activeRequests.delete(req); + resolve(result); + }; + const timer = setTimeout(() => { + finish({ body: "", error: new Error(`timed out after ${timeoutMs} ms`) }); + req?.destroy(); + }, timeoutMs); + + try { + req = lib.request(options, (res) => { + const chunks: Buffer[] = []; + let received = 0; + res.on("data", (chunk: Buffer) => { + if (received < MAX_RESPONSE_BODY_BYTES) { + chunks.push(chunk.subarray(0, MAX_RESPONSE_BODY_BYTES - received)); + } + received += chunk.length; + }); + const done = () => + finish({ + statusCode: res.statusCode, + statusMessage: res.statusMessage, + body: Buffer.concat(chunks).toString("utf8"), + retryAfterMs: parseRetryAfter(res.headers["retry-after"]), + }); + res.on("end", done); + // A response cut off mid-body emits neither 'end' nor a request error. + res.on("error", (err) => finish({ body: "", error: err })); + res.on("close", () => (res.complete ? done() : finish({ body: "", error: new Error("response closed before it completed") }))); + }); + this._activeRequests.add(req); + req.on("error", (err) => finish({ body: "", error: err })); + req.write(data); + req.end(); + } catch (err) { + finish({ body: "", error: err instanceof Error ? err : new Error(String(err)) }); } - } + }); + } + + /** + * Abort every export still in flight or queued, keeping the exporter + * usable. `Netra.shutdown()` calls this when its flush budget runs out, so + * an upload to a hung endpoint cannot keep a finished process alive + * (JS-PERF-003). + */ + abortPending(): void { + this._abortEpoch++; + for (const wake of [...this._sleepers]) wake(); + for (const req of [...this._activeRequests]) req.destroy(); + this._activeRequests.clear(); + // Queued batches start, see the new epoch and fail at once. + const queued = this._queue.splice(0); + for (const start of queued) start(); } + /** Waits for in-flight exports; each is bounded by its deadline. */ async forceFlush(): Promise { - return Promise.resolve(); + await Promise.allSettled([...this._inFlight]); } + /** + * Stops new exports and aborts in-flight requests, so an open socket to a + * hung endpoint cannot keep the process alive after shutdown (JS-PERF-003). + */ async shutdown(): Promise { this._isShutdown = true; - return Promise.resolve(); + // Queued batches start, see the shutdown flag and fail at once. + while (this._queue.length) this._queue.shift()!(); + for (const wake of [...this._sleepers]) wake(); + for (const req of this._activeRequests) req.destroy(); + this._activeRequests.clear(); + await Promise.allSettled([...this._inFlight]); } } diff --git a/src/exporters/utils.ts b/src/exporters/utils.ts index 66355cf..91e0626 100644 --- a/src/exporters/utils.ts +++ b/src/exporters/utils.ts @@ -12,7 +12,19 @@ import { export { INVALID_SPAN_ID }; let trialBlockedAt: number | null = null; -const blockedTraceIds = new Set(); + +/** + * Trace ids seen during a quota block, with the time each stops being blocked. + * Bounded by a TTL and a size cap; the set used to grow for as long as the + * process ran (JS-MEM-004). + */ +const blockedTraceIds = new Map(); +const MAX_BLOCKED_TRACE_IDS = 10_000; + +/** How long a trace id stays blocked: long enough for a trace to finish. */ +function blockedTraceTtlMs(): number { + return Config.TRIAL_BLOCK_DURATION_SECONDS * 2 * 1000; +} /** * Set the trial-blocked status, with automatic expiration. @@ -63,12 +75,35 @@ export function isTrialBlocked(): boolean { * block clears will be exported again. */ export function addBlockedTraceId(traceId: string) { - blockedTraceIds.add(traceId); + // Re-insert so the Map's insertion order stays oldest-first for eviction. + blockedTraceIds.delete(traceId); + blockedTraceIds.set(traceId, Date.now() + blockedTraceTtlMs()); + while (blockedTraceIds.size > MAX_BLOCKED_TRACE_IDS) { + const oldest = blockedTraceIds.keys().next().value; + if (oldest === undefined) break; + blockedTraceIds.delete(oldest); + } } /** Check whether a trace ID is in the blocked list. */ export function isTraceIdBlocked(traceId: string): boolean { - return blockedTraceIds.has(traceId); + const expiresAt = blockedTraceIds.get(traceId); + if (expiresAt === undefined) return false; + if (Date.now() >= expiresAt) { + blockedTraceIds.delete(traceId); + return false; + } + return true; +} + +/** Forget every blocked trace id (used on shutdown and in tests). */ +export function clearBlockedTraceIds(): void { + blockedTraceIds.clear(); +} + +/** Number of blocked trace ids currently remembered. */ +export function blockedTraceIdCount(): number { + return blockedTraceIds.size; } export function getTraceId(span: ReadableSpan): string { diff --git a/src/index.ts b/src/index.ts index 0dc513e..e527a6f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,7 @@ import { context, trace } from "@opentelemetry/api"; import { createRequire } from "module"; import { Prompts, Dashboard, Evaluation, Usage, Models } from "./api"; import { Config, NetraConfig } from "./config"; -import { initInstrumentations, instrumentationsReady, uninstrumentAll } from "./instrumentation"; +import { abortPendingExports, initInstrumentations, instrumentationsReady, uninstrumentAll } from "./instrumentation"; import { NetraLogger } from "./netraLogger"; import { clearSessionValues, @@ -368,14 +368,19 @@ export class Netra { } })(); - await Promise.race([ - flushPromise, - new Promise((resolve) => { - flushTimer = setTimeout(resolve, FLUSH_TIMEOUT_MS); + const flushed = await Promise.race([ + flushPromise.then(() => true), + new Promise((resolve) => { + flushTimer = setTimeout(() => resolve(false), FLUSH_TIMEOUT_MS); // Don't let the budget itself hold the process open after the flush. flushTimer.unref?.(); }), ]); + if (!flushed) { + // The endpoint did not answer within the budget. An open upload would + // keep the event loop, and so the process, alive (JS-PERF-003). + abortPendingExports(); + } } catch (e) { NetraLogger.error("Error during Netra trace shutdown:", e); } finally { diff --git a/src/instrumentation/google-genai/wrappers.ts b/src/instrumentation/google-genai/wrappers.ts index 9b8e021..23eb879 100644 --- a/src/instrumentation/google-genai/wrappers.ts +++ b/src/instrumentation/google-genai/wrappers.ts @@ -25,6 +25,7 @@ import { createSuppressedContext, modelAsDict, shouldSuppressInstrumentation, + isTraceContentEnabled, } from "../utils"; import { GoogleGenAIRequestType, SPAN_NAMES } from "./types"; import { @@ -56,7 +57,9 @@ function buildParams(args: any[], self: Record): Record, Iterator { if (Array.isArray(chunkChoices)) { chunkChoices.forEach((choice: any) => { const index = Number(choice.index || 0); + if (!isValidChoiceIndex(index)) return; this.ensureChoice(index); const delta = choice.delta || {}; @@ -244,7 +246,11 @@ export class StreamingWrapper implements Iterable, Iterator { this.completeResponse.usage = chunkDict.response.usage || {}; } - this.span.addEvent("llm.content.completion.chunk"); + // Per-chunk events only in debug mode, as for Anthropic and google-genai: + // past the event limit each one still allocates and shifts (JS-PERF-014). + if (NetraLogger.isDebugMode()) { + this.span.addEvent("llm.content.completion.chunk"); + } } private ensureChoice(index: number): void { @@ -299,6 +305,7 @@ class AsyncStreamCollector { if (Array.isArray(chunkChoices)) { chunkChoices.forEach((choice: any) => { const index = Number(choice.index || 0); + if (!isValidChoiceIndex(index)) return; this.ensureChoice(index); const delta = (choice.delta || {}) as Record; if (typeof delta === "object" && delta.content) { @@ -342,7 +349,11 @@ class AsyncStreamCollector { this.completeResponse.usage = usage; }); } - this.span.addEvent("llm.content.completion.chunk"); + // Per-chunk events only in debug mode, as for Anthropic and google-genai: + // past the event limit each one still allocates and shifts (JS-PERF-014). + if (NetraLogger.isDebugMode()) { + this.span.addEvent("llm.content.completion.chunk"); + } } private ensureChoice(index: number): void { diff --git a/src/instrumentation/index.ts b/src/instrumentation/index.ts index 5ff0a9d..2f518be 100644 --- a/src/instrumentation/index.ts +++ b/src/instrumentation/index.ts @@ -8,7 +8,9 @@ import { SpanExporter, SpanProcessor, } from "@opentelemetry/sdk-trace-base"; -import { initialize, InitializeOptions } from "@traceloop/node-server-sdk"; +// Type-only: the Traceloop SDK and its dependency tree are loaded on the +// first Netra.init(), not when netra-sdk is imported (JS-PERF-007). +import type { InitializeOptions } from "@traceloop/node-server-sdk"; import { createRequire } from "module"; import { Config, @@ -38,7 +40,6 @@ import { openaiAgentsInstrumentor } from "./openai-agents"; import { typeORMInstrumentor } from "./typeorm"; import { FilteringSpanExporter, TrialAwareOTLPExporter } from "../exporters"; import { LocalFilteringSpanProcessor } from "../processors/localfiltering-span-processor"; -import { propagation } from "@opentelemetry/api"; import { CompositePropagator, W3CTraceContextPropagator, @@ -83,11 +84,63 @@ function isPackageInstalled(packageName: string): boolean { */ export let instrumentationsReady: Promise = Promise.resolve(); -propagation.setGlobalPropagator( - new CompositePropagator({ +/** The OTLP exporter of the current init, if one was created. */ +let activeOtlpExporter: TrialAwareOTLPExporter | undefined; + +/** + * Abort span uploads still in flight. Used by `Netra.shutdown()` once its + * flush budget is spent, so a hung endpoint cannot keep the process alive. + */ +export function abortPendingExports(): void { + activeOtlpExporter?.abortPending(); +} + +/** + * W3C trace context plus Netra's baggage propagator. Handed to Traceloop's + * NodeSDK, which registers it when Netra.init() starts tracing. It used to be + * registered as soon as the module was imported, which overrode a propagator + * the app installed later, even if Netra was never initialized (JS-SEC-011). + */ +export function createNetraPropagator(): CompositePropagator { + return new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new NetraBaggagePropagator()], - }), -); + }); +} + +/** True once Traceloop's one-shot initialize() has run in this process. */ +let traceloopStarted = false; +/** The TracerProvider Traceloop registered, if it became the global one. */ +let netraTracerProvider: unknown; +/** The filtering processor whose blocked-parent map the live exporter reads. */ +let liveLocalFiltering: LocalFilteringSpanProcessor | undefined; +/** Processors Netra added to the provider in the last init. */ +let netraProcessors: SpanProcessor[] = []; + +function currentTracerDelegate(): unknown { + const provider = trace.getTracerProvider() as any; + return typeof provider?.getDelegate === "function" ? provider.getDelegate() : provider; +} + +/** + * Remove the processors added by an earlier init, so a re-init does not run + * every span through another full set (JS-MEM-008). Returns false when the + * provider does not allow removal, in which case nothing new should be added. + */ +function removePreviousNetraProcessors(delegate: any): boolean { + if (netraProcessors.length === 0) return true; + const active = delegate?._activeSpanProcessor?._spanProcessors; + if (!Array.isArray(active)) return false; + for (const processor of netraProcessors) { + const idx = active.indexOf(processor); + if (idx !== -1) active.splice(idx, 1); + // The live exporter keeps reading this filter's map; it is re-added below. + if (processor !== liveLocalFiltering) { + processor.shutdown().catch(() => {}); + } + } + netraProcessors = []; + return true; +} function patchTraceloopLangchainCallbackHandler(): void { const applyPatch = (mod: any, sourceLabel: string) => { @@ -148,6 +201,11 @@ function disableTraceloopLangchainCallbackHandler(): void { if (!CallbackManager || (CallbackManager as any).__netra_disable_traceloop) { return; } + // Only undo Traceloop's own patch: leave the app's @langchain/core alone + // when Traceloop did not touch it (JS-SEC-025). + if (!(CallbackManager as any)._traceloopPatched) { + return; + } const originalConfigureSync = (CallbackManager as any)._configureSync; if (typeof originalConfigureSync !== "function") return; @@ -393,7 +451,7 @@ export function initInstrumentations( // Set Traceloop environment variables before initializing // This ensures the SDK picks up our configuration - config.setTraceloopEnv(); + const restoreTraceloopEnv = config.setTraceloopEnv(); // Debug: Log configuration being used NetraLogger.debug("Netra SDK Configuration:"); @@ -418,47 +476,66 @@ export function initInstrumentations( // endpoint is set, sending the Netra API key there and crashing the app // with an unhandled rejection if the host is unreachable (JS-PERF-001). traceloopSyncEnabled: false, + propagator: createNetraPropagator(), }; - // ---- updated exporter setup (Python-equivalent) ---- + const providerBefore = currentTracerDelegate(); - // 1) Pick base exporter (Console fallback OR TrialAware(OTLP)) - let exporter: SpanExporter; + if (!traceloopStarted) { + // ---- exporter setup (Python-equivalent) ---- - if (!traceloopOptions.baseUrl || traceloopOptions.baseUrl == undefined) { - NetraLogger.notice("warn", MISSING_ENDPOINT_NOTICE); - exporter = new ConsoleSpanExporter(); - } else { - const formattedEndpoint = config.formatOtlpEndpoint(); + // 1) Pick base exporter (Console fallback OR TrialAware(OTLP)) + let exporter: SpanExporter; - // In TS, we pass the config directly to our custom class - // because it handles the HTTP transport itself to catch the error body. - exporter = new TrialAwareOTLPExporter({ - url: formattedEndpoint, - headers: config.headers, - }); - } + if (!traceloopOptions.baseUrl || traceloopOptions.baseUrl == undefined) { + NetraLogger.notice("warn", MISSING_ENDPOINT_NOTICE); + exporter = new ConsoleSpanExporter(); + } else { + const formattedEndpoint = config.formatOtlpEndpoint(); + + // In TS, we pass the config directly to our custom class + // because it handles the HTTP transport itself to catch the error body. + activeOtlpExporter = new TrialAwareOTLPExporter({ + url: formattedEndpoint, + headers: config.headers, + }); + exporter = activeOtlpExporter; + } - // 2) Always attempt filtering (even for Console fallback) - // The LocalFilteringSpanProcessor is instantiated below and its - // blockedParentMap is injected into FilteringSpanExporter so the - // two can share reparenting state without module-level globals. - const globalBlockedPatterns = config.blockedSpans ?? []; - const localFilteringSpanProcessor = new LocalFilteringSpanProcessor(globalBlockedPatterns); - const originalExporter = exporter; + // 2) Always attempt filtering (even for Console fallback). This + // LocalFilteringSpanProcessor is the one registered on the provider + // below, so the exporter's blocked-parent map is actually filled. + const globalBlockedPatterns = config.blockedSpans ?? []; + liveLocalFiltering = new LocalFilteringSpanProcessor(globalBlockedPatterns); + const originalExporter = exporter; - try { - exporter = new FilteringSpanExporter( - exporter, - globalBlockedPatterns, - localFilteringSpanProcessor.blockedParentMap, - ); - } catch { - exporter = originalExporter; - } + try { + exporter = new FilteringSpanExporter( + exporter, + globalBlockedPatterns, + liveLocalFiltering.blockedParentMap, + ); + } catch { + exporter = originalExporter; + } - traceloopOptions.exporter = exporter; + traceloopOptions.exporter = exporter; + } else { + // Traceloop's initialize() runs once per process; the exporter created by + // the first Netra.init() stays in use. + NetraLogger.debug("Netra re-initialized: reusing the exporter from the first init."); + } - initialize(traceloopOptions); + try { + if (!traceloopStarted) { + const { initialize } = require("@traceloop/node-server-sdk") as typeof import("@traceloop/node-server-sdk"); + initialize(traceloopOptions); + traceloopStarted = true; + const providerAfter = currentTracerDelegate(); + netraTracerProvider = providerAfter !== providerBefore ? providerAfter : undefined; + } + } finally { + restoreTraceloopEnv(); + } if (instrumentModules.langchain) { patchTraceloopLangchainCallbackHandler(); @@ -466,16 +543,32 @@ export function initInstrumentations( disableTraceloopLangchainCallbackHandler(); } - // ---- rest stays same ---- const tracerProvider = trace.getTracerProvider(); - // Add custom span processors to the TracerProvider - // The Traceloop SDK creates a BasicTracerProvider internally - const effectiveProvider = addCustomSpanProcessors( - tracerProvider, - config, - resolvedRootNames, - ); + // Netra's processors go only on the provider Traceloop created. When the + // app registered its own provider first, Traceloop's could not become the + // global one; adding Netra's processors to the app's provider rewrote the + // app's own spans without sending anything to Netra (JS-SEC-011). + let effectiveProvider: TracerProviderWithProcessors | null = null; + const delegate = currentTracerDelegate(); + if (netraTracerProvider === undefined || delegate !== netraTracerProvider) { + NetraLogger.notice( + "warn", + "Another OpenTelemetry TracerProvider was registered before Netra.init(), so Netra could not register its own " + + "and will not receive spans. Netra's span processors were not added to the other provider. " + + "Fix: call Netra.init() before any other OpenTelemetry setup.", + ); + } else if (!removePreviousNetraProcessors(delegate)) { + NetraLogger.debug("Netra processors from an earlier init could not be removed; keeping them."); + effectiveProvider = delegate as TracerProviderWithProcessors; + } else { + effectiveProvider = addCustomSpanProcessors( + tracerProvider, + config, + resolvedRootNames, + liveLocalFiltering ?? new LocalFilteringSpanProcessor(config.blockedSpans ?? []), + ); + } // Initialize custom instrumentations asynchronously // We use async initialization to ensure we get the same ES module instances @@ -750,6 +843,7 @@ function addCustomSpanProcessors( tracerProvider: ReturnType, config: Config, rootInstrumentNames: Set | null, + localFilteringSpanProcessor: LocalFilteringSpanProcessor, ): TracerProviderWithProcessors | null { try { // The TracerProvider from Traceloop is a ProxyTracerProvider @@ -836,16 +930,23 @@ function addCustomSpanProcessors( // Processors that only CALL setAttribute (not wrap) must be registered AFTER // all wrapping processors so their writes flow through the full chain. - // 0. Local Filtering Span Processor - filters spans based on local context - const localFilteringSpanProcessor = new LocalFilteringSpanProcessor(); - provider.addSpanProcessor(localFilteringSpanProcessor); + // Every processor added is remembered, so a later init can remove it. + const added: SpanProcessor[] = []; + const register = (processor: SpanProcessor) => { + provider!.addSpanProcessor(processor); + added.push(processor); + }; + + // 0. Local Filtering Span Processor - filters spans based on local + // context. The same instance whose map the exporter reads. + register(localFilteringSpanProcessor); // 0.5. Root Instrument Filter Processor - blocks root spans from non-allowed instrumentations if (rootInstrumentNames !== null) { const rootFilterProcessor = new RootInstrumentFilterProcessor( rootInstrumentNames, ); - provider.addSpanProcessor(rootFilterProcessor); + register(rootFilterProcessor); } // 1. Scrubbing Span Processor (wraps setAttribute — innermost layer) @@ -853,43 +954,44 @@ function addCustomSpanProcessors( // before they reach OTel storage. if (config.enableScrubbing) { const scrubbingProcessor = new ScrubbingSpanProcessor(); - provider.addSpanProcessor(scrubbingProcessor); + register(scrubbingProcessor); } // 2. Serialization Span Processor (wraps setAttribute — middle layer) // Serializes objects to JSON strings and truncates values at write time. // Runs before scrubbing so the scrubber receives string values. const serializationProcessor = new SerializationSpanProcessor(); - provider.addSpanProcessor(serializationProcessor); + register(serializationProcessor); // 3. Span I/O Processor (wraps setAttribute — outermost layer) // Routes IO-related attributes, assembles input/output from gen_ai.* // and traceloop.* keys. Assembled values flow through serialize → scrub. const spanIOProcessor = new SpanIOProcessor(config.traceContent); - provider.addSpanProcessor(spanIOProcessor); + register(spanIOProcessor); // 4. Instrumentation Span Processor - tags instrumentation name. // Runs AFTER wrappers are in place so its setAttribute calls flow // through the full chain. const instrumentationProcessor = new InstrumentationSpanProcessor(); - provider.addSpanProcessor(instrumentationProcessor); + register(instrumentationProcessor); // 5. Session Span Processor - adds session context (session_id, user_id, etc.) // Runs AFTER wrappers so session attributes flow through scrub→serialize. const sessionProcessor = new SessionSpanProcessor(config.environment); - provider.addSpanProcessor(sessionProcessor); + register(sessionProcessor); // 6. LLM Trace Identifier Span Processor - marks root spans containing LLM calls. // Uses setAttribute on root span in onEnd (root span is still recording). const llmTraceProcessor = new LlmTraceIdentifierSpanProcessor(); - provider.addSpanProcessor(llmTraceProcessor); + register(llmTraceProcessor); // 7. Root Span Processor - tracks root span per trace. // Registered AFTER LlmTraceIdentifierSpanProcessor so onEnd cleanup // runs after LLM annotation is complete. const rootSpanProcessor = new RootSpanProcessor(); - provider.addSpanProcessor(rootSpanProcessor); + register(rootSpanProcessor); + netraProcessors = added; NetraLogger.debug("Custom span processors registered successfully"); return provider; diff --git a/src/instrumentation/langgraph/utils.ts b/src/instrumentation/langgraph/utils.ts index b28dd23..493dfbe 100644 --- a/src/instrumentation/langgraph/utils.ts +++ b/src/instrumentation/langgraph/utils.ts @@ -2,6 +2,16 @@ import { Span } from "@opentelemetry/api"; import type { ChainValues } from "@langchain/core/utils/types"; import { SpanAttributes } from "../span-attributes"; import { isTraceContentEnabled } from "../utils"; +import { Config } from "../../config"; +import { safeStringify } from "../../utils/serialization"; + +/** + * Never throws (circular or BigInt graph state used to fail the app's call, + * JS-PERF-005) and stops after twice the attribute limit (JS-PERF-012). + */ +export function stringifyForSpan(value: unknown): string { + return safeStringify(value, { maxLength: Config.SPAN_ATTRIBUTE_MAX_SIZE * 2 }); +} export const NetraLanggraphAttributes = { spanType: "netra.span.type", @@ -25,7 +35,7 @@ export function setGraphInputAttributes( if (!isTraceContentEnabled()) return; span.setAttribute( NetraLanggraphAttributes.entityInput, - JSON.stringify({ inputs }), + stringifyForSpan({ inputs }), ); } @@ -36,7 +46,7 @@ export function setGraphOutputAttributes( if (!isTraceContentEnabled()) return; span.setAttribute( NetraLanggraphAttributes.entityOutput, - JSON.stringify({ outputs }), + stringifyForSpan({ outputs }), ); } @@ -87,7 +97,7 @@ export function setChainInputAttributes( } span.setAttribute( NetraLanggraphAttributes.entityInput, - JSON.stringify(entityInputs), + stringifyForSpan(entityInputs), ); } @@ -106,7 +116,7 @@ export function setChainOutputAttributes( } span.setAttribute( NetraLanggraphAttributes.entityOutput, - JSON.stringify(entityOutputs), + stringifyForSpan(entityOutputs), ); } @@ -130,7 +140,7 @@ export function setToolAttributes( } const entityInputs: Record = { - input_str: JSON.stringify(input), + input_str: stringifyForSpan(input), metadata: filteredMetadata, tags: filteredTags, }; @@ -142,11 +152,11 @@ export function setToolAttributes( span.setAttribute( NetraLanggraphAttributes.entityInput, - JSON.stringify(entityInputs), + stringifyForSpan(entityInputs), ); span.setAttribute( NetraLanggraphAttributes.entityOutput, - JSON.stringify(entityOutputs), + stringifyForSpan(entityOutputs), ); } diff --git a/src/instrumentation/langgraph/wrappers.ts b/src/instrumentation/langgraph/wrappers.ts index 3f9a4aa..928d1df 100644 --- a/src/instrumentation/langgraph/wrappers.ts +++ b/src/instrumentation/langgraph/wrappers.ts @@ -37,6 +37,7 @@ import { setGraphOutputAttributes, setLlmRequestAttributes, setToolAttributes, + stringifyForSpan, } from "./utils"; type AnyFunc = (...args: any[]) => any; @@ -534,7 +535,7 @@ export class LanggraphWrapper { if (status === "ok" && traceContent) { span.setAttribute( NetraLanggraphAttributes.entityOutput, - JSON.stringify({ outputs: output }), + stringifyForSpan({ outputs: output }), ); } } finally { diff --git a/src/instrumentation/mistralai/index.ts b/src/instrumentation/mistralai/index.ts index 31cd645..6d4c5ef 100644 --- a/src/instrumentation/mistralai/index.ts +++ b/src/instrumentation/mistralai/index.ts @@ -251,9 +251,10 @@ export class NetraMistralAIInstrumentor { return; } - // Some SDK versions require an apiKey at construction time. - // Use a dummy if none is provided; this is only for discovering constructors. - const apiKey = process.env.MISTRAL_API_KEY ?? "netra_dummy_api_key"; + // Some SDK versions require an apiKey at construction time. This client is + // only used to discover constructors, so it never gets the app's real key + // (JS-SEC-025). + const apiKey = "netra_dummy_api_key"; let client: any; try { diff --git a/src/instrumentation/mistralai/utils.ts b/src/instrumentation/mistralai/utils.ts index 0eb56d2..2d66946 100644 --- a/src/instrumentation/mistralai/utils.ts +++ b/src/instrumentation/mistralai/utils.ts @@ -1,3 +1,4 @@ +import { NetraLogger } from "../../netraLogger"; /** * MistralAI-specific utility functions for instrumentation. * @@ -24,6 +25,19 @@ export function setRequestAttributes( span: Span, kwargs: Record, requestType: string +): void { + // Never throws: this runs before the request is sent (JS-PERF-005). + try { + writeMistralRequestAttributes(span, kwargs, requestType); + } catch (e) { + NetraLogger.debug("netra.instrumentation.mistralai: could not record request attributes", e); + } +} + +function writeMistralRequestAttributes( + span: Span, + kwargs: Record, + requestType: string ): void { // Set shared/common attributes first setBaseRequestAttributes(span, kwargs, requestType, "mistralai"); diff --git a/src/instrumentation/mistralai/wrappers.ts b/src/instrumentation/mistralai/wrappers.ts index aee0f55..d2a0370 100644 --- a/src/instrumentation/mistralai/wrappers.ts +++ b/src/instrumentation/mistralai/wrappers.ts @@ -10,7 +10,9 @@ import { context, } from "@opentelemetry/api"; import { NetraLogger } from "../../netraLogger"; -import { defineHidden, isPromise } from "../utils"; +import { defineHidden, isPromise, + isValidChoiceIndex, +} from "../utils"; import { isAsyncIterable, wrapResponse, @@ -331,6 +333,7 @@ export class StreamingWrapper implements Iterable, Iterator { if (Array.isArray(dataChoices)) { for (const choice of dataChoices) { const index = Number(choice.index || 0); + if (!isValidChoiceIndex(index)) continue; this.ensureChoice(index); const delta = (choice.delta || {}) as Record; @@ -366,6 +369,7 @@ export class StreamingWrapper implements Iterable, Iterator { if (Array.isArray(chunkChoices) && chunkChoices.length > 0) { for (const choice of chunkChoices) { const index = Number(choice.index || 0); + if (!isValidChoiceIndex(index)) continue; this.ensureChoice(index); const delta = (choice.delta || {}) as Record; @@ -393,7 +397,11 @@ export class StreamingWrapper implements Iterable, Iterator { this.completeResponse.usage = chunkDict.usage; } - this.span.addEvent("llm.content.completion.chunk"); + // Per-chunk events only in debug mode, as for Anthropic and google-genai: + // past the event limit each one still allocates and shifts (JS-PERF-014). + if (NetraLogger.isDebugMode()) { + this.span.addEvent("llm.content.completion.chunk"); + } } private finalizeSpan(error?: unknown): void { @@ -479,6 +487,7 @@ class AsyncStreamCollector { if (Array.isArray(dataChoices)) { for (const choice of dataChoices) { const index = Number(choice.index || 0); + if (!isValidChoiceIndex(index)) continue; this.ensureChoice(index); const delta = (choice.delta || {}) as Record; @@ -514,6 +523,7 @@ class AsyncStreamCollector { if (Array.isArray(chunkChoices) && chunkChoices.length > 0) { for (const choice of chunkChoices) { const index = Number(choice.index || 0); + if (!isValidChoiceIndex(index)) continue; this.ensureChoice(index); const delta = (choice.delta || {}) as Record; @@ -541,7 +551,11 @@ class AsyncStreamCollector { this.completeResponse.usage = chunkDict.usage; } - this.span.addEvent("llm.content.completion.chunk"); + // Per-chunk events only in debug mode, as for Anthropic and google-genai: + // past the event limit each one still allocates and shifts (JS-PERF-014). + if (NetraLogger.isDebugMode()) { + this.span.addEvent("llm.content.completion.chunk"); + } } finish(status: "ok" | "error"): void { diff --git a/src/instrumentation/openai/wrappers.ts b/src/instrumentation/openai/wrappers.ts index feabf33..8255a6c 100644 --- a/src/instrumentation/openai/wrappers.ts +++ b/src/instrumentation/openai/wrappers.ts @@ -7,11 +7,13 @@ import { context, trace, } from "@opentelemetry/api"; +import { NetraLogger } from "../../netraLogger"; import { defineHidden, isPromise, modelAsDict, shouldSuppressInstrumentation, + isValidChoiceIndex, } from "../utils"; import { isAsyncIterable, @@ -102,6 +104,7 @@ abstract class BaseStreamHandler { if (Array.isArray(chunkChoices)) { for (const choice of chunkChoices as Array>) { const index = Number(choice.index ?? 0); + if (!isValidChoiceIndex(index)) continue; this.ensureChoice(index); const delta = (choice.delta ?? {}) as Record; if (delta.content) { @@ -146,7 +149,11 @@ abstract class BaseStreamHandler { this.completeResponse.usage = responseChunk.usage ?? {}; } - this.span.addEvent("llm.content.completion.chunk"); + // Per-chunk events only in debug mode, as for Anthropic and google-genai: + // past the event limit each one still allocates and shifts (JS-PERF-014). + if (NetraLogger.isDebugMode()) { + this.span.addEvent("llm.content.completion.chunk"); + } } protected ensureChoice(index: number): void { diff --git a/src/instrumentation/typeorm/utils.ts b/src/instrumentation/typeorm/utils.ts index dc5171f..416be80 100644 --- a/src/instrumentation/typeorm/utils.ts +++ b/src/instrumentation/typeorm/utils.ts @@ -1,5 +1,17 @@ import { Span } from "@opentelemetry/api"; import { NetraLogger } from "../../netraLogger"; +import { isTraceContentEnabled } from "../utils"; + +/** + * Query parameter values are application data (emails, reset tokens, ...). + * They are recorded only when content tracing is on and the app opts in with + * NETRA_TRACE_DB_PARAMETERS=true, as OpenTelemetry's database conventions make + * parameter capture opt-in (JS-SEC-016). + */ +export function shouldRecordDbParameters(): boolean { + const raw = String(process.env.NETRA_TRACE_DB_PARAMETERS ?? "").toLowerCase(); + return isTraceContentEnabled() && (raw === "1" || raw === "true"); +} export function extractQuery(query: string | { query: string; parameters?: any[] }): { sql: string; @@ -58,10 +70,13 @@ export function setQueryAttributes( span.setAttribute("db.statement", sanitizeQuery(sql)); if (parameters && parameters.length > 0) { - try { - span.setAttribute("db.statement.parameters", JSON.stringify(parameters)); - } catch (e) { - NetraLogger.log(e); + span.setAttribute("db.statement.parameters.count", parameters.length); + if (shouldRecordDbParameters()) { + try { + span.setAttribute("db.statement.parameters", JSON.stringify(parameters)); + } catch (e) { + NetraLogger.log(e); + } } } } diff --git a/src/instrumentation/utils.ts b/src/instrumentation/utils.ts index 54b104f..8672f5e 100644 --- a/src/instrumentation/utils.ts +++ b/src/instrumentation/utils.ts @@ -107,7 +107,28 @@ export interface TracedMessage { content: string; } +/** Most choices tracked for one streamed response. */ +export const MAX_STREAM_CHOICES = 128; + +/** + * Whether a streamed `choice.index` is usable. A misbehaving server could + * send a huge index, and filling the choices array up to it allocated memory + * without bound (JS-MEM-009). + */ +export function isValidChoiceIndex(index: number): boolean { + return Number.isInteger(index) && index >= 0 && index < MAX_STREAM_CHOICES; +} + +/** The `traceContent` setting of the active Netra config, once one exists. */ +let configuredTraceContent: boolean | undefined; + +/** Set by `Config`; `undefined` falls back to the environment. */ +export function setTraceContentEnabled(enabled: boolean | undefined): void { + configuredTraceContent = enabled; +} + export function isTraceContentEnabled(): boolean { + if (configuredTraceContent !== undefined) return configuredTraceContent; const raw = process.env.TRACELOOP_TRACE_CONTENT ?? process.env.NETRA_TRACE_CONTENT ?? @@ -495,11 +516,28 @@ export function sanitizeToolsForTrace(tools: unknown[]): unknown[] { // Request Attributes +/** + * Records the request on the span. Never throws: recording must not fail + * the app's call, and this runs before the request is sent (JS-PERF-005). + */ export function setRequestAttributes( span: Span, kwargs: Record, requestType: string, system: string, +): void { + try { + writeRequestAttributes(span, kwargs, requestType, system); + } catch (e) { + NetraLogger.debug(`netra.instrumentation.${system}: could not record request attributes`, e); + } +} + +function writeRequestAttributes( + span: Span, + kwargs: Record, + requestType: string, + system: string, ): void { if (!span.isRecording()) return; @@ -523,7 +561,7 @@ export function setRequestAttributes( if (kwargs.reasoning !== undefined) { span.setAttribute( SpanAttributes.LLM_REQUEST_REASONING, - JSON.stringify(kwargs.reasoning), + safeStringify(kwargs.reasoning), ); } diff --git a/src/netraLogger.test.ts b/src/netraLogger.test.ts index 44e53c4..3d10555 100644 --- a/src/netraLogger.test.ts +++ b/src/netraLogger.test.ts @@ -186,7 +186,8 @@ describe("NetraLogger", () => { const server = await startServer([]); const closedUrl = server.url; await server.close(); // nothing listens on this port any more: ECONNREFUSED - const exporter = new TrialAwareOTLPExporter({ url: closedUrl }); + // A short deadline leaves no room for a retry, so each export fails once. + const exporter = new TrialAwareOTLPExporter({ url: closedUrl, timeoutMillis: 500 }); await exportOnce(exporter); await exportOnce(exporter); diff --git a/src/processors/root-span-processor.ts b/src/processors/root-span-processor.ts index dd6fb7d..8c213f5 100644 --- a/src/processors/root-span-processor.ts +++ b/src/processors/root-span-processor.ts @@ -10,6 +10,14 @@ import { NetraLogger } from "../netraLogger"; * root span. */ export class RootSpanProcessor implements SpanProcessor { + /** + * Upper bound on tracked roots. A root that never ends (a stream nobody + * reads, `Netra.startSpan()` without `end()`) would otherwise stay here for + * the life of the process (JS-MEM-005). Past the cap the oldest entry is + * dropped, which only costs that trace its root-level annotations. + */ + static readonly MAX_TRACKED_ROOTS = 10_000; + private static readonly _rootSpans = new Map(); static getRootSpanByTraceId(traceId: string): Span | undefined { @@ -62,6 +70,10 @@ export class RootSpanProcessor implements SpanProcessor { // setdefault: first span with no valid parent wins if (!RootSpanProcessor._rootSpans.has(ctx.traceId)) { RootSpanProcessor._rootSpans.set(ctx.traceId, span); + if (RootSpanProcessor._rootSpans.size > RootSpanProcessor.MAX_TRACKED_ROOTS) { + const oldest = RootSpanProcessor._rootSpans.keys().next().value; + if (oldest !== undefined) RootSpanProcessor._rootSpans.delete(oldest); + } } } catch (e) { NetraLogger.warn("RootSpanProcessor.onStart: unexpected error:", e); diff --git a/src/processors/scrubbing-span-processor.ts b/src/processors/scrubbing-span-processor.ts index e413a21..8729ca8 100644 --- a/src/processors/scrubbing-span-processor.ts +++ b/src/processors/scrubbing-span-processor.ts @@ -29,8 +29,9 @@ const SENSITIVE_PATTERNS: Record = { "|(?:sk-[A-Za-z0-9]{16,})", // sk-... tokens "g", ), - // Email addresses - email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/gi, + // Email addresses. Every repeat is bounded and the domain is matched label + // by label, so input like "a.a.a.…" cannot backtrack quadratically (JS-SEC-009). + email: /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})*\.[A-Za-z]{2,24}/g, // Phone numbers (US format) phone: /(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}/g, // Credit cards (Visa, Mastercard, Amex, Discover) @@ -49,41 +50,35 @@ const SENSITIVE_PATTERNS: Record = { // Generic pattern for long digit sequences (credit/debit cards) const LONG_DIGIT_PATTERN = /(? Span; -function isSensitiveKey(key: string): boolean { +export function isSensitiveKey(key: string): boolean { const keyLower = key.toLowerCase(); - for (const sensitiveKey of SENSITIVE_KEYS) { - if (keyLower.includes(sensitiveKey)) { - return true; - } - } - return false; + if (SENSITIVE_KEY_PHRASES.test(keyLower)) return true; + return keyLower.split(/[^a-z0-9]+/).some((part) => SENSITIVE_KEY_PARTS.has(part)); } function scrubStringValue(value: string): string { @@ -92,14 +87,11 @@ function scrubStringValue(value: string): string { // Early catch-all for contiguous 13-19 digit sequences (credit/debit cards) scrubbed = scrubbed.replace(LONG_DIGIT_PATTERN, SCRUB_REPLACEMENT); - // Apply all sensitive patterns + // Apply all sensitive patterns (one replace pass each; a separate test() + // pass doubled the work) for (const pattern of Object.values(SENSITIVE_PATTERNS)) { - // Reset lastIndex for global patterns pattern.lastIndex = 0; - if (pattern.test(scrubbed)) { - pattern.lastIndex = 0; - scrubbed = scrubbed.replace(pattern, SCRUB_REPLACEMENT); - } + scrubbed = scrubbed.replace(pattern, SCRUB_REPLACEMENT); } return scrubbed; @@ -140,15 +132,77 @@ function scrubValue(key: string, value: AttributeValue): AttributeValue { return scrubAny(key, value) as AttributeValue; } +function scrubAttributes(attrs: unknown): unknown { + if (!attrs || typeof attrs !== "object" || Array.isArray(attrs)) return attrs; + const out: Record = {}; + for (const [k, v] of Object.entries(attrs as Record)) { + out[k] = v === undefined ? v : scrubValue(k, v as AttributeValue); + } + return out; +} + export class ScrubbingSpanProcessor implements SpanProcessor { onStart(span: Span, _parentContext: Context): void { try { this.wrapSetAttribute(span); + this.wrapOtherWriters(span); + this.scrubInitialState(span); } catch (e) { NetraLogger.error("ScrubbingSpanProcessor.onStart error:", e); } } + /** + * Attributes passed to startSpan() and the span name are set before + * onStart, so the setAttribute wrapper never saw them (JS-SEC-021). + */ + private scrubInitialState(span: Span): void { + const attrs = (span as any).attributes; + if (attrs && typeof attrs === "object") { + for (const [k, v] of Object.entries(attrs)) { + if (v === undefined) continue; + const scrubbed = scrubValue(k, v as AttributeValue); + if (scrubbed !== v) span.setAttribute(k, scrubbed); + } + } + const name = (span as any).name; + if (typeof name === "string") { + const scrubbedName = scrubStringValue(name); + if (scrubbedName !== name) span.updateName(scrubbedName); + } + } + + /** + * Events (including the exception event recordException adds), status + * messages and renamed spans are scrubbed too (JS-SEC-021). + */ + private wrapOtherWriters(span: Span): void { + const s = span as any; + const addEvent = s.addEvent?.bind(span); + if (addEvent) { + s.addEvent = (name: string, attributesOrTime?: unknown, time?: unknown) => { + try { + return addEvent(name, scrubAttributes(attributesOrTime), time); + } catch { + return addEvent(name, attributesOrTime, time); + } + }; + } + const setStatus = s.setStatus?.bind(span); + if (setStatus) { + s.setStatus = (status: { code: number; message?: string }) => + setStatus( + status && typeof status.message === "string" + ? { ...status, message: scrubStringValue(status.message) } + : status, + ); + } + const updateName = s.updateName?.bind(span); + if (updateName) { + s.updateName = (name: string) => updateName(typeof name === "string" ? scrubStringValue(name) : name); + } + } + onEnd(_span: ReadableSpan): void {} shutdown(): Promise { diff --git a/src/processors/span-io-processor.ts b/src/processors/span-io-processor.ts index f46d0bd..ae8ddae 100644 --- a/src/processors/span-io-processor.ts +++ b/src/processors/span-io-processor.ts @@ -1,5 +1,6 @@ import { AttributeValue, Context, Span } from "@opentelemetry/api"; import { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-base"; +import { Config } from "../config"; import { isTraceContentEnabled } from "../instrumentation/utils"; import { NetraLogger } from "../netraLogger"; @@ -23,7 +24,19 @@ const NETRA_ROOT_OUTPUT = "netra.root.output"; const NETRA_ENTITY_INPUT = "netra.entity.input"; const NETRA_ENTITY_OUTPUT = "netra.entity.output"; -const MAX_PARSE_LEN = 1_000_000; +/** + * Longest entity input/output JSON parsed to extract `inputs`/`outputs`. + * Larger values are kept as-is and cut by the serialization layer, instead of + * being parsed and re-stringified in full (JS-PERF-012). + */ +const maxParseLen = (): number => Config.SPAN_ATTRIBUTE_MAX_SIZE * 2; + +/** One prompt/completion field, cut to the attribute size limit (JS-MEM-006). */ +function capField(value: AttributeValue): string { + const str = String(value); + const max = Config.SPAN_ATTRIBUTE_MAX_SIZE; + return str.length > max ? str.slice(0, max) : str; +} /** * Keys that carry prompts, completions, function I/O or other user content. @@ -79,7 +92,7 @@ function buildMessages(indexMap: Map>): string { function extractTraceloopInput(raw: AttributeValue): string { try { const str = String(raw); - if (typeof raw === "string" && str.length > MAX_PARSE_LEN) return str; + if (typeof raw === "string" && str.length > maxParseLen()) return str; const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; const payload = parsed && typeof parsed === "object" && "inputs" in parsed @@ -94,7 +107,7 @@ function extractTraceloopInput(raw: AttributeValue): string { function extractTraceloopOutput(raw: AttributeValue): string { try { const str = String(raw); - if (typeof raw === "string" && str.length > MAX_PARSE_LEN) return str; + if (typeof raw === "string" && str.length > maxParseLen()) return str; const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; const payload = parsed && typeof parsed === "object" && "outputs" in parsed @@ -173,6 +186,45 @@ export class SpanIOProcessor implements SpanProcessor { const outputIsEmpty = (): boolean => isEmpty(((span as any).attributes ?? {})["output"]); + // input/output are rebuilt from the accumulated messages once per burst + // of writes (a microtask later, or at end()), not after every message: + // rebuilding on each write was quadratic in the number of messages + // (JS-PERF-002). + let inputDirty = false; + let outputDirty = false; + let flushScheduled = false; + const flush = (): void => { + flushScheduled = false; + try { + if (inputDirty && prompts) { + inputDirty = false; + if (!inputLocked() && (inputIsEmpty() || genAiOwnsInput)) { + original("input", buildMessages(prompts)); + genAiOwnsInput = true; + } + } + if (outputDirty && completions) { + outputDirty = false; + if (!outputLocked() && (outputIsEmpty() || genAiOwnsOutput)) { + original("output", buildMessages(completions)); + genAiOwnsOutput = true; + } + } + } catch (e) { + NetraLogger.debug("SpanIOProcessor: error rebuilding input/output", e); + } + }; + const scheduleFlush = (): void => { + if (flushScheduled) return; + flushScheduled = true; + queueMicrotask(flush); + }; + const originalEnd = span.end.bind(span); + (span as any).end = (endTime?: Parameters[0]) => { + if (inputDirty || outputDirty) flush(); + return originalEnd(endTime); + }; + const patched = (key: string, value: AttributeValue): Span => { try { // Priority 0: traceContent disabled → content never reaches the span. @@ -234,11 +286,9 @@ export class SpanIOProcessor implements SpanProcessor { entry = {}; prompts.set(idx, entry); } - entry[field] = String(value); - if (!inputLocked() && (inputIsEmpty() || genAiOwnsInput)) { - original("input", buildMessages(prompts)); - genAiOwnsInput = true; - } + entry[field] = capField(value); + inputDirty = true; + scheduleFlush(); return span; } @@ -254,11 +304,9 @@ export class SpanIOProcessor implements SpanProcessor { entry = {}; completions.set(idx, entry); } - entry[field] = String(value); - if (!outputLocked() && (outputIsEmpty() || genAiOwnsOutput)) { - original("output", buildMessages(completions)); - genAiOwnsOutput = true; - } + entry[field] = capField(value); + outputDirty = true; + scheduleFlush(); return span; } diff --git a/src/session-manager.ts b/src/session-manager.ts index fda7d7f..fb781d4 100644 --- a/src/session-manager.ts +++ b/src/session-manager.ts @@ -22,15 +22,30 @@ const MODULE_NAME = "netra.session-manager"; /** * Per-async-scope state: entity name stacks and a name→span registry. * Deliberately minimal — live span references belong to OTel's context, not here. + * + * A scope is never mutated by a nested call: entering an entity copies the + * scope (`runWithEntity`), and the registry is copy-on-write. Each decorated + * call therefore sees only its own ancestors, concurrent requests cannot + * interleave their stacks (JS-SEC-018), and a scope's state is released with + * the scope instead of living in a module global (JS-MEM-005). */ interface EntityContext { - workflowStack: string[]; - taskStack: string[]; - agentStack: string[]; - spanStack: string[]; - spansByName: Map; + readonly workflowStack: readonly string[]; + readonly taskStack: readonly string[]; + readonly agentStack: readonly string[]; + readonly spanStack: readonly string[]; + readonly spansByName: Map; } +type EntityStackKey = "workflowStack" | "taskStack" | "agentStack" | "spanStack"; + +const STACK_FOR_ENTITY: Record = { + workflow: "workflowStack", + task: "taskStack", + agent: "agentStack", + span: "spanStack", +}; + type ConversationEntry = { type: string; role: string; @@ -40,17 +55,27 @@ type ConversationEntry = { const entityStorage = new AsyncLocalStorage(); -// Global fallback for single-threaded / non-async entry points -const globalFallbackContext: EntityContext = { - workflowStack: [], - taskStack: [], - agentStack: [], - spanStack: [], - spansByName: new Map(), -}; +// Read-only state for code running outside any entity scope. Never mutated. +const EMPTY_ENTITY_CONTEXT: EntityContext = Object.freeze({ + workflowStack: Object.freeze([]), + taskStack: Object.freeze([]), + agentStack: Object.freeze([]), + spanStack: Object.freeze([]), + spansByName: new Map(), +}); function getEntityContext(): EntityContext { - return entityStorage.getStore() ?? globalFallbackContext; + return entityStorage.getStore() ?? EMPTY_ENTITY_CONTEXT; +} + +function copyEntityContext(ctx: EntityContext): EntityContext { + return { + workflowStack: ctx.workflowStack, + taskStack: ctx.taskStack, + agentStack: ctx.agentStack, + spanStack: ctx.spanStack, + spansByName: new Map(ctx.spansByName), + }; } /** @@ -59,28 +84,37 @@ function getEntityContext(): EntityContext { * independent entity stacks. */ export function runWithEntityContext(fn: () => T): T { - const ctx: EntityContext = { - workflowStack: [], - taskStack: [], - agentStack: [], - spanStack: [], - spansByName: new Map(), + return entityStorage.run(copyEntityContext(EMPTY_ENTITY_CONTEXT), fn); +} + +/** + * Run `fn` in a new entity scope: a copy of the caller's scope with + * `entityName` pushed onto the `entityType` stack. Spans started inside `fn` + * (synchronously or in its async continuations) see it; the caller's scope + * and concurrent calls never do. Unknown entity types get a plain copy. + */ +export function runWithEntity(entityType: string, entityName: string, fn: () => T): T { + const next = copyEntityContext(getEntityContext()) as { + -readonly [K in keyof EntityContext]: EntityContext[K]; }; - return entityStorage.run(ctx, fn); + const key = STACK_FOR_ENTITY[entityType]; + if (key) next[key] = [...next[key], entityName]; + return entityStorage.run(next, fn); } // SessionManager export class SessionManager { - // Span registry (name → stack) + // Span registry (name → stack), scoped to the current entity scope static registerSpan(name: string, span: Span): void { try { - const ctx = getEntityContext(); - const stack = ctx.spansByName.get(name) ?? []; - stack.push(span); - ctx.spansByName.set(name, stack); + // Outside any entity scope there is nowhere request-local to keep it; + // a module-level registry would retain spans that never end (JS-MEM-005). + const ctx = entityStorage.getStore(); + if (!ctx) return; + ctx.spansByName.set(name, [...(ctx.spansByName.get(name) ?? []), span]); } catch (e) { NetraLogger.error(`Failed to register span '${name}':`, e); } @@ -88,16 +122,14 @@ export class SessionManager { static unregisterSpan(name: string, span: Span): void { try { - const ctx = getEntityContext(); - const stack = ctx.spansByName.get(name); - if (!stack) return; - for (let i = stack.length - 1; i >= 0; i--) { - if (stack[i] === span) { - stack.splice(i, 1); - break; - } - } - if (stack.length === 0) ctx.spansByName.delete(name); + const ctx = entityStorage.getStore(); + const stack = ctx?.spansByName.get(name); + if (!ctx || !stack) return; + const idx = stack.lastIndexOf(span); + if (idx === -1) return; + const next = [...stack.slice(0, idx), ...stack.slice(idx + 1)]; + if (next.length === 0) ctx.spansByName.delete(name); + else ctx.spansByName.set(name, next); } catch (e) { NetraLogger.error(`Failed to unregister span '${name}':`, e); } @@ -111,31 +143,10 @@ export class SessionManager { // Entity stacks (workflow / task / agent / span) - static pushEntity(entityType: string, entityName: string): void { - const ctx = getEntityContext(); - switch (entityType) { - case "workflow": ctx.workflowStack.push(entityName); break; - case "task": ctx.taskStack.push(entityName); break; - case "agent": ctx.agentStack.push(entityName); break; - case "span": ctx.spanStack.push(entityName); break; - } - } - - static popEntity(entityType: string): string | undefined { - const ctx = getEntityContext(); - switch (entityType) { - case "workflow": return ctx.workflowStack.pop(); - case "task": return ctx.taskStack.pop(); - case "agent": return ctx.agentStack.pop(); - case "span": return ctx.spanStack.pop(); - default: return undefined; - } - } - static getCurrentEntityAttributes(): Record { const ctx = getEntityContext(); const attrs: Record = {}; - const last = (arr: T[]) => arr[arr.length - 1]; + const last = (arr: readonly T[]) => arr[arr.length - 1]; if (ctx.workflowStack.length) attrs[`${Config.LIBRARY_NAME}.workflow.name`] = last(ctx.workflowStack)!; if (ctx.taskStack.length) attrs[`${Config.LIBRARY_NAME}.task.name`] = last(ctx.taskStack)!; if (ctx.agentStack.length) attrs[`${Config.LIBRARY_NAME}.agent.name`] = last(ctx.agentStack)!; @@ -143,12 +154,14 @@ export class SessionManager { return attrs; } + /** + * Clear the entity stacks for the rest of the current async flow. The + * caller's enclosing scope is not modified. + */ static clearEntityStacks(): void { - const ctx = getEntityContext(); - ctx.workflowStack = []; - ctx.taskStack = []; - ctx.agentStack = []; - ctx.spanStack = []; + const ctx = entityStorage.getStore(); + if (!ctx) return; + entityStorage.enterWith({ ...copyEntityContext(ctx), workflowStack: [], taskStack: [], agentStack: [], spanStack: [] }); } // OTel context helpers diff --git a/src/simulation/api.ts b/src/simulation/api.ts index 6c2eb15..8d88d22 100644 --- a/src/simulation/api.ts +++ b/src/simulation/api.ts @@ -43,6 +43,15 @@ export interface SimulationOptions { /** * Public API for running multi-turn conversation simulations. */ + +const DEFAULT_MAX_CONVERSATION_TURNS = 100; + +/** Most turns one simulated conversation may take (NETRA_SIMULATION_MAX_TURNS). */ +function maxConversationTurns(): number { + const value = Number(process.env.NETRA_SIMULATION_MAX_TURNS); + return Number.isInteger(value) && value > 0 ? value : DEFAULT_MAX_CONVERSATION_TURNS; +} + export class Simulation { private _config: Config; private _client: SimulationHttpClient; @@ -435,8 +444,19 @@ export class Simulation { let turnId = initialTurnId; let sessionId: string | null = null; let rawFiles: FileData[] = initialFiles ?? []; - - while (true) { + const maxTurns = maxConversationTurns(); + + for (let turn = 1; ; turn++) { + // The backend decides when a conversation ends; this bounds a + // conversation it never stops (JS-PERF-011). + if (turn > maxTurns) { + const errorMsg = `Conversation exceeded ${maxTurns} turns (NETRA_SIMULATION_MAX_TURNS)`; + NetraLogger.notice("error", `${LOG_PREFIX}: ${errorMsg}, run_item_id=${runItemId}`); + await this._client.reportFailure(runId, runItemId, errorMsg); + const itemResult: ConversationResult = { runItemId, success: false, error: errorMsg, turnId }; + await this._runAfterHooks(runId, runItemId, datasetItemId, hooks, itemResult as any, setupContext); + return itemResult; + } const span = new SpanWrapper( SPAN_NAME, { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION }, @@ -488,8 +508,11 @@ export class Simulation { return itemResult; } - message = response.nextUserMessage!; - turnId = response.nextTurnId!; + if (!response.nextTurnId || response.nextUserMessage === undefined || response.nextUserMessage === null) { + throw new Error("Conversation response has no next turn and did not stop"); + } + message = response.nextUserMessage; + turnId = response.nextTurnId; rawFiles = response.nextFiles || []; } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error); diff --git a/src/simulation/client.ts b/src/simulation/client.ts index 67445f4..fbe832a 100644 --- a/src/simulation/client.ts +++ b/src/simulation/client.ts @@ -43,10 +43,20 @@ export class SimulationHttpClient { const timeout = this._getTimeout(); try { + const apiOrigin = new URL(baseURL).origin; const instance = axios.create({ baseURL, headers, timeout, + // Redirects stay on the API's origin, so x-api-key is never + // sent to another host (JS-SEC-017). + maxRedirects: 3, + beforeRedirect: (options: Record) => { + const target = String(options.href ?? `${options.protocol}//${options.host ?? options.hostname}${options.path ?? ""}`); + if (new URL(target).origin !== apiOrigin) { + throw new Error(`refusing to follow a redirect to another origin (${new URL(target).origin})`); + } + }, }); // Inject W3C trace context (traceparent/tracestate) into every diff --git a/src/simulation/download-guard.ts b/src/simulation/download-guard.ts new file mode 100644 index 0000000..4a4fa0d --- /dev/null +++ b/src/simulation/download-guard.ts @@ -0,0 +1,110 @@ +/** + * Checks for simulation file downloads (JS-SEC-017). + * + * `downloadUrl` values come from the Netra backend. Without checks, any URL it + * returned was fetched from the app's network, including internal services and + * cloud metadata endpoints, with no size limit and up to 21 redirects. + */ +import { promises as dns } from "dns"; +import { isIP } from "net"; + +const DEFAULT_MAX_FILE_BYTES = 50 * 1024 * 1024; +export const MAX_DOWNLOAD_REDIRECTS = 3; + +/** Largest file accepted, from NETRA_SIMULATION_MAX_FILE_BYTES (default 50 MiB). */ +export function maxDownloadBytes(): number { + const value = Number(process.env.NETRA_SIMULATION_MAX_FILE_BYTES); + return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_FILE_BYTES; +} + +function ipv4ToInt(ip: string): number { + return ip.split(".").reduce((acc, part) => (acc << 8) + Number(part), 0) >>> 0; +} + +function inV4Range(ip: string, base: string, bits: number): boolean { + const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0; + return (ipv4ToInt(ip) & mask) === (ipv4ToInt(base) & mask); +} + +const PRIVATE_V4: Array<[string, number]> = [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], // carrier-grade NAT + ["127.0.0.0", 8], + ["169.254.0.0", 16], // link-local, cloud metadata + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +]; + +/** True for loopback, private, link-local, CGNAT, multicast and reserved addresses. */ +export function isPrivateAddress(ip: string): boolean { + const family = isIP(ip); + if (family === 4) return PRIVATE_V4.some(([base, bits]) => inV4Range(ip, base, bits)); + if (family === 6) { + const v6 = ip.toLowerCase(); + const mapped = v6.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); + if (mapped) return isPrivateAddress(mapped[1]); + return ( + v6 === "::" || + v6 === "::1" || + v6.startsWith("fc") || + v6.startsWith("fd") || // unique local + /^fe[89ab]/.test(v6) || // link-local + v6.startsWith("ff") // multicast + ); + } + return false; +} + +/** Host of the configured Netra endpoint, which is always allowed. */ +function netraHost(): string | undefined { + const endpoint = process.env.NETRA_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + if (!endpoint) return undefined; + try { + return new URL(endpoint.trim()).hostname.toLowerCase(); + } catch { + return undefined; + } +} + +/** + * Synchronous checks on a URL: scheme and literal host. Used for the first + * URL and for every redirect target. + */ +export function checkDownloadUrlSync(raw: string): URL { + let url: URL; + try { + url = new URL(raw); + } catch { + throw new Error("download URL is not a valid URL"); + } + const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase(); + const trusted = host === netraHost(); + if (url.protocol !== "https:" && !(url.protocol === "http:" && trusted)) { + throw new Error(`download URL must use https (got ${url.protocol})`); + } + if (!trusted && (host === "localhost" || host.endsWith(".localhost") || isPrivateAddress(host))) { + throw new Error(`download URL points to a private or local address (${host})`); + } + return url; +} + +/** + * Full check before downloading: scheme, literal host, and every address the + * hostname resolves to. + */ +export async function assertSafeDownloadUrl(raw: string): Promise { + const url = checkDownloadUrlSync(raw); + const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase(); + if (host === netraHost() || isIP(host)) return url; + const addresses = await dns.lookup(host, { all: true }); + const blocked = addresses.find((a) => isPrivateAddress(a.address)); + if (blocked) { + throw new Error(`download URL host ${host} resolves to a private address (${blocked.address})`); + } + return url; +} diff --git a/src/simulation/utils.ts b/src/simulation/utils.ts index c767b7b..73ddc9b 100644 --- a/src/simulation/utils.ts +++ b/src/simulation/utils.ts @@ -1,6 +1,12 @@ import axios from "axios"; import { createLimit, LimitFunction } from "../utils/concurrency-limit"; import { NetraLogger } from "../netraLogger"; +import { + assertSafeDownloadUrl, + checkDownloadUrlSync, + MAX_DOWNLOAD_REDIRECTS, + maxDownloadBytes, +} from "./download-guard"; import { FileData, ProcessedFile } from "./models"; import { BaseTask } from "./task"; @@ -89,10 +95,20 @@ async function _downloadSingleFile( signal?: AbortSignal, ): Promise { try { + // Scheme, host and resolved addresses are checked first, and again + // for every redirect; size and redirect count are bounded (JS-SEC-017). + await assertSafeDownloadUrl(fileData.downloadUrl); + const maxBytes = maxDownloadBytes(); const response = await axios.get(fileData.downloadUrl, { responseType: "arraybuffer", timeout: timeoutMs, signal, + maxRedirects: MAX_DOWNLOAD_REDIRECTS, + maxContentLength: maxBytes, + maxBodyLength: maxBytes, + beforeRedirect: (options: Record) => { + checkDownloadUrlSync(String(options.href ?? `${options.protocol}//${options.hostname}${options.path ?? ""}`)); + }, }); const encoded = Buffer.from(response.data).toString("base64"); diff --git a/src/utils/response-handler.ts b/src/utils/response-handler.ts index f9974e2..dd62dd9 100644 --- a/src/utils/response-handler.ts +++ b/src/utils/response-handler.ts @@ -20,6 +20,17 @@ export function isPromise(value: unknown): value is Promise { return value != null && typeof (value as any).then === "function"; } +/** + * A real Promise (including subclasses such as the provider SDKs' APIPromise, + * and promises from another realm), as opposed to any object with a `then` + * method. Query builders (Knex, Prisma, Mongoose, ...) are lazy thenables: + * calling `then` runs the query (JS-SEC-010). + */ +export function isNativePromise(value: unknown): value is Promise { + if (value == null || typeof (value as any).then !== "function") return false; + return value instanceof Promise || Object.prototype.toString.call(value) === "[object Promise]"; +} + /** * The `APIPromise` returned by Stainless-generated SDKs (OpenAI, Anthropic, * Groq): a Promise subclass whose extra methods (`.withResponse()`, @@ -48,6 +59,31 @@ export function isAPIPromise(value: unknown): value is APIPromiseLike { const ITERATOR_METHODS = new Set(["next", "return", "throw"]); +/** + * Ends the span of a stream the app dropped without reading to the end or + * cancelling: once the stream object is garbage-collected, nothing can read + * it any more, so its span is finalized. Without this the span was never + * ended or exported and stayed in memory (JS-MEM-003). + */ +interface FinalizationRegistryLike { + register(target: object, held: T, unregisterToken?: object): void; + unregister(unregisterToken: object): void; +} +type FinalizationRegistryCtor = new (cleanup: (held: T) => void) => FinalizationRegistryLike; +// Reached through globalThis: the project's TS lib predates ES2021 weakrefs. +const FinalizationRegistryImpl = (globalThis as { FinalizationRegistry?: FinalizationRegistryCtor }) + .FinalizationRegistry; +const abandonedStreams: FinalizationRegistryLike<() => void> | undefined = + FinalizationRegistryImpl + ? new FinalizationRegistryImpl<() => void>((finalize) => { + try { + finalize(); + } catch (e) { + NetraLogger.debug("netra: finalizing an abandoned stream failed", e); + } + }) + : undefined; + /** * Wrap an async iterable with lifecycle callbacks. * Returns a Proxy that preserves the original object's full interface @@ -61,6 +97,35 @@ export function wrapAsyncIterable( source: AsyncIterable, callbacks: ResponseCallbacks, ): any { + // One stream, one finalize, however it is consumed (iteration, a reader, + // cancel(), or garbage collection). + const state = { settled: false }; + const unregisterToken = {}; + const finalizeOnce = (status: "ok" | "error") => { + if (state.settled) return; + state.settled = true; + abandonedStreams?.unregister(unregisterToken); + try { + callbacks.finalize(status); + } catch (e) { + NetraLogger.error("netra: finalize callback error", e); + } + }; + const safeOnChunk = (chunk: T) => { + try { + callbacks.onChunk?.(chunk); + } catch (e) { + NetraLogger.error("netra: onChunk callback error", e); + } + }; + const safeOnError = (e: unknown) => { + try { + callbacks.onError(e); + } catch { + NetraLogger.error("netra: onError callback error", e); + } + }; + function createWrappedIterator(): AsyncIterator { const iterator = source[Symbol.asyncIterator](); let done = false; @@ -68,11 +133,7 @@ export function wrapAsyncIterable( const safeFinalize = (status: "ok" | "error") => { if (done) return; done = true; - try { - callbacks.finalize(status); - } catch (e) { - NetraLogger.error("netra: finalize callback error", e); - } + finalizeOnce(status); }; return { @@ -139,11 +200,61 @@ export function wrapAsyncIterable( let directIterator: AsyncIterator | null = null; - return new Proxy(source, { + /** + * ReadableStream-style streams (LangGraph's IterableReadableStream) can be + * read with getReader() or cancelled without ever iterating; observe those + * paths too so the span still ends (JS-MEM-003). + */ + const wrapReader = (reader: any): any => { + if (!reader || typeof reader.read !== "function") return reader; + return new Proxy(reader, { + get(r, prop) { + const value = r[prop]; + if (prop === "read" && typeof value === "function") { + return async (...args: any[]) => { + try { + const result = await callbacks.withContext(() => value.apply(r, args)); + if (result?.done) finalizeOnce("ok"); + else safeOnChunk(result?.value); + return result; + } catch (e) { + safeOnError(e); + finalizeOnce("error"); + throw e; + } + }; + } + if (prop === "cancel" && typeof value === "function") { + return async (...args: any[]) => { + try { + return await value.apply(r, args); + } finally { + finalizeOnce("ok"); + } + }; + } + return typeof value === "function" ? value.bind(r) : value; + }, + }); + }; + + const proxy = new Proxy(source, { get(target, prop, receiver) { if (prop === Symbol.asyncIterator) { return () => createWrappedIterator(); } + if (prop === "getReader" && typeof (target as any).getReader === "function") { + return (...args: any[]) => wrapReader((target as any).getReader(...args)); + } + if (prop === "cancel" && typeof (target as any).cancel === "function") { + return async (...args: any[]) => { + try { + return await (target as any).cancel(...args); + } finally { + finalizeOnce("ok"); + } + }; + } if (typeof prop === "string" && ITERATOR_METHODS.has(prop)) { if (!directIterator) directIterator = createWrappedIterator(); return (directIterator as any)[prop].bind(directIterator); @@ -159,6 +270,8 @@ export function wrapAsyncIterable( return value; }, }); + abandonedStreams?.register(proxy, () => finalizeOnce("ok"), unregisterToken); + return proxy; } /** @@ -261,7 +374,7 @@ export function wrapPromise( try { const value = await promise; if (isAsyncIterable(value)) { - return wrapAsyncIterable(value as any, callbacks); + return wrapAsyncIterable(value as any, { ...callbacks, finalize: safeFinalize }); } safeOnSuccess(value); safeFinalize("ok"); @@ -282,7 +395,7 @@ export function wrapPromise( // The caller still sees the error through its own then/catch. instrumentedPromise.catch(() => {}); - const original = options.preserveOriginal; + const original = options.preserveOriginal as any; return new Proxy(instrumentedPromise, { get(target, prop, receiver) { if (prop === "then" || prop === "catch" || prop === "finally") { @@ -290,6 +403,32 @@ export function wrapPromise( if (typeof value === "function") return value.bind(target); return value; } + // `.withResponse()` resolves to the SDK's own stream, which Netra never + // sees being read, so the span never ended (JS-MEM-003). Hand back the + // same result with a wrapped stream. + if (prop === "withResponse" && typeof original.withResponse === "function") { + return async (...args: any[]) => { + const result = await original.withResponse(...args); + if (result && isAsyncIterable(result.data)) { + return { ...result, data: wrapAsyncIterable(result.data, { ...callbacks, finalize: safeFinalize }) }; + } + return result; + }; + } + // `.asResponse()` on a stream: the app reads the raw bytes itself and + // nothing more can be observed, so end the span once the call returns. + if (prop === "asResponse" && typeof original.asResponse === "function") { + return async (...args: any[]) => { + const response = await original.asResponse(...args); + instrumentedPromise.then( + (value) => { + if (isAsyncIterable(value)) safeFinalize("ok"); + }, + () => {}, + ); + return response; + }; + } const originalValue = (original as any)[prop]; if (originalValue !== undefined) { if (typeof originalValue === "function") @@ -318,10 +457,22 @@ export function wrapResponse( return wrapAsyncIterable(response as any, callbacks) as T; } - if (isPromise(response)) { + if (isNativePromise(response)) { return wrapPromise(response as any, callbacks, options) as T; } + if (isPromise(response)) { + // A lazy thenable: awaiting it would run it early, outside the caller's + // control (for example outside a database transaction). Hand it back + // untouched; the span ends now, without an output (JS-SEC-010). + try { + callbacks.finalize("ok"); + } catch (e) { + NetraLogger.error("netra: finalize callback error", e); + } + return response; + } + try { callbacks.onSuccess?.(response); } catch (e) { diff --git a/src/utils/serialization/safe-stringify.ts b/src/utils/serialization/safe-stringify.ts index 54c18ac..d6dd4d1 100644 --- a/src/utils/serialization/safe-stringify.ts +++ b/src/utils/serialization/safe-stringify.ts @@ -11,6 +11,68 @@ export interface SafeStringifyOptions { * When called without options, performs pure serialization with no truncation. * Pass `{ maxLength }` to enable hard truncation of the final result. */ +const OVER_BUDGET = "[TRUNCATED]"; +/** Class instances with more own keys than this are summarized as `[ClassName]`. */ +const MAX_INSTANCE_KEYS = 20; + +/** `[Buffer 1048576 bytes]` for binary data, otherwise undefined (JS-MEM-007). */ +function describeBinary(val: unknown): string | undefined { + if (val === null || typeof val !== "object") return undefined; + if (typeof Buffer !== "undefined" && Buffer.isBuffer(val)) return `[Buffer ${val.length} bytes]`; + if (ArrayBuffer.isView(val)) return `[${val.constructor?.name ?? "TypedArray"} ${val.byteLength} bytes]`; + if (val instanceof ArrayBuffer) return `[ArrayBuffer ${val.byteLength} bytes]`; + return undefined; +} + +/** + * A shallow copy of `val` with binary children replaced by their description, + * or `val` itself when it has none. Done while visiting the parent, because + * JSON.stringify calls a Buffer's toJSON() (one array element per byte) before + * the replacer ever sees the Buffer. + */ +function withBinaryChildrenDescribed(val: object): object { + let copy: any; + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + const description = describeBinary(val[i]); + if (description) { + copy ??= val.slice(); + copy[i] = description; + } + } + return copy ?? val; + } + for (const key of Object.keys(val)) { + const description = describeBinary((val as any)[key]); + if (description) { + copy ??= { ...val }; + copy[key] = description; + } + } + return copy ?? val; +} + +/** True when `val` has more than `limit` enumerable keys, without listing them all. */ +function hasMoreKeysThan(val: object, limit: number): boolean { + let n = 0; + for (const _ in val) { + if (++n > limit) return true; + } + return false; +} + +/** + * Circular-reference-safe JSON serialization. + * + * Handles circular references, functions, symbols, bigints, binary data and + * large class instances gracefully. Never throws. + * + * When called without options, performs pure serialization with no truncation. + * Pass `{ maxLength }` to bound the work as well as the result: once roughly + * `maxLength` characters have been produced, remaining values are replaced + * with "[TRUNCATED]" instead of being walked, and the result is cut to + * `maxLength` (JS-MEM-007, JS-PERF-012). + */ export function safeStringify(value: unknown, options?: SafeStringifyOptions): string { const maxLength = options?.maxLength; @@ -30,27 +92,46 @@ export function safeStringify(value: unknown, options?: SafeStringifyOptions): s if (t === "symbol") return (value as symbol).toString(); if (t === "function") return `[Function: ${(value as Function).name || "anonymous"}]`; + const binary = describeBinary(value); + if (binary) return binary; + const seen = new WeakSet(); + let produced = 0; let result: string; try { - result = JSON.stringify(value, (_key, val) => { + result = JSON.stringify(value, function (this: any, key, val) { + if (maxLength && produced > maxLength) return OVER_BUDGET; + produced += key.length + 4; + // `toJSON` has already run on `val`; the holder still has the original, + // so a Buffer is caught here before it becomes an array of numbers. + const original = key === "" ? value : this?.[key]; + const binaryVal = describeBinary(original); + if (binaryVal) { + produced += binaryVal.length; + return binaryVal; + } if (typeof val === "function") return `[Function: ${val.name || "anonymous"}]`; if (typeof val === "symbol") return val.toString(); if (typeof val === "bigint") return val.toString(); + if (typeof val === "string") { + produced += val.length; + if (maxLength && val.length > maxLength) return val.slice(0, maxLength); + return val; + } + if (typeof val === "number" || typeof val === "boolean") { + produced += 6; + return val; + } if (val !== null && typeof val === "object") { if (seen.has(val)) return "[Circular]"; seen.add(val); const name = val.constructor?.name; - if ( - name && - name !== "Object" && - name !== "Array" && - Object.keys(val).length > 20 - ) { + if (name && name !== "Object" && name !== "Array" && hasMoreKeysThan(val, MAX_INSTANCE_KEYS)) { return `[${name}]`; } + return withBinaryChildrenDescribed(val); } return val; }) ?? "null"; From b2b065ff202b1ab10cb54bbb42b9e95fcf49466e Mon Sep 17 00:00:00 2001 From: RiyaSunil27 Date: Fri, 20 Nov 2026 17:21:39 +0530 Subject: [PATCH 2/2] fix: Keep stream spans open until the stream is dropped, block private IPv6 and redirect targets in simulation downloads, and add the missing tests and CI config --- .github/dependabot.yml | 17 ++ .github/workflows/ci.yml | 81 ++++++ src/api/http-client.test.ts | 113 ++++++++ src/audit-remaining.test.ts | 212 +++++++++++++++ src/config.security.test.ts | 131 ++++++++++ src/entity-scope.test.ts | 116 +++++++++ src/exporters/trialAwareOtlpExporter.test.ts | 246 ++++++++++++++++++ src/index.host-provider.test.ts | 36 +++ src/index.lifecycle.test.ts | 53 ++++ .../anthropic/wrappers.test.ts | 28 ++ .../langgraph/wrappers.test.ts | 26 ++ src/instrumentation/typeorm/utils.test.ts | 40 +++ src/processors/span-io-performance.test.ts | 73 ++++++ src/simulation/download-guard.test.ts | 134 ++++++++++ src/simulation/download-guard.ts | 192 ++++++++++++-- src/simulation/utils.ts | 43 ++- src/utils/response-handler.test.ts | 97 ++++++- src/utils/response-handler.ts | 59 ++++- 18 files changed, 1653 insertions(+), 44 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 src/api/http-client.test.ts create mode 100644 src/audit-remaining.test.ts create mode 100644 src/config.security.test.ts create mode 100644 src/entity-scope.test.ts create mode 100644 src/exporters/trialAwareOtlpExporter.test.ts create mode 100644 src/index.host-provider.test.ts create mode 100644 src/index.lifecycle.test.ts create mode 100644 src/instrumentation/typeorm/utils.test.ts create mode 100644 src/processors/span-io-performance.test.ts create mode 100644 src/simulation/download-guard.test.ts diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..c73b30a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +# Weekly dependency and GitHub Actions updates (JS-SEC-026). +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 10 + groups: + opentelemetry: + patterns: ["@opentelemetry/*"] + traceloop: + patterns: ["@traceloop/*"] + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..df6c73e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,81 @@ +name: CI + +# Type-checks, tests and builds every change, and checks that the CommonJS +# build loads with require() on the oldest Node versions `engines` allows +# (JS-SEC-020, JS-SEC-026, JS-PERF-004). + +on: + pull_request: + push: + branches: [main, dev] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Test (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci + - run: npx tsc --noEmit -p . + - run: npx vitest run + - run: npm run build + - name: Upload build + if: matrix.node == 22 + uses: actions/upload-artifact@v4 + with: + name: dist + path: dist + retention-days: 1 + + require-cjs: + name: require() on Node ${{ matrix.node }} + needs: test + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + # Versions without require(esm): an ESM-only runtime dependency makes + # require("netra-sdk") throw ERR_REQUIRE_ESM here. + node: ["18", "20.18.0", "22.11.0"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + - run: npm ci --omit=dev --ignore-scripts --no-audit --no-fund + - run: node -e "const { Netra } = require('./dist/index.cjs'); if (typeof Netra?.init !== 'function') process.exit(1); console.log('require() ok')" + + audit: + name: npm audit (production dependencies) + runs-on: ubuntu-latest + timeout-minutes: 5 + # Reported, not blocking: some advisories come in through + # @traceloop/node-server-sdk with no fix available yet (JS-SEC-019). + continue-on-error: true + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm audit --omit=dev --audit-level=high diff --git a/src/api/http-client.test.ts b/src/api/http-client.test.ts new file mode 100644 index 0000000..33a1b9f --- /dev/null +++ b/src/api/http-client.test.ts @@ -0,0 +1,113 @@ +/** + * JS-PERF-009 / JS-SEC-017 regression tests for the REST client: a deadline + * that covers the body, no timer left behind, bounded bodies, GET retries, + * and redirects that never take x-api-key to another origin. + */ +import * as http from "node:http"; +import { AddressInfo } from "node:net"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { Config } from "../config"; +import { NetraLogger } from "../netraLogger"; +import { NetraHttpClient } from "./http-client"; + +type Handler = (req: http.IncomingMessage, res: http.ServerResponse) => void; +async function serve(handler: Handler) { + const seen: http.IncomingHttpHeaders[] = []; + const server = http.createServer((req, res) => { seen.push(req.headers); handler(req, res); }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + return { url, seen, close: () => new Promise((r) => { server.closeAllConnections(); server.close(() => r()); }) }; +} + +function clientFor(base: string, timeoutSeconds = 3): NetraHttpClient { + process.env.NETRA_OTLP_ENDPOINT = `${base}/telemetry`; + process.env.NETRA_API_KEY = "netra-key-TEST"; + return new NetraHttpClient(new Config(), "NETRA_TEST_TIMEOUT", timeoutSeconds); +} + +const timers = () => process.getActiveResourcesInfo().filter((r) => r === "Timeout").length; + +describe("NetraHttpClient", () => { + const saved = { endpoint: process.env.NETRA_OTLP_ENDPOINT, key: process.env.NETRA_API_KEY }; + beforeEach(() => vi.spyOn(NetraLogger, "notice").mockImplementation(() => {})); + afterEach(() => { + vi.restoreAllMocks(); + process.env.NETRA_OTLP_ENDPOINT = saved.endpoint; + process.env.NETRA_API_KEY = saved.key; + if (saved.endpoint === undefined) delete process.env.NETRA_OTLP_ENDPOINT; + if (saved.key === undefined) delete process.env.NETRA_API_KEY; + }); + + it("PERF-009: a failed request leaves no timer behind", async () => { + const s = await serve(() => {}); + const url = s.url; + await s.close(); // nothing listens: ECONNREFUSED + const client = clientFor(url, 30); + const before = timers(); + const res = await client.post("/x", { a: 1 }); + expect(res.ok).toBe(false); + expect(timers()).toBeLessThanOrEqual(before); + }); + + it("PERF-009: the deadline covers a body that never finishes", async () => { + const s = await serve((_q, res) => { res.writeHead(200, { "Content-Type": "application/json" }); res.write("{"); }); + const client = clientFor(s.url, 1); + const t0 = Date.now(); + const res = await client.post("/slow-body", {}); + expect(res.ok).toBe(false); + expect(Date.now() - t0).toBeLessThan(2500); + await s.close(); + }); + + it("PERF-009: GET retries 503 and succeeds; POST does not retry", async () => { + let gets = 0; + let posts = 0; + const s = await serve((req, res) => { + if (req.method === "GET") gets++; else posts++; + const n = req.method === "GET" ? gets : posts; + res.writeHead(n < 2 ? 503 : 200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ data: { n } })); + }); + const client = clientFor(s.url, 5); + vi.spyOn(Math, "random").mockReturnValue(0); + expect((await client.get("/g")).ok).toBe(true); + expect(gets).toBe(2); + expect((await client.post("/p", {})).status).toBe(503); + expect(posts).toBe(1); + await s.close(); + }); + + it("PERF-009: rejects a response larger than the limit", async () => { + const s = await serve((_q, res) => { + res.writeHead(200, { "Content-Type": "application/json", "Content-Length": String(11 * 1024 * 1024) }); + res.end(); + }); + const client = clientFor(s.url, 3); + expect((await client.get("/huge")).ok).toBe(false); + await s.close(); + }); + + it("SEC-017: follows same-origin redirects", async () => { + const s = await serve((req, res) => { + if (req.url === "/old") { res.writeHead(302, { Location: "/new" }); res.end(); return; } + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ data: "moved" })); + }); + const client = clientFor(s.url); + const res = await client.get("/old"); + expect(res.ok).toBe(true); + expect(res.data).toEqual({ data: "moved" }); + await s.close(); + }); + + it("SEC-017: refuses a cross-origin redirect, so the key never reaches the other host", async () => { + const other = await serve((_q, res) => { res.writeHead(200); res.end("{}"); }); + const api = await serve((_q, res) => { res.writeHead(302, { Location: `${other.url}/steal` }); res.end(); }); + const client = clientFor(api.url); + expect((await client.get("/redirect")).ok).toBe(false); + expect(other.seen).toHaveLength(0); + await other.close(); + await api.close(); + }); +}); diff --git a/src/audit-remaining.test.ts b/src/audit-remaining.test.ts new file mode 100644 index 0000000..c85550f --- /dev/null +++ b/src/audit-remaining.test.ts @@ -0,0 +1,212 @@ +/** + * Regression tests for the remaining Nov 2026 audit items: SEC-009, SEC-010, + * SEC-021, SEC-023, SEC-024, MEM-007, MEM-009, PERF-005, PERF-011, PERF-012, + * PERF-015. + */ +import { context, trace } from "@opentelemetry/api"; +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; +import { + BasicTracerProvider, + InMemorySpanExporter, + SimpleSpanProcessor, +} from "@opentelemetry/sdk-trace-base"; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +import { Config } from "./config"; +import { workflow } from "./decorators"; +import { sanitizeForLog } from "./exporters/trialAwareOtlpExporter"; +import { isValidChoiceIndex, MAX_STREAM_CHOICES, setRequestAttributes } from "./instrumentation/utils"; +import { isSensitiveKey, ScrubbingSpanProcessor } from "./processors/scrubbing-span-processor"; +import { safeStringify } from "./utils/serialization"; +import { Prompts } from "./api/prompts"; +import { Dashboard } from "./api/dashboard"; + +const named = any>(name: string, fn: T): T => + Object.defineProperty(fn, "name", { value: name }); + +describe("safeStringify (MEM-007, PERF-012)", () => { + it("summarizes Buffers and typed arrays instead of expanding every byte", () => { + const buf = Buffer.alloc(1024 * 1024, 7); + expect(safeStringify(buf)).toBe("[Buffer 1048576 bytes]"); + expect(safeStringify({ file: buf, bytes: new Uint8Array(10) })).toBe( + JSON.stringify({ file: "[Buffer 1048576 bytes]", bytes: "[Uint8Array 10 bytes]" }), + ); + }); + + it("never expands a nested Buffer through toJSON()", () => { + const toJSON = vi.spyOn(Buffer.prototype, "toJSON"); + const out = safeStringify([Buffer.alloc(4 * 1024 * 1024), { nested: { file: Buffer.alloc(10) } }]); + expect(toJSON).not.toHaveBeenCalled(); + toJSON.mockRestore(); + expect(out).toBe(JSON.stringify(["[Buffer 4194304 bytes]", { nested: { file: "[Buffer 10 bytes]" } }])); + }); + + it("stops walking once the budget is used", () => { + const big = Array.from({ length: 50_000 }, (_, i) => ({ i, text: "x".repeat(50) })); + const t0 = performance.now(); + const out = safeStringify(big, { maxLength: 2000 }); + expect(out.length).toBeLessThanOrEqual(2000); + expect(performance.now() - t0).toBeLessThan(500); + }); + + it("still serializes ordinary values exactly", () => { + const value = { a: 1, b: "two", c: [true, null], d: { e: 1.5 } }; + expect(safeStringify(value)).toBe(JSON.stringify(value)); + expect(safeStringify(value, { maxLength: 1000 })).toBe(JSON.stringify(value)); + }); +}); + +describe("decorators and thenables (SEC-010)", () => { + const exporter = new InMemorySpanExporter(); + const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] }); + beforeAll(() => { + context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable()); + trace.setGlobalTracerProvider(provider); + }); + afterAll(async () => { + trace.disable(); + context.disable(); + await provider.shutdown(); + }); + + it("returns a lazy query builder untouched and does not run it", async () => { + let executed = 0; + const builder = { + where() { return this; }, + then(resolve: (v: unknown) => void) { executed++; resolve([{ id: 1 }]); }, + }; + const findUsers = workflow(named("find-users", () => builder)); + const result = findUsers(); + expect(result).toBe(builder); + expect(typeof (result as any).where).toBe("function"); + expect(executed).toBe(0); + expect(exporter.getFinishedSpans().map((s) => s.name)).toContain("find-users"); + // The app decides when it runs. + await result; + expect(executed).toBe(1); + }); + + it("still awaits real promises", async () => { + const add = workflow(named("add", async (a: number, b: number) => a + b)); + await expect(add(1, 2)).resolves.toBe(3); + }); +}); + +describe("scrubbing (SEC-009, SEC-021)", () => { + const exporter = new InMemorySpanExporter(); + const provider = new BasicTracerProvider({ + spanProcessors: [new ScrubbingSpanProcessor(), new SimpleSpanProcessor(exporter)], + }); + const tracer = provider.getTracer("t"); + afterAll(() => provider.shutdown()); + beforeEach(() => exporter.reset()); + + it("SEC-009: a crafted message does not freeze the app", () => { + const span = tracer.startSpan("redos"); + const t0 = performance.now(); + span.setAttribute("input", "a.".repeat(20_000) + "1-".repeat(20_000)); + span.end(); + expect(performance.now() - t0).toBeLessThan(500); + }); + + it("SEC-009: still scrubs emails", () => { + const span = tracer.startSpan("email"); + span.setAttribute("input", "contact first.last+x@sub.example.co.uk today"); + span.end(); + expect(exporter.getFinishedSpans()[0].attributes.input).toBe("contact [SCRUBBED] today"); + }); + + it("SEC-021: scrubs start attributes, events, exceptions, status and name", () => { + const span = tracer.startSpan("charge sk-ABCDEFGHIJKLMNOPQRST", { + attributes: { note: "card 4111111111111111", password: "hunter2" }, + }); + span.addEvent("retry", { detail: "mail alice@example.com" }); + span.recordException(new Error("token: SECRETVALUE leaked")); + span.setStatus({ code: 2, message: "user bob@example.com failed" }); + span.end(); + const finished = exporter.getFinishedSpans()[0]; + const all = JSON.stringify({ name: finished.name, attributes: finished.attributes, events: finished.events, status: finished.status }); + expect(all).not.toMatch(/4111111111111111|hunter2|alice@example\.com|SECRETVALUE|bob@example\.com|sk-ABCDEFGHIJ/); + }); + + it("SEC-021: matches sensitive key names by whole parts", () => { + for (const key of ["password", "db.password", "x-api-key", "api_key", "http.request.header.authorization", "access_token", "set-cookie"]) { + expect(isSensitiveKey(key)).toBe(true); + } + for (const key of ["netra.span.type", "gen_ai.request.max_tokens", "monkey", "keyword", "author"]) { + expect(isSensitiveKey(key)).toBe(false); + } + }); +}); + +describe("export log hygiene (SEC-024)", () => { + it("escapes control characters and caps length", () => { + const out = sanitizeForLog("ok\n[Netra] forged\u001b[31m" + "x".repeat(500)); + expect(out).not.toMatch(/[\n\u001b]/); + expect(out.length).toBeLessThan(260); + }); +}); + +describe("streamed choice indexes (MEM-009)", () => { + it("rejects huge or invalid indexes", () => { + expect(isValidChoiceIndex(0)).toBe(true); + expect(isValidChoiceIndex(MAX_STREAM_CHOICES - 1)).toBe(true); + expect(isValidChoiceIndex(1e9)).toBe(false); + expect(isValidChoiceIndex(-1)).toBe(false); + expect(isValidChoiceIndex(Number.NaN)).toBe(false); + }); +}); + +describe("request attributes never throw (PERF-005)", () => { + it("survives unserializable reasoning config", () => { + const circular: any = { effort: "high" }; + circular.self = circular; + const span: any = { isRecording: () => true, setAttribute: vi.fn() }; + expect(() => setRequestAttributes(span, { model: "m", reasoning: circular, tools: [circular] }, "chat", "groq")).not.toThrow(); + }); +}); + +describe("prompt cache (SEC-023, PERF-015)", () => { + function promptsWithFakeClient(fetcher: (name: string, label: string) => Promise) { + const prompts = new Prompts(new Config()); + (prompts as any).client = { getPromptVersion: fetcher }; + return prompts; + } + + it("SEC-023: names and labels containing ':' do not collide", async () => { + const prompts = promptsWithFakeClient(async (name, label) => ({ data: { name, label } })); + const a = await prompts.getPrompt({ name: "a:b", label: "c", useCache: true }); + const b = await prompts.getPrompt({ name: "a", label: "b:c", useCache: true }); + expect(a).toMatchObject({ name: "a:b", label: "c" }); + expect(b).toMatchObject({ name: "a", label: "b:c" }); + }); + + it("PERF-015: concurrent cache misses share one request and get separate copies", async () => { + let calls = 0; + const prompts = promptsWithFakeClient(async (name) => { + calls++; + await new Promise((r) => setTimeout(r, 20)); + return { data: { name, messages: [] as string[] } }; + }); + const results = await Promise.all(Array.from({ length: 10 }, () => prompts.getPrompt({ name: "p", useCache: true }))); + expect(calls).toBe(1); + (results[0] as any).messages.push("mutated"); + expect((results[1] as any).messages).toEqual([]); + }); +}); + +describe("session stats paging (PERF-011)", () => { + it("stops when a page claims more without a new cursor", async () => { + const dashboard = new Dashboard(new Config()); + let pages = 0; + (dashboard as any).getSessionStats = async () => { + pages++; + if (pages > 5) throw new Error("looped"); + return { data: [{ id: pages }], hasNextPage: true, nextCursor: undefined }; + }; + const seen: unknown[] = []; + for await (const s of dashboard.iterSessionStats("2026-01-01", "2026-01-02")) seen.push(s); + expect(pages).toBe(1); + expect(seen).toHaveLength(1); + }); +}); diff --git a/src/config.security.test.ts b/src/config.security.test.ts new file mode 100644 index 0000000..1f73b9d --- /dev/null +++ b/src/config.security.test.ts @@ -0,0 +1,131 @@ +/** + * JS-SEC-006 / JS-SEC-007 / JS-SEC-022 / JS-PERF-008 regression tests for + * Config: where the API key is sent, what is written to the environment, and + * startup with unusual OTEL_RESOURCE_ATTRIBUTES. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { Config, isNetraHost } from "./config"; +import { isTraceContentEnabled, setTraceContentEnabled } from "./instrumentation/utils"; +import { NetraLogger } from "./netraLogger"; + +const KEY = "netra-key-TEST"; +const ENV_KEYS = [ + "NETRA_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_ENDPOINT", "NETRA_API_KEY", "NETRA_HEADERS", + "TRACELOOP_API_KEY", "TRACELOOP_HEADERS", "TRACELOOP_BASE_URL", "TRACELOOP_TRACE_CONTENT", + "OTEL_RESOURCE_ATTRIBUTES", "NETRA_TRACE_CONTENT", +]; + +describe("Config security", () => { + const saved: Record = {}; + beforeEach(() => { + for (const k of ENV_KEYS) { saved[k] = process.env[k]; delete process.env[k]; } + vi.spyOn(NetraLogger, "notice").mockImplementation(() => {}); + }); + afterEach(() => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } + setTraceContentEnabled(undefined); + vi.restoreAllMocks(); + }); + + describe("SEC-006: the key only goes to Netra", () => { + it("is not attached for a non-Netra OTEL_EXPORTER_OTLP_ENDPOINT", () => { + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://otel-collector.vendor.example"; + process.env.NETRA_API_KEY = KEY; + const cfg = new Config(); + expect(cfg.apiKey).toBeUndefined(); + expect(JSON.stringify(cfg.headers)).not.toContain(KEY); + expect(vi.mocked(NetraLogger.notice).mock.calls.some(([, m]) => String(m).includes("NETRA_API_KEY is not sent"))).toBe(true); + }); + + it("is not attached when only the URL path contains 'getnetra'", () => { + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://collector.example/getnetra/v1"; + process.env.NETRA_API_KEY = KEY; + expect(JSON.stringify(new Config().headers)).not.toContain(KEY); + }); + + it("is attached as x-api-key for a Netra host, from either variable", () => { + process.env.NETRA_API_KEY = KEY; + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://api.eu.getnetra.ai/telemetry"; + expect(new Config().headers["x-api-key"]).toBe(KEY); + process.env.NETRA_OTLP_ENDPOINT = "https://api.getnetra.ai/telemetry"; + expect(new Config().headers["x-api-key"]).toBe(KEY); + }); + + it("keeps working for an explicit self-hosted NETRA_OTLP_ENDPOINT", () => { + process.env.NETRA_OTLP_ENDPOINT = "https://netra.internal.example/telemetry"; + process.env.NETRA_API_KEY = KEY; + const cfg = new Config(); + expect(cfg.apiKey).toBe(KEY); + expect(cfg.headers.Authorization).toBe(`Bearer ${KEY}`); + }); + + it.each([ + ["https://api.getnetra.ai/telemetry", true], + ["https://getnetra.ai", true], + ["https://api.demo.getnetra.ai", true], + ["https://getnetra.ai.evil.example", false], + ["https://evilgetnetra.ai", false], + ["https://collector.example/getnetra", false], + ["not a url", false], + ])("isNetraHost(%s) = %s", (url, expected) => { + expect(isNetraHost(url)).toBe(expected); + }); + }); + + it("SEC-022: the app's headers object is not modified", () => { + process.env.NETRA_OTLP_ENDPOINT = "https://api.getnetra.ai/telemetry"; + process.env.NETRA_API_KEY = KEY; + const headers = { "x-team": "payments" }; + const cfg = new Config({ headers }); + expect(headers).toEqual({ "x-team": "payments" }); + expect(cfg.headers["x-api-key"]).toBe(KEY); + }); + + describe("SEC-007: nothing secret or shared is left in process.env", () => { + it("does not copy the key, headers or endpoint into TRACELOOP_* variables", () => { + process.env.NETRA_OTLP_ENDPOINT = "https://api.getnetra.ai/telemetry"; + process.env.NETRA_API_KEY = KEY; + const restore = new Config({ headers: { Authorization: "Bearer app-token" } }).setTraceloopEnv(); + restore(); + for (const k of ["TRACELOOP_API_KEY", "TRACELOOP_HEADERS", "TRACELOOP_BASE_URL"]) { + expect(process.env[k]).toBeUndefined(); + } + }); + + it("does not overwrite TRACELOOP_TRACE_CONTENT, and traceContent still applies in-process", () => { + process.env.TRACELOOP_TRACE_CONTENT = "false"; + new Config({ traceContent: true }); + expect(process.env.TRACELOOP_TRACE_CONTENT).toBe("false"); + expect(isTraceContentEnabled()).toBe(true); + new Config({ traceContent: false }); + expect(isTraceContentEnabled()).toBe(false); + }); + + it("sets OTEL_RESOURCE_ATTRIBUTES only until restored", () => { + process.env.OTEL_RESOURCE_ATTRIBUTES = "team=payments"; + const restore = new Config({ appName: "svc", environment: "prod" }).setTraceloopEnv(); + expect(process.env.OTEL_RESOURCE_ATTRIBUTES).toContain("service.name=svc"); + expect(process.env.OTEL_RESOURCE_ATTRIBUTES).toContain("deployment.environment=prod"); + expect(process.env.OTEL_RESOURCE_ATTRIBUTES).toContain("team=payments"); + restore(); + expect(process.env.OTEL_RESOURCE_ATTRIBUTES).toBe("team=payments"); + + delete process.env.OTEL_RESOURCE_ATTRIBUTES; + new Config().setTraceloopEnv()(); + expect(process.env.OTEL_RESOURCE_ATTRIBUTES).toBeUndefined(); + }); + }); + + it("PERF-008: a % in OTEL_RESOURCE_ATTRIBUTES does not throw", () => { + process.env.OTEL_RESOURCE_ATTRIBUTES = "team=R%D,note=50%,ok=a%20b"; + const restore = new Config().setTraceloopEnv(); + const value = process.env.OTEL_RESOURCE_ATTRIBUTES ?? ""; + expect(value).toContain(`team=${encodeURIComponent("R%D")}`); + expect(value).toContain(`ok=${encodeURIComponent("a b")}`); + restore(); + }); +}); diff --git a/src/entity-scope.test.ts b/src/entity-scope.test.ts new file mode 100644 index 0000000..61ee60b --- /dev/null +++ b/src/entity-scope.test.ts @@ -0,0 +1,116 @@ +/** + * JS-SEC-018 / JS-MEM-005 regression tests. + * + * - SEC-018: concurrent decorated calls must keep their own workflow, agent + * and task names; entity scopes are per call, not a shared global stack. + * - MEM-005: spans that never end must not stay reachable from module-level + * state (span registry, root-span map). + */ +import { context, trace } from "@opentelemetry/api"; +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; +import { + BasicTracerProvider, + InMemorySpanExporter, + SimpleSpanProcessor, +} from "@opentelemetry/sdk-trace-base"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; + +import { agent, task, workflow } from "./decorators"; +import { RootSpanProcessor } from "./processors/root-span-processor"; +import { SessionSpanProcessor } from "./processors/session-span-processor"; +import { runWithEntity, SessionManager } from "./session-manager"; + +const named = any>(name: string, fn: T): T => + Object.defineProperty(fn, "name", { value: name }); +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +describe("entity scopes", () => { + const exporter = new InMemorySpanExporter(); + const provider = new BasicTracerProvider({ + spanProcessors: [new SessionSpanProcessor(), new RootSpanProcessor(), new SimpleSpanProcessor(exporter)], + }); + const spans = (re: RegExp) => exporter.getFinishedSpans().filter((s) => re.test(s.name)); + + beforeAll(() => { + context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable()); + trace.setGlobalTracerProvider(provider); + }); + + afterAll(async () => { + trace.disable(); + context.disable(); + await provider.shutdown(); + }); + + beforeEach(() => exporter.reset()); + + it("SEC-018: concurrent requests keep their own workflow, agent and task names", async () => { + const handle = (i: number) => { + const step = task(named(`lookup-${i}`, async () => { await sleep((i * 13) % 25); return i; })); + const ag = agent(named(`agent-${i}`, async () => { await sleep((i * 7) % 20); return step(); })); + return workflow(named(`checkout-${i}`, async () => { await sleep((i * 5) % 15); return ag(); }))(); + }; + await Promise.all(Array.from({ length: 12 }, (_, i) => handle(i))); + + const lookups = spans(/^lookup-/); + expect(lookups).toHaveLength(12); + for (const s of lookups) { + const i = s.name.split("-")[1]; + expect(s.attributes["netra.workflow.name"]).toBe(`checkout-${i}`); + expect(s.attributes["netra.agent.name"]).toBe(`agent-${i}`); + expect(s.attributes["netra.task.name"]).toBe(`lookup-${i}`); + } + }); + + it("SEC-018: a decorated span carries its own entity name, and the caller's scope is untouched", async () => { + await workflow(named("outer", async () => { + await task(named("inner", async () => "ok"))(); + // After the nested task returns, its name is gone from this scope. + expect(SessionManager.getCurrentEntityAttributes()["netra.task.name"]).toBeUndefined(); + expect(SessionManager.getCurrentEntityAttributes()["netra.workflow.name"]).toBe("outer"); + }))(); + expect(SessionManager.getCurrentEntityAttributes()).toEqual({}); + expect(spans(/^outer$/)[0].attributes["netra.workflow.name"]).toBe("outer"); + expect(spans(/^inner$/)[0].attributes["netra.workflow.name"]).toBe("outer"); + }); + + it("SEC-018: a failing call does not leave its name behind for the next one", async () => { + const boom = workflow(named("failing", async () => { throw new Error("x"); })); + await expect(boom()).rejects.toThrow("x"); + await task(named("after-failure", async () => "ok"))(); + expect(spans(/^after-failure$/)[0].attributes["netra.workflow.name"]).toBeUndefined(); + }); + + it("MEM-005: spans are only registered inside a scope and the scope keeps its own registry", () => { + const tracer = provider.getTracer("t"); + const loose = tracer.startSpan("loose"); + SessionManager.registerSpan("loose", loose); + expect(SessionManager.getSpanByName("loose")).toBeUndefined(); + loose.end(); + + runWithEntity("workflow", "w", () => { + const s = tracer.startSpan("scoped"); + SessionManager.registerSpan("scoped", s); + expect(SessionManager.getSpanByName("scoped")).toBe(s); + runWithEntity("task", "t", () => { + expect(SessionManager.getSpanByName("scoped")).toBe(s); + const child = tracer.startSpan("child"); + SessionManager.registerSpan("child", child); + child.end(); + }); + // A nested scope's registrations do not leak into the parent scope. + expect(SessionManager.getSpanByName("child")).toBeUndefined(); + SessionManager.unregisterSpan("scoped", s); + expect(SessionManager.getSpanByName("scoped")).toBeUndefined(); + s.end(); + }); + }); + + it("MEM-005: roots that never end are capped", () => { + const rootSpans = (RootSpanProcessor as any)._rootSpans as Map; + const tracer = provider.getTracer("t"); + for (let i = 0; i < RootSpanProcessor.MAX_TRACKED_ROOTS + 50; i++) tracer.startSpan(`never-ended-${i}`); + expect(rootSpans.size).toBeLessThanOrEqual(RootSpanProcessor.MAX_TRACKED_ROOTS); + rootSpans.clear(); + }); +}); diff --git a/src/exporters/trialAwareOtlpExporter.test.ts b/src/exporters/trialAwareOtlpExporter.test.ts new file mode 100644 index 0000000..62d329a --- /dev/null +++ b/src/exporters/trialAwareOtlpExporter.test.ts @@ -0,0 +1,246 @@ +/** + * JS-MEM-002 / JS-PERF-003 / JS-PERF-006 / JS-MEM-004 regression tests for + * the OTLP exporter: bounded time per batch, retries for transient failures, + * bounded concurrency, and quota detection that ignores plain rate limits. + */ +import * as http from "node:http"; +import { AddressInfo, Socket } from "node:net"; +import { ExportResult, ExportResultCode } from "@opentelemetry/core"; +import type { ReadableSpan } from "@opentelemetry/sdk-trace-base"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { NetraLogger } from "../netraLogger"; +import { isQuotaExceededResponse, TrialAwareOTLPExporter } from "./trialAwareOtlpExporter"; +import { + addBlockedTraceId, + blockedTraceIdCount, + clearBlockedTraceIds, + isTraceIdBlocked, + isTrialBlocked, + setTrialBlocked, +} from "./utils"; + +const NO_SPANS: ReadableSpan[] = []; +const exportOnce = (e: TrialAwareOTLPExporter) => + new Promise((resolve) => e.export(NO_SPANS, resolve)); + +type Handler = (req: http.IncomingMessage, res: http.ServerResponse, n: number) => void; + +async function startServer(handler: Handler) { + let n = 0; + const sockets = new Set(); + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => handler(req, res, ++n)); + }); + server.on("connection", (s) => { sockets.add(s); s.on("close", () => sockets.delete(s)); }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + return { + url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1/traces`, + requests: () => n, + openSockets: () => sockets.size, + close: async () => { + for (const s of sockets) s.destroy(); + await new Promise((r) => server.close(() => r())); + }, + }; +} + +const json = (res: http.ServerResponse, status: number, body: unknown, headers: Record = {}) => { + res.writeHead(status, { "Content-Type": "application/json", ...headers }); + res.end(JSON.stringify(body)); +}; + +describe("TrialAwareOTLPExporter", () => { + beforeEach(() => { + vi.spyOn(NetraLogger, "notice").mockImplementation(() => {}); + setTrialBlocked(false); + }); + afterEach(() => { + vi.restoreAllMocks(); + setTrialBlocked(false); + clearBlockedTraceIds(); + }); + + it("PERF-003/MEM-002: a hung endpoint fails the batch at the deadline and leaves no open socket", async () => { + const server = await startServer(() => { /* never answers */ }); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 400 }); + const t0 = Date.now(); + const result = await exportOnce(exporter); + expect(result.code).toBe(ExportResultCode.FAILED); + expect(Date.now() - t0).toBeLessThan(2000); + await new Promise((r) => setTimeout(r, 50)); + expect(server.openSockets()).toBe(0); + await server.close(); + }); + + it("PERF-006: retries 503 and succeeds", async () => { + const server = await startServer((_q, res, n) => (n < 3 ? json(res, 503, { error: { message: "busy" } }, { "retry-after": "0" }) : json(res, 200, {}))); + vi.spyOn(Math, "random").mockReturnValue(0); // shortest backoff + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 8000 }); + const result = await exportOnce(exporter); + expect(result.code).toBe(ExportResultCode.SUCCESS); + expect(server.requests()).toBe(3); + await server.close(); + }, 10_000); + + it("PERF-006: retries a reset connection", async () => { + const server = await startServer((req, res, n) => (n === 1 ? req.socket.destroy() : json(res, 200, {}))); + vi.spyOn(Math, "random").mockReturnValue(0); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 5000 }); + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.SUCCESS); + expect(server.requests()).toBe(2); + await server.close(); + }); + + it("does not retry a rejected batch (4xx other than 408/429)", async () => { + const server = await startServer((_q, res) => json(res, 401, { error: { message: "bad key" } })); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 5000 }); + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.FAILED); + expect(server.requests()).toBe(1); + await server.close(); + }); + + it("gives up when Retry-After is past the deadline", async () => { + const server = await startServer((_q, res) => json(res, 503, {}, { "retry-after": "120" })); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 2000 }); + const t0 = Date.now(); + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.FAILED); + expect(server.requests()).toBe(1); + expect(Date.now() - t0).toBeLessThan(1500); + await server.close(); + }); + + it("MEM-004: a plain 429 rate limit is retried and does not start a quota block", async () => { + const server = await startServer((_q, res, n) => (n === 1 ? json(res, 429, { error: { code: 429, message: "Too Many Requests" } }, { "retry-after": "0" }) : json(res, 200, {}))); + vi.spyOn(Math, "random").mockReturnValue(0); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 5000 }); + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.SUCCESS); + expect(isTrialBlocked()).toBe(false); + await server.close(); + }); + + it("MEM-004: the backend's QUOTA_EXCEEDED response starts a block and is not retried", async () => { + const body = { error: { code: 429, error: "QuotaExceededException", message: "TRACE usage quota exceeded for your current plan.", errorCode: "QUOTA_EXCEEDED" } }; + const server = await startServer((_q, res) => json(res, 429, body)); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 5000 }); + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.FAILED); + expect(server.requests()).toBe(1); + expect(isTrialBlocked()).toBe(true); + await server.close(); + }); + + it("recognises every quota response shape", () => { + expect(isQuotaExceededResponse(JSON.stringify({ error: { errorCode: "QUOTA_EXCEEDED" } }))).toBe(true); + expect(isQuotaExceededResponse(JSON.stringify({ error: { error: { code: "QUOTA_EXCEEDED" } } }))).toBe(true); + expect(isQuotaExceededResponse(JSON.stringify({ error: { message: "usage quota exceeded" } }))).toBe(true); + expect(isQuotaExceededResponse(JSON.stringify({ error: { code: 429, message: "slow down" } }))).toBe(false); + expect(isQuotaExceededResponse("not json")).toBe(false); + }); + + it("MEM-002: queues a burst beyond the concurrency limit instead of dropping it", async () => { + let active = 0; + let peak = 0; + const server = await startServer((_q, res) => { + active++; peak = Math.max(peak, active); + setTimeout(() => { active--; json(res, 200, {}); }, 30); + }); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 5000, maxConcurrentExports: 4 }); + const results = await Promise.all(Array.from({ length: 25 }, () => exportOnce(exporter))); + expect(results.every((r) => r.code === ExportResultCode.SUCCESS)).toBe(true); + expect(peak).toBeLessThanOrEqual(4); + await server.close(); + }); + + it("MEM-002: drops batches only when the bounded queue is full", async () => { + const server = await startServer(() => { /* never answers */ }); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 600, maxConcurrentExports: 1, maxQueuedExports: 2 }); + const accepted = [exportOnce(exporter), exportOnce(exporter), exportOnce(exporter)]; + const overflow = await exportOnce(exporter); + expect(overflow.code).toBe(ExportResultCode.FAILED); + expect(overflow.error?.message).toMatch(/in flight/); + const t0 = Date.now(); + await Promise.all(accepted); + // Queued batches share the deadline set when they were accepted. + expect(Date.now() - t0).toBeLessThan(1500); + await server.close(); + }); + + it("MEM-002: reads at most 64 KiB of an error body", async () => { + const huge = "x".repeat(2 * 1024 * 1024); + const server = await startServer((_q, res) => { res.writeHead(400); res.end(huge); }); + const notice = vi.mocked(NetraLogger.notice); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 3000 }); + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.FAILED); + expect(String(notice.mock.calls[notice.mock.calls.length - 1]?.[1]).length).toBeLessThan(1000); + await server.close(); + }); + + it("settles when the response is cut off mid-body", async () => { + const server = await startServer((req, res) => { + res.writeHead(200, { "Content-Length": "1000" }); + res.write("partial"); + setTimeout(() => req.socket.destroy(), 20); + }); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 800 }); + const result = await exportOnce(exporter); + expect(result.code).toBe(ExportResultCode.FAILED); + await server.close(); + }); + + it("PERF-003: shutdown() aborts an in-flight export to a hung endpoint", async () => { + const server = await startServer(() => { /* never answers */ }); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 30_000 }); + const pending = exportOnce(exporter); + await new Promise((r) => setTimeout(r, 50)); + const t0 = Date.now(); + await exporter.shutdown(); + expect((await pending).code).toBe(ExportResultCode.FAILED); + expect(Date.now() - t0).toBeLessThan(1000); + await server.close(); + }); + + it("PERF-003: abortPending() aborts in-flight exports and keeps the exporter usable", async () => { + let hang = true; + const server = await startServer((_q, res) => { if (!hang) json(res, 200, {}); }); + const exporter = new TrialAwareOTLPExporter({ url: server.url, timeoutMillis: 30_000 }); + const pending = exportOnce(exporter); + await new Promise((r) => setTimeout(r, 50)); + const t0 = Date.now(); + exporter.abortPending(); + expect((await pending).code).toBe(ExportResultCode.FAILED); + expect(Date.now() - t0).toBeLessThan(500); + hang = false; + expect((await exportOnce(exporter)).code).toBe(ExportResultCode.SUCCESS); + await server.close(); + }); + + it("does not keep a reference to the caller's headers object", () => { + const headers: Record = { "x-api-key": "k" }; + const exporter = new TrialAwareOTLPExporter({ url: "http://127.0.0.1:1/v1/traces", headers }); + headers["x-api-key"] = "changed"; + expect((exporter as any)._headers["x-api-key"]).toBe("k"); + }); +}); + +describe("blocked trace ids (MEM-004)", () => { + afterEach(() => { + vi.useRealTimers(); + clearBlockedTraceIds(); + }); + + it("expire after their TTL", () => { + vi.useFakeTimers(); + addBlockedTraceId("t1"); + expect(isTraceIdBlocked("t1")).toBe(true); + vi.advanceTimersByTime(2 * 900 * 1000 + 1); + expect(isTraceIdBlocked("t1")).toBe(false); + }); + + it("are capped", () => { + for (let i = 0; i < 10_050; i++) addBlockedTraceId(`t${i}`); + expect(blockedTraceIdCount()).toBeLessThanOrEqual(10_000); + expect(isTraceIdBlocked("t0")).toBe(false); + expect(isTraceIdBlocked("t10049")).toBe(true); + }); +}); diff --git a/src/index.host-provider.test.ts b/src/index.host-provider.test.ts new file mode 100644 index 0000000..ea7e2b9 --- /dev/null +++ b/src/index.host-provider.test.ts @@ -0,0 +1,36 @@ +/** + * JS-SEC-011: when the app registered its own TracerProvider first, Netra + * warns and leaves that provider's processors alone. + */ +import { trace } from "@opentelemetry/api"; +import { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base"; +import { afterAll, describe, expect, it, vi } from "vitest"; + +import { Netra } from "./index"; +import { NetraLogger } from "./netraLogger"; + +describe("an app-owned TracerProvider", () => { + afterAll(async () => { + await Netra.shutdown(); + trace.disable(); + vi.restoreAllMocks(); + }, 30_000); + + it("is not modified by Netra.init()", { timeout: 60_000 }, async () => { + const notice = vi.spyOn(NetraLogger, "notice").mockImplementation(() => {}); + const exporter = new InMemorySpanExporter(); + const hostProvider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] }); + trace.setGlobalTracerProvider(hostProvider); + const before = [...(hostProvider as any)._activeSpanProcessor._spanProcessors]; + + await Netra.init({ appName: "host", disableBatch: true, registerShutdownHooks: false }); + + expect((hostProvider as any)._activeSpanProcessor._spanProcessors).toEqual(before); + expect(notice.mock.calls.some(([, m]) => String(m).includes("Another OpenTelemetry TracerProvider"))).toBe(true); + + // The app's own spans keep their attributes untouched. + const span = trace.getTracer("app").startSpan("app-span"); + span.end(); + expect(Object.keys(exporter.getFinishedSpans()[0].attributes)).not.toContain("netra.span.type"); + }); +}); diff --git a/src/index.lifecycle.test.ts b/src/index.lifecycle.test.ts new file mode 100644 index 0000000..6c37269 --- /dev/null +++ b/src/index.lifecycle.test.ts @@ -0,0 +1,53 @@ +/** + * JS-SEC-011 / JS-MEM-008: importing the SDK registers nothing global, and a + * re-init replaces Netra's span processors instead of adding another set. + */ +import * as http from "node:http"; +import { AddressInfo } from "node:net"; +import { propagation, trace } from "@opentelemetry/api"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +import { Netra } from "./index"; +import { NetraLogger } from "./netraLogger"; + +const processors = () => + ((trace.getTracerProvider() as any).getDelegate()._activeSpanProcessor._spanProcessors as any[]); +const netraCount = () => + processors().filter((p) => /SpanIOProcessor|SessionSpanProcessor|LocalFilteringSpanProcessor|RootSpanProcessor/.test(p.constructor.name)).length; + +describe("SDK lifecycle", () => { + let server: http.Server; + beforeAll(async () => { + vi.spyOn(NetraLogger, "notice").mockImplementation(() => {}); + server = http.createServer((req, res) => { req.resume(); req.on("end", () => res.end("{}")); }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + process.env.NETRA_OTLP_ENDPOINT = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + process.env.NETRA_API_KEY = "k"; + }); + afterAll(async () => { + await Netra.shutdown(); + await new Promise((r) => server.close(() => r())); + vi.restoreAllMocks(); + }, 30_000); + + it("SEC-011: importing the SDK does not register a global propagator", () => { + expect(propagation.fields()).toEqual([]); + }); + + it("registers Netra's propagator at init", { timeout: 60_000 }, async () => { + await Netra.init({ appName: "lifecycle", disableBatch: true, registerShutdownHooks: false }); + expect(propagation.fields()).toEqual(expect.arrayContaining(["traceparent", "baggage"])); + }); + + it("MEM-008: re-initializing does not add another set of processors", { timeout: 60_000 }, async () => { + const first = netraCount(); + const total = processors().length; + expect(first).toBeGreaterThan(0); + for (let i = 0; i < 3; i++) { + await Netra.shutdown(); + await Netra.init({ appName: "lifecycle", disableBatch: true, registerShutdownHooks: false }); + } + expect(netraCount()).toBe(first); + expect(processors().length).toBe(total); + }); +}); diff --git a/src/instrumentation/anthropic/wrappers.test.ts b/src/instrumentation/anthropic/wrappers.test.ts index ef57b51..9bf0ac7 100644 --- a/src/instrumentation/anthropic/wrappers.test.ts +++ b/src/instrumentation/anthropic/wrappers.test.ts @@ -165,6 +165,34 @@ describe("Anthropic instrumentation", () => { expect(await collect(data)).toHaveLength(EVENTS.length); }); + // JS-MEM-003: the stream from .withResponse() is the SDK's own object, so + // Netra's span was never ended (or exported) however it was read. + it("create({ stream: true }).withResponse() ends the span when the stream is read", async () => { + const { data } = await client.messages.create({ ...PARAMS, stream: true }).withResponse(); + expect((data as any).controller).toBeInstanceOf(AbortController); + await collect(data); + + const [span] = tracing.spans("anthropic.chat"); + expect(span).toBeDefined(); + expect(span.status.code).toBe(SpanStatusCode.OK); + expect(span.attributes["gen_ai.usage.completion_tokens"]).toBe(2); + }); + + it("create({ stream: true }).withResponse() ends the span when the app breaks out early", async () => { + const { data } = await client.messages.create({ ...PARAMS, stream: true }).withResponse(); + for await (const _ of data) break; + + expect(tracing.spans("anthropic.chat")).toHaveLength(1); + }); + + it("create({ stream: true }).asResponse() ends the span", async () => { + const response = await client.messages.create({ ...PARAMS, stream: true }).asResponse(); + await response.text(); + await settle(); + + expect(tracing.spans("anthropic.chat")).toHaveLength(1); + }); + it("toReadableStream() works and still ends the span", async () => { const stream = await client.messages.create({ ...PARAMS, stream: true }); const reader = stream.toReadableStream().getReader(); diff --git a/src/instrumentation/langgraph/wrappers.test.ts b/src/instrumentation/langgraph/wrappers.test.ts index 7925a6f..355ed1b 100644 --- a/src/instrumentation/langgraph/wrappers.test.ts +++ b/src/instrumentation/langgraph/wrappers.test.ts @@ -120,4 +120,30 @@ describe("LangGraph instrumentation", () => { expect(JSON.stringify(span.attributes)).not.toContain("SECRET"); } }); + + // JS-MEM-003: reading through getReader() or cancelling never iterated the + // stream, so the workflow span was never ended or exported. + it("ends the span when the stream is read through getReader()", async () => { + const stream: any = await graph.stream({ question: "reader" }); + const reader = stream.getReader(); + for (let r = await reader.read(); !r.done; r = await reader.read()) { /* drain */ } + + expect(tracing.spans(WORKFLOW)).toHaveLength(1); + }); + + it("ends the span when a reader is cancelled", async () => { + const stream: any = await graph.stream({ question: "reader-cancel" }); + const reader = stream.getReader(); + await reader.read(); + await reader.cancel(); + + expect(tracing.spans(WORKFLOW)).toHaveLength(1); + }); + + it("ends the span when the stream is cancelled without being read", async () => { + const stream: any = await graph.stream({ question: "cancel" }); + await stream.cancel(); + + expect(tracing.spans(WORKFLOW)).toHaveLength(1); + }); }); diff --git a/src/instrumentation/typeorm/utils.test.ts b/src/instrumentation/typeorm/utils.test.ts new file mode 100644 index 0000000..a993dcb --- /dev/null +++ b/src/instrumentation/typeorm/utils.test.ts @@ -0,0 +1,40 @@ +/** JS-SEC-016: TypeORM query parameter values are opt-in. */ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { setTraceContentEnabled } from "../utils"; +import { setQueryAttributes } from "./utils"; + +function record(sql: string, parameters?: any[]) { + const attrs: Record = {}; + const span: any = { setAttribute: (k: string, v: unknown) => { attrs[k] = v; } }; + setQueryAttributes(span, sql, parameters); + return attrs; +} + +describe("TypeORM query attributes", () => { + afterEach(() => { + vi.unstubAllEnvs(); + setTraceContentEnabled(undefined); + }); + + const SQL = "UPDATE users SET reset_token = $1 WHERE email = $2"; + const PARAMS = ["tok_SECRET", "alice@example.com"]; + + it("records the statement and parameter count, not the values, by default", () => { + setTraceContentEnabled(true); + const attrs = record(SQL, PARAMS); + expect(attrs["db.statement"]).toBe(SQL); + expect(attrs["db.statement.parameters.count"]).toBe(2); + expect(attrs["db.statement.parameters"]).toBeUndefined(); + expect(JSON.stringify(attrs)).not.toMatch(/SECRET|alice/); + }); + + it("records values only with NETRA_TRACE_DB_PARAMETERS=true and content tracing on", () => { + vi.stubEnv("NETRA_TRACE_DB_PARAMETERS", "true"); + setTraceContentEnabled(true); + expect(record(SQL, PARAMS)["db.statement.parameters"]).toBe(JSON.stringify(PARAMS)); + + setTraceContentEnabled(false); + expect(record(SQL, PARAMS)["db.statement.parameters"]).toBeUndefined(); + }); +}); diff --git a/src/processors/span-io-performance.test.ts b/src/processors/span-io-performance.test.ts new file mode 100644 index 0000000..c1b8501 --- /dev/null +++ b/src/processors/span-io-performance.test.ts @@ -0,0 +1,73 @@ +/** + * JS-PERF-002 / JS-MEM-006: a long chat history must not be rebuilt once per + * message, and stored message fields are capped at the attribute size limit. + */ +import { + BasicTracerProvider, + InMemorySpanExporter, + SimpleSpanProcessor, +} from "@opentelemetry/sdk-trace-base"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; + +import { writePromptAttributes } from "../instrumentation/utils"; +import { SerializationSpanProcessor } from "./serialization-span-processor"; +import { SpanIOProcessor } from "./span-io-processor"; + +describe("SpanIOProcessor with long histories", () => { + const exporter = new InMemorySpanExporter(); + const provider = new BasicTracerProvider({ + spanProcessors: [new SerializationSpanProcessor(), new SpanIOProcessor(true), new SimpleSpanProcessor(exporter)], + }); + const tracer = provider.getTracer("t"); + afterAll(() => provider.shutdown()); + beforeEach(() => exporter.reset()); + + const history = (n: number) => + Array.from({ length: n }, (_, i) => ({ role: i % 2 ? "assistant" : "user", content: `message ${i} `.repeat(20) })); + + it("PERF-002: records a 1,000-message prompt without rebuilding it per message", () => { + const stringify = vi.spyOn(JSON, "stringify"); + const span = tracer.startSpan("llm"); + const t0 = performance.now(); + writePromptAttributes(span, history(1000)); + span.end(); + const elapsed = performance.now() - t0; + const calls = stringify.mock.calls.length; + stringify.mockRestore(); + + // One stringify by writePromptAttributes plus a handful in serialization, + // not one rebuild of the whole history per message. + expect(calls).toBeLessThan(50); + expect(elapsed).toBeLessThan(1500); + expect(String(exporter.getFinishedSpans()[0].attributes.input)).toContain("message 0"); + }); + + it("builds input from prompt keys alone, even when the span ends synchronously", () => { + const span = tracer.startSpan("traceloop-style"); + span.setAttribute("gen_ai.prompt.0.role", "user"); + span.setAttribute("gen_ai.prompt.0.content", "hello"); + span.setAttribute("gen_ai.completion.0.role", "assistant"); + span.setAttribute("gen_ai.completion.0.content", "hi"); + span.end(); + const attrs = exporter.getFinishedSpans()[0].attributes; + expect(JSON.parse(String(attrs.input))).toEqual([{ role: "user", content: "hello" }]); + expect(JSON.parse(String(attrs.output))).toEqual([{ role: "assistant", content: "hi" }]); + }); + + it("builds input from prompt keys on the next microtask for long-lived spans", async () => { + const span = tracer.startSpan("async"); + span.setAttribute("gen_ai.prompt.0.role", "user"); + span.setAttribute("gen_ai.prompt.0.content", "later"); + await Promise.resolve(); + expect(String((span as any).attributes.input)).toContain("later"); + span.end(); + }); + + it("MEM-006: an oversized message is cut to the attribute limit", () => { + const span = tracer.startSpan("big"); + span.setAttribute("gen_ai.prompt.0.role", "user"); + span.setAttribute("gen_ai.prompt.0.content", "x".repeat(200_000)); + span.end(); + expect(String(exporter.getFinishedSpans()[0].attributes.input).length).toBeLessThanOrEqual(30_100); + }); +}); diff --git a/src/simulation/download-guard.test.ts b/src/simulation/download-guard.test.ts new file mode 100644 index 0000000..502be2e --- /dev/null +++ b/src/simulation/download-guard.test.ts @@ -0,0 +1,134 @@ +/** JS-SEC-017: simulation attachment URLs are checked before download. */ +import dns from "dns"; +import http from "http"; +import { AddressInfo } from "net"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { assertSafeDownloadUrl, checkDownloadUrlSync, DownloadAgents, isPrivateAddress } from "./download-guard"; + +describe("download guard", () => { + const saved = process.env.NETRA_OTLP_ENDPOINT; + const savedOtel = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + afterEach(() => { + if (saved === undefined) delete process.env.NETRA_OTLP_ENDPOINT; + else process.env.NETRA_OTLP_ENDPOINT = saved; + if (savedOtel === undefined) delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + else process.env.OTEL_EXPORTER_OTLP_ENDPOINT = savedOtel; + vi.restoreAllMocks(); + }); + + it.each([ + ["127.0.0.1", true], ["10.1.2.3", true], ["172.20.0.1", true], ["192.168.1.1", true], + ["169.254.169.254", true], ["100.64.0.1", true], ["0.0.0.0", true], ["::1", true], + ["fd00::1", true], ["fe80::1", true], ["::ffff:10.0.0.1", true], + ["8.8.8.8", false], ["52.95.110.1", false], ["2606:4700::1111", false], + // IPv4 embedded in IPv6, in the hex form new URL() produces + ["::ffff:7f00:1", true], ["::ffff:a9fe:a9fe", true], ["::ffff:808:808", false], + ["0:0:0:0:0:ffff:127.0.0.1", true], ["::127.0.0.1", true], + ["64:ff9b::a9fe:a9fe", true], ["64:ff9b::808:808", false], ["64:ff9b:1::1", true], + ["2002:a00:1::1", true], ["2002:808:808::1", false], + ["2001::1", true], ["2001:db8::1", true], ["fec0::1", true], ["ff02::1", true], + ["fe80::1%eth0", true], + ])("isPrivateAddress(%s) = %s", (ip, expected) => { + expect(isPrivateAddress(ip)).toBe(expected); + }); + + it("accepts https URLs on public hosts", () => { + expect(checkDownloadUrlSync("https://bucket.s3.amazonaws.com/file.png?sig=1").hostname).toBe("bucket.s3.amazonaws.com"); + }); + + it.each([ + "http://bucket.s3.amazonaws.com/file.png", + "file:///etc/passwd", + "https://169.254.169.254/latest/meta-data/", + "https://localhost/file", + "https://10.0.0.5/internal", + "https://[::1]/x", + "https://[::ffff:127.0.0.1]/x", + "https://[::ffff:169.254.169.254]/latest/meta-data/", + "https://[64:ff9b::a9fe:a9fe]/", + "not a url", + ])("refuses %s", (url) => { + expect(() => checkDownloadUrlSync(url)).toThrow(); + }); + + it("allows the configured Netra host, even over http (local or self-hosted)", () => { + process.env.NETRA_OTLP_ENDPOINT = "http://localhost:3002/telemetry"; + expect(() => checkDownloadUrlSync("http://localhost:3002/files/a.png")).not.toThrow(); + expect(() => checkDownloadUrlSync("http://localhost:9999/files/a.png")).not.toThrow(); + }); + + it("refuses a hostname that resolves to a private address", async () => { + delete process.env.NETRA_OTLP_ENDPOINT; + await expect(assertSafeDownloadUrl("https://localtest.me/x")).rejects.toThrow(); + }); + + it("does not trust a non-Netra OTEL_EXPORTER_OTLP_ENDPOINT host", () => { + delete process.env.NETRA_OTLP_ENDPOINT; + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "http://10.0.0.9:4318"; + expect(() => checkDownloadUrlSync("http://10.0.0.9:4318/files/a.png")).toThrow(); + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://api.getnetra.ai/telemetry"; + expect(() => checkDownloadUrlSync("https://api.getnetra.ai/files/a.png")).not.toThrow(); + }); + + describe("DownloadAgents", () => { + /** Resolve the given hostnames to 127.0.0.1; leave every other lookup alone. */ + function resolveToLoopback(...hosts: string[]) { + const original = dns.lookup; + vi.spyOn(dns, "lookup").mockImplementation(((hostname: string, options: any, callback: any) => { + if (!hosts.includes(hostname)) return (original as any)(hostname, options, callback); + const address = { address: "127.0.0.1", family: 4 }; + if (options?.all) callback(null, [address]); + else callback(null, address.address, address.family); + }) as any); + } + + async function withServer(fn: (port: number) => Promise) { + const server = http.createServer((_req, res) => res.end("ok")); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + await fn((server.address() as AddressInfo).port); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } + } + + function get(url: string, agent: http.Agent): Promise { + return new Promise((resolve, reject) => { + http.get(url, { agent }, (res) => { + let body = ""; + res.on("data", (c) => (body += c)); + res.on("end", () => resolve(body)); + }).on("error", reject); + }); + } + + it("refuses to connect when a download host resolves to a private address (rebinding, redirects)", async () => { + resolveToLoopback("files.example.test", "redirect.example.test"); + await withServer(async (port) => { + const agents = new DownloadAgents(new URL("https://files.example.test/a.png")); + try { + await expect(get(`http://files.example.test:${port}/`, agents.httpAgent)).rejects.toThrow(/private address/); + // A redirect target becomes a download host once beforeRedirect adds it. + agents.addTarget(new URL("https://redirect.example.test/b.png")); + await expect(get(`http://redirect.example.test:${port}/`, agents.httpAgent)).rejects.toThrow(/private address/); + } finally { + agents.destroy(); + } + }); + }); + + it("resolves other hosts (such as a proxy) normally", async () => { + resolveToLoopback("proxy.example.test"); + await withServer(async (port) => { + const agents = new DownloadAgents(new URL("https://files.example.test/a.png")); + try { + await expect(get(`http://proxy.example.test:${port}/`, agents.httpAgent)).resolves.toBe("ok"); + } finally { + agents.destroy(); + } + }); + }); + }); +}); diff --git a/src/simulation/download-guard.ts b/src/simulation/download-guard.ts index 4a4fa0d..6401183 100644 --- a/src/simulation/download-guard.ts +++ b/src/simulation/download-guard.ts @@ -5,8 +5,11 @@ * returned was fetched from the app's network, including internal services and * cloud metadata endpoints, with no size limit and up to 21 redirects. */ -import { promises as dns } from "dns"; +import dns, { promises as dnsPromises, LookupAddress } from "dns"; +import http from "http"; +import https from "https"; import { isIP } from "net"; +import { isNetraHost } from "../config"; const DEFAULT_MAX_FILE_BYTES = 50 * 1024 * 1024; export const MAX_DOWNLOAD_REDIRECTS = 3; @@ -34,35 +37,121 @@ const PRIVATE_V4: Array<[string, number]> = [ ["169.254.0.0", 16], // link-local, cloud metadata ["172.16.0.0", 12], ["192.0.0.0", 24], + ["192.0.2.0", 24], // documentation ["192.168.0.0", 16], ["198.18.0.0", 15], + ["198.51.100.0", 24], // documentation + ["203.0.113.0", 24], // documentation ["224.0.0.0", 4], ["240.0.0.0", 4], ]; -/** True for loopback, private, link-local, CGNAT, multicast and reserved addresses. */ +/** + * The 16 bytes of an IPv6 address, or undefined if it is not one. Parsing to + * bytes, instead of matching text, catches every spelling of an address: + * `new URL()` rewrites `[::ffff:127.0.0.1]` as `[::ffff:7f00:1]`, which a + * dotted-quad pattern never matched. + */ +function parseIPv6(ip: string): number[] | undefined { + if (isIP(ip) !== 6) return undefined; + let text = ip.toLowerCase(); + const zone = text.indexOf("%"); + if (zone !== -1) text = text.slice(0, zone); + + // A trailing dotted IPv4 part becomes two hex groups. + const lastColon = text.lastIndexOf(":"); + const tail = text.slice(lastColon + 1); + if (tail.includes(".")) { + const v4 = ipv4ToInt(tail); + text = `${text.slice(0, lastColon + 1)}${(v4 >>> 16).toString(16)}:${(v4 & 0xffff).toString(16)}`; + } + + const [head, rest] = text.split("::"); + const headGroups = head ? head.split(":") : []; + const restGroups = rest ? rest.split(":") : []; + const fill = text.includes("::") ? 8 - headGroups.length - restGroups.length : 0; + const groups = [...headGroups, ...Array(fill).fill("0"), ...restGroups]; + if (groups.length !== 8) return undefined; + + const bytes: number[] = []; + for (const group of groups) { + const value = parseInt(group, 16); + bytes.push(value >> 8, value & 0xff); + } + return bytes; +} + +function startsWith(bytes: number[], prefix: number[]): boolean { + return prefix.every((b, i) => bytes[i] === b); +} + +function v4FromBytes(bytes: number[], offset: number): string { + return bytes.slice(offset, offset + 4).join("."); +} + +function isPrivateIPv6(bytes: number[]): boolean { + const allZeroUpTo = (n: number) => bytes.slice(0, n).every((b) => b === 0); + + // Forms that carry an IPv4 address: judge the embedded address. + // ::ffff:a.b.c.d (IPv4-mapped) + if (allZeroUpTo(10) && bytes[10] === 0xff && bytes[11] === 0xff) { + return isPrivateAddress(v4FromBytes(bytes, 12)); + } + // ::a.b.c.d (deprecated IPv4-compatible), and :: / ::1 + if (allZeroUpTo(12)) { + return true; + } + // 64:ff9b::/96 (NAT64) and 64:ff9b:1::/48 (local-use NAT64) + if (startsWith(bytes, [0x00, 0x64, 0xff, 0x9b])) { + const wellKnown = bytes.slice(4, 12).every((b) => b === 0); + return wellKnown ? isPrivateAddress(v4FromBytes(bytes, 12)) : true; + } + // 2002::/16 (6to4): IPv4 address in bytes 2-5 + if (bytes[0] === 0x20 && bytes[1] === 0x02) { + return isPrivateAddress(v4FromBytes(bytes, 2)); + } + // 2001::/32 (Teredo): the server and client addresses are obfuscated + if (startsWith(bytes, [0x20, 0x01, 0x00, 0x00])) return true; + // 2001:db8::/32 (documentation) + if (startsWith(bytes, [0x20, 0x01, 0x0d, 0xb8])) return true; + // 100::/64 (discard) + if (startsWith(bytes, [0x01, 0x00, 0, 0, 0, 0, 0, 0])) return true; + + return ( + (bytes[0] & 0xfe) === 0xfc || // fc00::/7 unique local + (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80) || // fe80::/10 link-local + (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0xc0) || // fec0::/10 site-local (deprecated) + bytes[0] === 0xff // ff00::/8 multicast + ); +} + +/** + * True for loopback, private, link-local, CGNAT, multicast, documentation and + * reserved addresses, including IPv4 addresses embedded in IPv6 (mapped, + * compatible, NAT64, 6to4) in any spelling. + */ export function isPrivateAddress(ip: string): boolean { const family = isIP(ip); if (family === 4) return PRIVATE_V4.some(([base, bits]) => inV4Range(ip, base, bits)); if (family === 6) { - const v6 = ip.toLowerCase(); - const mapped = v6.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); - if (mapped) return isPrivateAddress(mapped[1]); - return ( - v6 === "::" || - v6 === "::1" || - v6.startsWith("fc") || - v6.startsWith("fd") || // unique local - /^fe[89ab]/.test(v6) || // link-local - v6.startsWith("ff") // multicast - ); + const bytes = parseIPv6(ip); + // Unparseable: refuse rather than guess. + return bytes ? isPrivateIPv6(bytes) : true; } return false; } -/** Host of the configured Netra endpoint, which is always allowed. */ -function netraHost(): string | undefined { - const endpoint = process.env.NETRA_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT; +/** + * Host of the Netra endpoint, which is always allowed (a local or self-hosted + * Netra may use http and a private address). NETRA_OTLP_ENDPOINT is explicit + * Netra configuration and always counts. OTEL_EXPORTER_OTLP_ENDPOINT often + * points at another vendor or a shared collector, so it counts only when it is + * a Netra host (as for the API key, JS-SEC-006). + */ +function trustedNetraHost(): string | undefined { + const netra = process.env.NETRA_OTLP_ENDPOINT; + const otel = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + const endpoint = netra || (otel && isNetraHost(otel) ? otel : undefined); if (!endpoint) return undefined; try { return new URL(endpoint.trim()).hostname.toLowerCase(); @@ -71,6 +160,10 @@ function netraHost(): string | undefined { } } +function hostOf(url: URL): string { + return url.hostname.replace(/^\[|\]$/g, "").toLowerCase(); +} + /** * Synchronous checks on a URL: scheme and literal host. Used for the first * URL and for every redirect target. @@ -82,8 +175,8 @@ export function checkDownloadUrlSync(raw: string): URL { } catch { throw new Error("download URL is not a valid URL"); } - const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase(); - const trusted = host === netraHost(); + const host = hostOf(url); + const trusted = host === trustedNetraHost(); if (url.protocol !== "https:" && !(url.protocol === "http:" && trusted)) { throw new Error(`download URL must use https (got ${url.protocol})`); } @@ -99,12 +192,69 @@ export function checkDownloadUrlSync(raw: string): URL { */ export async function assertSafeDownloadUrl(raw: string): Promise { const url = checkDownloadUrlSync(raw); - const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase(); - if (host === netraHost() || isIP(host)) return url; - const addresses = await dns.lookup(host, { all: true }); + const host = hostOf(url); + if (host === trustedNetraHost() || isIP(host)) return url; + const addresses = await dnsPromises.lookup(host, { all: true }); const blocked = addresses.find((a) => isPrivateAddress(a.address)); if (blocked) { throw new Error(`download URL host ${host} resolves to a private address (${blocked.address})`); } return url; } + +type LookupCallback = ( + err: NodeJS.ErrnoException | null, + address: string | LookupAddress[], + family?: number, +) => void; + +/** + * HTTP agents for one download whose DNS lookup refuses private addresses for + * the download's own hosts (the first URL and each redirect target, added with + * `addTarget`). The check runs on the addresses the socket actually connects + * to, so a redirect to a hostname that resolves to a private address, or a + * DNS answer that changes between a check and the connection (rebinding), is + * refused. Other hosts, such as an HTTP proxy from the environment, resolve + * normally. IP literals never reach `lookup`; `checkDownloadUrlSync` covers them. + */ +export class DownloadAgents { + readonly httpAgent: http.Agent; + readonly httpsAgent: https.Agent; + private readonly targets = new Set(); + + constructor(url: URL) { + this.addTarget(url); + const lookup = this.lookup.bind(this) as any; + this.httpAgent = new http.Agent({ lookup }); + this.httpsAgent = new https.Agent({ lookup }); + } + + addTarget(url: URL): void { + this.targets.add(hostOf(url)); + } + + destroy(): void { + this.httpAgent.destroy(); + this.httpsAgent.destroy(); + } + + private lookup(hostname: string, options: dns.LookupOptions, callback: LookupCallback): void { + const host = hostname.replace(/^\[|\]$/g, "").toLowerCase(); + dns.lookup(hostname, { ...options, all: true }, (err, addresses) => { + if (err) return callback(err, []); + if (this.targets.has(host) && host !== trustedNetraHost()) { + const blocked = addresses.find((a) => isPrivateAddress(a.address)); + if (blocked) { + return callback( + new Error(`download URL host ${host} resolves to a private address (${blocked.address})`), + [], + ); + } + } + if (options.all) return callback(null, addresses); + const first = addresses[0]; + if (!first) return callback(new Error(`no address found for ${host}`), []); + callback(null, first.address, first.family); + }); + } +} diff --git a/src/simulation/utils.ts b/src/simulation/utils.ts index 73ddc9b..13f7b51 100644 --- a/src/simulation/utils.ts +++ b/src/simulation/utils.ts @@ -4,6 +4,7 @@ import { NetraLogger } from "../netraLogger"; import { assertSafeDownloadUrl, checkDownloadUrlSync, + DownloadAgents, MAX_DOWNLOAD_REDIRECTS, maxDownloadBytes, } from "./download-guard"; @@ -95,21 +96,35 @@ async function _downloadSingleFile( signal?: AbortSignal, ): Promise { try { - // Scheme, host and resolved addresses are checked first, and again - // for every redirect; size and redirect count are bounded (JS-SEC-017). - await assertSafeDownloadUrl(fileData.downloadUrl); + // Scheme, host and resolved addresses are checked first. The agents + // check the addresses actually connected to, for the first request + // and every redirect, so a redirect to a hostname with a private + // address, or a DNS answer that changes after this check (rebinding), + // is refused too. Size and redirect count are bounded (JS-SEC-017). + // The pre-check still matters behind an HTTP proxy, where axios + // tunnels through its own agent and the proxy resolves the host. + const url = await assertSafeDownloadUrl(fileData.downloadUrl); const maxBytes = maxDownloadBytes(); - const response = await axios.get(fileData.downloadUrl, { - responseType: "arraybuffer", - timeout: timeoutMs, - signal, - maxRedirects: MAX_DOWNLOAD_REDIRECTS, - maxContentLength: maxBytes, - maxBodyLength: maxBytes, - beforeRedirect: (options: Record) => { - checkDownloadUrlSync(String(options.href ?? `${options.protocol}//${options.hostname}${options.path ?? ""}`)); - }, - }); + const agents = new DownloadAgents(url); + let response; + try { + response = await axios.get(fileData.downloadUrl, { + responseType: "arraybuffer", + timeout: timeoutMs, + signal, + maxRedirects: MAX_DOWNLOAD_REDIRECTS, + maxContentLength: maxBytes, + maxBodyLength: maxBytes, + httpAgent: agents.httpAgent, + httpsAgent: agents.httpsAgent, + beforeRedirect: (options: Record) => { + const next = checkDownloadUrlSync(String(options.href ?? `${options.protocol}//${options.hostname}${options.path ?? ""}`)); + agents.addTarget(next); + }, + }); + } finally { + agents.destroy(); + } const encoded = Buffer.from(response.data).toString("base64"); return { diff --git a/src/utils/response-handler.test.ts b/src/utils/response-handler.test.ts index 39768af..79116c2 100644 --- a/src/utils/response-handler.test.ts +++ b/src/utils/response-handler.test.ts @@ -1,7 +1,9 @@ +import v8 from "v8"; +import vm from "vm"; import { describe, expect, it, vi } from "vitest"; import { captureUnhandledRejections, settle } from "../__fixtures__/llm-test-utils"; -import { wrapPromise } from "./response-handler"; +import { wrapAsyncIterable, wrapPromise } from "./response-handler"; function callbacks() { return { @@ -42,3 +44,96 @@ describe("wrapPromise with preserveOriginal", () => { await expect(wrapped).rejects.toBe(failure); }); }); + +/** + * JS-MEM-003: the span of a stream the app drops is ended once the stream is + * garbage-collected. A stream that is still being read must never be + * finalized that way, however the app holds it. + */ +describe("wrapAsyncIterable garbage-collection finalizer", () => { + v8.setFlagsFromString("--expose-gc"); + const gc = vm.runInNewContext("gc") as () => void; + const tick = (ms = 5) => new Promise((resolve) => setTimeout(resolve, ms)); + + async function* chunks(n = 4) { + for (let i = 0; i < n; i++) { + await tick(); + yield i; + } + } + + function readableChunks(n = 4) { + let i = 0; + return new ReadableStream({ + async pull(controller) { + await tick(); + if (i < n) controller.enqueue(i++); + else controller.close(); + }, + }); + } + + /** Records chunk and finalize order. */ + function recorder() { + const events: string[] = []; + const cb = { + withContext: (fn: () => T) => fn(), + onChunk: (c: unknown) => events.push(`chunk ${c}`), + onError: vi.fn(), + onSuccess: vi.fn(), + finalize: (status: string) => events.push(`finalize ${status}`), + }; + return { events, cb }; + } + + async function collect() { + for (let i = 0; i < 3; i++) { + gc(); + await tick(); + } + } + + const expected = ["chunk 0", "chunk 1", "chunk 2", "chunk 3", "finalize ok", "done"]; + + it("keeps the span open while for-await holds only the iterator", async () => { + const { events, cb } = recorder(); + // The wrapped stream is a temporary: only the loop's iterator lives on. + for await (const _ of wrapAsyncIterable(chunks(), cb)) await collect(); + events.push("done"); + expect(events).toEqual(expected); + }); + + it("keeps the span open while the app holds only a reader", async () => { + const { events, cb } = recorder(); + const reader = wrapAsyncIterable(readableChunks() as any, cb).getReader(); + for (;;) { + await collect(); + if ((await reader.read()).done) break; + } + events.push("done"); + expect(events).toEqual(expected); + }); + + it("keeps the span open while the app reads a stream from .withResponse()", async () => { + const { events, cb } = recorder(); + const stream = chunks(); + // An SDK promise whose withResponse() returns the same (cached) stream. + const sdkPromise = Object.assign(Promise.resolve(stream), { + withResponse: async () => ({ data: stream, response: {} }), + }); + const { data } = await wrapPromise(sdkPromise, cb, { preserveOriginal: sdkPromise }).withResponse(); + for await (const _ of data) await collect(); + events.push("done"); + expect(events).toEqual(expected); + }); + + it("still ends the span of a stream the app drops", async () => { + const { events, cb } = recorder(); + (() => { + wrapAsyncIterable(chunks(), cb); + })(); + for (let i = 0; i < 20 && events.length === 0; i++) await collect(); + expect(events).toEqual(["finalize ok"]); + }); +}); + diff --git a/src/utils/response-handler.ts b/src/utils/response-handler.ts index dd62dd9..828f500 100644 --- a/src/utils/response-handler.ts +++ b/src/utils/response-handler.ts @@ -84,6 +84,17 @@ const abandonedStreams: FinalizationRegistryLike<() => void> | undefined = }) : undefined; +const NETRA_STREAM_OWNER = Symbol("netra.streamOwner"); + +/** Make `holder` keep `target` reachable (a hidden, non-enumerable reference). */ +function keepAlive(holder: object, target: object): void { + try { + Object.defineProperty(holder, NETRA_STREAM_OWNER, { value: target }); + } catch { + // A frozen or non-extensible holder: nothing more can be done. + } +} + /** * Wrap an async iterable with lifecycle callbacks. * Returns a Proxy that preserves the original object's full interface @@ -126,7 +137,13 @@ export function wrapAsyncIterable( } }; - function createWrappedIterator(): AsyncIterator { + /** + * `owner` is the wrapped stream the iterator came from. The iterator keeps + * a strong reference to it: `for await (const c of await create(...))` + * holds only the iterator, and without this reference the stream could be + * garbage-collected mid-loop, ending its span after the first chunk. + */ + function createWrappedIterator(owner?: object): AsyncIterator { const iterator = source[Symbol.asyncIterator](); let done = false; @@ -136,7 +153,7 @@ export function wrapAsyncIterable( finalizeOnce(status); }; - return { + const wrapped: AsyncIterator = { async next(value?: any) { try { const result = await callbacks.withContext(() => iterator.next(value)); @@ -196,6 +213,8 @@ export function wrapAsyncIterable( } }, }; + if (owner) keepAlive(wrapped, owner); + return wrapped; } let directIterator: AsyncIterator | null = null; @@ -205,9 +224,12 @@ export function wrapAsyncIterable( * read with getReader() or cancelled without ever iterating; observe those * paths too so the span still ends (JS-MEM-003). */ - const wrapReader = (reader: any): any => { + const wrapReader = (reader: any, owner: object): any => { if (!reader || typeof reader.read !== "function") return reader; + // The handler holds the stream it came from, so an app that keeps only + // the reader does not let the stream (and its span) be finalized early. return new Proxy(reader, { + owner, get(r, prop) { const value = r[prop]; if (prop === "read" && typeof value === "function") { @@ -235,16 +257,20 @@ export function wrapAsyncIterable( } return typeof value === "function" ? value.bind(r) : value; }, - }); + } as ProxyHandler & { owner: object }); }; + // `proxy` must stay out of every closure created in this function: the + // registry's held callback closes over this scope, and a reference to the + // proxy from there would keep it alive forever. The handler reaches it as + // `receiver` instead. const proxy = new Proxy(source, { get(target, prop, receiver) { if (prop === Symbol.asyncIterator) { - return () => createWrappedIterator(); + return () => createWrappedIterator(receiver); } if (prop === "getReader" && typeof (target as any).getReader === "function") { - return (...args: any[]) => wrapReader((target as any).getReader(...args)); + return (...args: any[]) => wrapReader((target as any).getReader(...args), receiver); } if (prop === "cancel" && typeof (target as any).cancel === "function") { return async (...args: any[]) => { @@ -370,11 +396,16 @@ export function wrapPromise( } } + // The stream the promise resolved to, and its wrapper, for `.withResponse()`. + let rawStream: unknown; + let wrappedStream: unknown; const instrumentedPromise = (async () => { try { const value = await promise; if (isAsyncIterable(value)) { - return wrapAsyncIterable(value as any, { ...callbacks, finalize: safeFinalize }); + rawStream = value; + wrappedStream = wrapAsyncIterable(value as any, { ...callbacks, finalize: safeFinalize }); + return wrappedStream; } safeOnSuccess(value); safeFinalize("ok"); @@ -410,7 +441,19 @@ export function wrapPromise( return async (...args: any[]) => { const result = await original.withResponse(...args); if (result && isAsyncIterable(result.data)) { - return { ...result, data: wrapAsyncIterable(result.data, { ...callbacks, finalize: safeFinalize }) }; + // The SDK caches its parsed result, so `data` is the stream this + // promise already wrapped. Hand back that one wrapper: a second + // wrapper would leave the first unreferenced, and its + // garbage-collection finalizer would end the span mid-read. + await instrumentedPromise.catch(() => {}); + if (result.data === rawStream && wrappedStream) { + return { ...result, data: wrappedStream }; + } + const data = wrapAsyncIterable(result.data, { ...callbacks, finalize: safeFinalize }); + // A different stream object: keep the unused first wrapper alive as + // long as this one, so its finalizer cannot end the span early. + if (wrappedStream && typeof wrappedStream === "object") keepAlive(data, wrappedStream); + return { ...result, data }; } return result; };