From f2f228640af3649396c22f1659823dcd755451be Mon Sep 17 00:00:00 2001 From: Saba Siddique Date: Sat, 21 Nov 2026 00:03:27 +0500 Subject: [PATCH 1/2] Harden the trace exporter's file and endpoint handling Part of #283 Refs #274 Signed-off-by: Saba Siddique --- .../agt/packages/guardian/README.md | 58 +- .../packages/guardian/src/audit-to-otlp.ts | 4 +- .../packages/guardian/src/loopback-proxy.ts | 48 +- .../agt/packages/guardian/src/main.ts | 2 + .../agt/packages/guardian/src/otel-mapping.ts | 8 + .../guardian/src/otel-trace-exporter.ts | 88 ++- .../guardian/src/otlp-file-exporter.ts | 114 ++- .../agt/packages/guardian/src/server.ts | 5 + .../agt/packages/guardian/test/main.test.ts | 61 ++ .../guardian/test/otel-trace-exporter.test.ts | 695 +++++++++++++++++- .../agt/test/audit-to-otlp.test.ts | 35 +- 11 files changed, 1085 insertions(+), 33 deletions(-) diff --git a/reference-implementations/agt/packages/guardian/README.md b/reference-implementations/agt/packages/guardian/README.md index 3a070f0e3..f79a7d384 100644 --- a/reference-implementations/agt/packages/guardian/README.md +++ b/reference-implementations/agt/packages/guardian/README.md @@ -31,6 +31,7 @@ It constructs the AGT runtime once, at startup, against `policy/manifest.yaml`, | `ACS_SESSION_CONTEXT_LOG` | `.acs/session-context.jsonl` | Where each session's hash chain is written | | `ACS_OTEL_FILE` | unset | Writes one OpenTelemetry span per decided step as OTLP/JSON, one export request per line. Unset means no trace export | | `ACS_OTEL_ENDPOINT` | unset | Sends the same spans to an OTLP/HTTP collector, for example `http://127.0.0.1:4318/v1/traces` | +| `ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT` | unset | Set to `1` to let `ACS_OTEL_ENDPOINT` be plain `http://` to a host that is not loopback. The spans then cross the network unencrypted. See [Send traces to another host](#send-traces-to-another-host) | To see a decision without an agent client, pipe a hook payload into the Claude Code shim while the Guardian runs. The [tree README](../../README.md#drive-one-hook-by-hand) shows the command and its output. @@ -62,7 +63,7 @@ Each step the Guardian trusted becomes one span, named by [`trace/otel-mapping.j Every span also carries `acs.session.id`, and `acs.request_id` whenever the envelope has one, so a session can be rebuilt from the trace alone. When an argument or output carries a Provenance object, the span carries `acs.provenance.origin` as an array, one element per Provenance object in wire order. `acs.provenance.source_id` is the matching array, with `""` where an object has no `source_id`, and it is left out when no object has one. Both stop at 64 objects. `acs.provenance.lineage_depth` is not emitted: `provenance.json` defines no such field. -Every string attribute is cut at 4096 characters, a long `acs.reasoning` included, so one large request cannot grow the export queue without bound. The sampler and span limits are set in code, so `OTEL_TRACES_*`, `OTEL_SPAN_*`, `OTEL_ATTRIBUTE_*` and `OTEL_BSP_*` variables in the environment do not change what is exported, and the endpoint output is never compressed. `OTEL_EXPORTER_OTLP_*HEADERS` still add headers to the endpoint's requests, and a loopback endpoint is added to `NO_PROXY` so an `HTTP_PROXY` cannot route it. +Every string attribute is cut at 4096 characters, a long `acs.reasoning` included, so one large request cannot grow the export queue without bound. The sampler and span limits are set in code, so `OTEL_TRACES_*`, `OTEL_SPAN_*`, `OTEL_ATTRIBUTE_*` and `OTEL_BSP_*` variables in the environment do not change what is exported, and the endpoint output is never compressed. `OTEL_EXPORTER_OTLP_*HEADERS` still add headers to the endpoint's requests, and a loopback endpoint is added to `NO_PROXY` so an `HTTP_PROXY` cannot route it. Under the plain `http://` opt-in, either headers variable stops the endpoint from being built: see [Send traces to another host](#send-traces-to-another-host). The decision rides on the span as an `acs.decision` event. The event always carries `acs.decision`, carries `acs.reasoning` when the response has one, and carries `acs.reason_codes`, `acs.policy.ids`, `acs.policy.versions`, `acs.policy.rule_ids`, `acs.cited_provenance_ids` and `acs.chain_hash` only when the response carries them. `acs.evaluator` appears when the Guardian's response carries `metadata.evaluator`. This Guardian doesn't send it. @@ -70,6 +71,8 @@ This Guardian does not send `chain_hash`, `cited_provenance_ids`, or `policy_ver A step that got no decision is recorded as an `acs.decision.failure` event on the same span, with `acs.failure.class`, `acs.failure.posture` and `acs.failure.reported_by`, plus the error code, the timeout, the elapsed time and the request size when known. The Guardian emits it for an error it answered instead of a decision, for a decision it finished after the negotiated timeout, and for a step still open when it shut down. It carries the error code but never the error text, because that text can quote the request. The converter below produces the same event, reported by the observed agent, from the host adapter's audit log. +A step still open at shutdown has class `timeout` when it has been open for longer than its timeout, because the host has already applied its posture, and `other` when it hasn't. The elapsed time is rounded up to a whole millisecond, so a late step never shows `acs.failure.elapsed_ms` equal to `acs.failure.timeout_ms`. + A request the Guardian cannot vouch for is recorded apart from the steps it governed, as a `guardian.rejected_request` span. Such a request can carry any session and request id, a genuine request's included. So the span carries no `acs.session.id`, `acs.request_id`, step attribute or `acs.decision` event. It records the ids the request claimed as `guardian.rejected.claimed_session_id` and `guardian.rejected.claimed_request_id`, with `guardian.rejected.reason` and, for an error answer, `guardian.rejected.error_code`. These names belong to this Guardian, not to the ACS mapping. The reasons are `envelope_invalid`, for an envelope that fails validation, and `signature_invalid`, `replay_detected` or `timestamp_out_of_window`, for a step answered with that error by whichever check produced it. The last is `guardian_fault`, for a request the Guardian could not check at all, a missing schema directory for example. The host got an error for that one, so its span also carries an `acs.decision.failure` with class `guardian_error`. This Guardian verifies no signature, replay or timestamp, so a forged or replayed request that passes the schema is still recorded as a step. @@ -99,6 +102,49 @@ Each processor sends a batch about every five seconds. At shutdown, the exporter Use synthetic sessions for lab runs. The envelope log holds raw envelopes before any redaction, a span's `acs.reasoning` repeats the Guardian's explanation of them, and `acs.provenance.source_id` goes out as the host sent it: by `provenance.json` it can be a URL or a file path, so a signed URL or a home-directory path would too. +### What the file output refuses + +The trace file holds reasoning text and provenance ids, so the Guardian checks `ACS_OTEL_FILE` every time it appends a batch. It does not check when it starts, so a refusal first shows with the first batch, about five seconds after the first decision. It opens the path without following a symlink and judges the file it opened, not the name. It refuses: + +- a symlink at the path, or a parent directory that is a symlink; +- a file with a second hard link, or anything that is not a regular file, such as a FIFO; +- a file, or a parent directory, that the user running the Guardian does not own; +- a parent directory that every user can write to, such as `/tmp`. Put the file in a directory of its own, as `.acs/` is. + +An existing file with a wider mode is not refused. The Guardian sets it to `0600` and appends. A file it creates is `0600`, and a directory it creates is `0700`. + +Only the immediate parent directory is checked, and it is checked by name. A directory swapped for a symlink between that check and the open is followed, and the file's own checks still apply to what was opened. + +A refusal turns the file output off and prints the reason once (see [Troubleshooting](#troubleshooting)). The endpoint output keeps running. The converter below writes through the same code, so it refuses the same paths. + +On Windows the Guardian still refuses a symlink and a second hard link, but it checks no owner and sets no mode, because Windows controls access with ACLs. It also has to look for the symlink before it opens the file, so a link put there in between is followed. + +### Send traces to another host + +Use an `https://` endpoint to send spans to another host. A span carries the Guardian's reasoning text and provenance ids, and plain `http://` lets anyone on the network path read them. + +Two kinds of endpoint work with no extra setting: `https://` to any host, and `http://` to a loopback host. Loopback means an address in `127.0.0.0/8`, `::1`, the same IPv4 range written as `::ffff:127.0.0.1`, or the name `localhost` and no other name. [`otel-collector.yaml`](../../otel-collector.yaml) listens on loopback with no TLS, so it is for a collector on the same machine. + +Plain `http://` to any other host is refused. The Guardian builds no endpoint output, keeps the file output if you set one, and prints: + +``` +otel trace export to http://10.0.0.1:4318/v1/traces disabled after failure: refusing plain http to 10.0.0.1, which is not a loopback host: spans would cross the network unencrypted. Use an https endpoint, or set ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 to send them anyway. +``` + +`ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1` sends them over plain `http://` anyway. Any other value is ignored. Set it only when you trust every hop between the Guardian and the collector. With it set, the Guardian builds the output and prints a warning when it starts: + +``` +otel trace export to http://10.0.0.1:4318/v1/traces: ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 is set, so spans go to 10.0.0.1 over plain http, unencrypted. Use an https endpoint unless every hop to that host is trusted. +``` + +`OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_EXPORTER_OTLP_TRACES_HEADERS` add headers to every request the endpoint output sends, which is how a collector is usually given its credential. Over plain `http://` that credential would cross the network unencrypted too. So when either variable is set to a non-empty value, the opt-in is refused, and the Guardian names the variable: + +``` +otel trace export to http://10.0.0.1:4318/v1/traces disabled after failure: refusing plain http to 10.0.0.1 even with ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1: OTEL_EXPORTER_OTLP_HEADERS is set, and the headers it adds can carry credentials, which would cross the network unencrypted. Use an https endpoint, or unset OTEL_EXPORTER_OTLP_HEADERS. +``` + +A user name or password in the endpoint URL is refused under the opt-in for the same reason: the HTTP client sends it as an `Authorization` header. Over `https://`, and to a loopback host, the headers and the URL's credential are sent as before. + ### Convert the host audit log The failures only the host sees, a Guardian it could not reach or one that answered too late, are in the host adapter's audit log, not in the Guardian's file. `audit-to-otlp.ts` turns that log into the same OTLP/JSON shape: one span per posture entry, with an `acs.decision.failure` event whose `acs.failure.reported_by` is `observed_agent`. Each span carries the same `acs.session.id` and `acs.request_id` as the Guardian's span for that request, so the two files join. It does not carry `gen_ai.tool.name`, because the audit log does not record the tool. @@ -135,6 +181,10 @@ That command regenerates it. `test/sample-trace.test.ts` checks the sample again These are the messages export can print, with what each one means. None of them changes a decision. - `otel trace export to disabled after failure: ` on the Guardian's stderr. That output failed its first write or send and is off until the Guardian restarts. The other output keeps running. For an endpoint, the usual cause is a collector that wasn't running yet or was restarted: stop the Guardian, start the collector, then start the Guardian again. +- `otel trace export to disabled after failure: refusing to write : `. The file output failed one of its checks, and no span was written to that path. The reason names what to fix: `it is a symbolic link`, `it has more than one hard link`, `it is not a regular file`, `it is not owned by the user running this process`, or the same about `its directory `, which can also be `writable by every user`. [What the file output refuses](#what-the-file-output-refuses) lists the rules. +- `otel trace export to disabled after failure: refusing plain http to , which is not a loopback host: ...` at startup. The endpoint is plain `http://` to another host, so no endpoint output was built. Use an `https://` endpoint, or read [Send traces to another host](#send-traces-to-another-host) before you set `ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1`. +- `otel trace export to disabled after failure: refusing plain http to even with ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1: is set, ...` at startup. You opted in, but `OTEL_EXPORTER_OTLP_HEADERS` or `OTEL_EXPORTER_OTLP_TRACES_HEADERS` is set, and its headers would cross the network unencrypted. Unset the variable the message names, or use an `https://` endpoint. The same line with `the endpoint URL carries a user name or password` means the credential is in `ACS_OTEL_ENDPOINT` itself. +- `otel trace export to : ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 is set, so spans go to over plain http, unencrypted. ...` at startup. A warning, not a failure: the endpoint output is running, and it sends in clear text because you opted in. - `otel trace exporter disabled after failure: `, with no output named. The exporter as a whole stopped, for example because `otel-mapping.json` didn't load. No spans reach either output for the rest of the process. - `otel trace exporter shutdown disabled after failure: did not finish within 3000 ms; unexported spans were dropped`. An output stalled at shutdown. The spans still in its queue are lost. - `otel trace export to : an HTTP proxy is set and NO_PROXY/no_proxy did not exempt , so on some Bun versions these spans go through the proxy.` at startup. Your shell has `HTTP_PROXY` set, and the loopback host isn't in the proxy exemption list Bun reads. The Guardian adds the host itself, which takes effect on Bun 1.3.14 and later. On older versions, start the Guardian with the host in both `NO_PROXY` and `no_proxy`, as step 1 of [Produce a trace](../../README.md#produce-a-trace) does. @@ -153,7 +203,7 @@ const guardian = await startGuardian({ port: 0, manifestPath: "policy/manifest.y await guardian.close(); ``` -`StartGuardianOptions` also accepts `hostname`, `envelopeLogPath`, `sessionContextLog`, `otelTraceFile`, `otelTraceEndpoint` and `onDecisionFailure`, which mirror the environment variables above, and five options for tests: `mappingPath`, `annotator`, `bridge`, `sessionContextStore` and `traceExporter`. Each is documented where it is declared, in `src/server.ts`. +`StartGuardianOptions` also accepts `hostname`, `envelopeLogPath`, `sessionContextLog`, `otelTraceFile`, `otelTraceEndpoint`, `otelAllowPlaintextEndpoint` and `onDecisionFailure`, which mirror the environment variables above, and five options for tests: `mappingPath`, `annotator`, `bridge`, `sessionContextStore` and `traceExporter`. Each is documented where it is declared, in `src/server.ts`. `otelTraceEndpoint` leaves the proxy variables alone. `src/main.ts` prints the proxy warning and adds a loopback endpoint's host to whichever of `NO_PROXY` and `no_proxy` is set, or to both when neither is. An embedder that wants the same imports `loopbackProxyWarning` and `keepLoopbackOffProxy` from `guardian` and calls each with `(endpoint, process.env)` before it starts the Guardian. @@ -177,8 +227,8 @@ The package has two entry points. `guardian` exports the governance verbs listed | `src/envelope-log-sink.ts` | The envelope log writer | | `src/otel-trace-exporter.ts` | The OpenTelemetry span exporter, assembled from the three files below | | `src/otel-mapping.ts` | Reads `otel-mapping.json`, and says which envelope field feeds each span attribute | -| `src/otlp-file-exporter.ts` | The OTLP/JSON file writer | -| `src/loopback-proxy.ts` | Keeps a loopback trace endpoint off an HTTP proxy, applied by `src/main.ts` | +| `src/otlp-file-exporter.ts` | The OTLP/JSON file writer, and the checks it makes before each append | +| `src/loopback-proxy.ts` | Says which trace endpoints are loopback, and keeps one off an HTTP proxy, applied by `src/main.ts` | | `src/audit-to-otlp.ts` | Converts the host adapter's audit log into the same OTLP/JSON file | | `src/acs-result.ts` | The decision result type | diff --git a/reference-implementations/agt/packages/guardian/src/audit-to-otlp.ts b/reference-implementations/agt/packages/guardian/src/audit-to-otlp.ts index 9cf327bbc..439c52a38 100644 --- a/reference-implementations/agt/packages/guardian/src/audit-to-otlp.ts +++ b/reference-implementations/agt/packages/guardian/src/audit-to-otlp.ts @@ -63,7 +63,7 @@ import { type JsonObject, } from "./otel-mapping.ts"; import { SPAN_LIMITS } from "./otel-trace-exporter.ts"; -import { createFileSpanExporter } from "./otlp-file-exporter.ts"; +import { checkTraceDirectory, createFileSpanExporter } from "./otlp-file-exporter.ts"; /** * The host's `failure.kind` (packages/host-adapter/src/failure-kinds.ts) @@ -208,6 +208,8 @@ export async function convertAuditLog(auditPath: string, otelPath: string, mappi // otherwise corrupt or double. It does not stop another process swapping // the path mid-run. Nothing here defends against a same-user writer. mkdirSync(dirname(otelPath), { recursive: true, mode: 0o700 }); + // Before the create, so a refused directory is left with no empty output. + await checkTraceDirectory(otelPath); try { closeSync(openSync(otelPath, "wx", 0o600)); } catch (error) { diff --git a/reference-implementations/agt/packages/guardian/src/loopback-proxy.ts b/reference-implementations/agt/packages/guardian/src/loopback-proxy.ts index 2ac225c74..275aa6cfa 100644 --- a/reference-implementations/agt/packages/guardian/src/loopback-proxy.ts +++ b/reference-implementations/agt/packages/guardian/src/loopback-proxy.ts @@ -1,18 +1,52 @@ /** - * Keeps a loopback trace endpoint off an HTTP proxy. Both functions take the - * environment as a parameter: main.ts, the composition root, passes - * process.env, and the exporter itself never reads or writes it. + * Says which trace endpoints are loopback, and keeps one off an HTTP proxy. + * The two proxy functions take the environment as a parameter: main.ts, the + * composition root, passes process.env, and the exporter itself never reads + * or writes the proxy variables. */ +import { isIPv4, isIPv6 } from "node:net"; + +/** The eight groups of an IPv6 address as the URL parser prints it. */ +function ipv6Groups(address: string): number[] { + const [head = "", tail] = address.split("::"); + const groups = (part: string): number[] => (part === "" ? [] : part.split(":").map((group) => Number.parseInt(group, 16))); + const before = groups(head); + const after = tail === undefined ? [] : groups(tail); + return [...before, ...new Array(8 - before.length - after.length).fill(0), ...after]; +} + +/** + * Whether an endpoint's host is this machine: 127.0.0.0/8, `::1`, the + * IPv4-mapped 127 range, or exactly `localhost`. The URL parser normalizes + * the host first (`127.1` and `0x7f.0.0.1` arrive as `127.0.0.1`), so the + * address is judged as numbers and `127.0.0.1.example.com` stays a name. + * `localhost` is accepted because the walkthrough uses it, though a hosts + * file can point it elsewhere. + */ +export function isLoopbackEndpoint(endpoint: string): boolean { + const host = new URL(endpoint).hostname.replace(/^\[|\]$/g, ""); + if (isIPv4(host)) { + return Number(host.split(".")[0]) === 127; + } + if (isIPv6(host)) { + const groups = ipv6Groups(host); + const leadingZeros = (count: number): boolean => groups.slice(0, count).every((group) => group === 0); + const isLoopback = leadingZeros(7) && groups[7] === 1; + const isMappedLoopback = leadingZeros(5) && groups[5] === 0xffff && groups[6]! >> 8 === 127; + return isLoopback || isMappedLoopback; + } + return host === "localhost"; +} /** The NO_PROXY entries that exempt a loopback endpoint's host, or none * when the endpoint is not loopback. IPv6 gets both forms: Bun matches only * `[::1]`, and other clients expect the bare `::1`. */ function loopbackProxyEntries(endpoint: string): string[] { - const host = new URL(endpoint).hostname.replace(/^\[|\]$/g, ""); - if (host === "127.0.0.1" || host === "localhost") { - return [host]; + if (!isLoopbackEndpoint(endpoint)) { + return []; } - return host === "::1" ? ["::1", "[::1]"] : []; + const host = new URL(endpoint).hostname.replace(/^\[|\]$/g, ""); + return host.includes(":") ? [host, `[${host}]`] : [host]; } const splitProxyList = (value: string): string[] => diff --git a/reference-implementations/agt/packages/guardian/src/main.ts b/reference-implementations/agt/packages/guardian/src/main.ts index 302c81b20..0a36100cc 100644 --- a/reference-implementations/agt/packages/guardian/src/main.ts +++ b/reference-implementations/agt/packages/guardian/src/main.ts @@ -36,6 +36,7 @@ const sessionContextLog = process.env.ACS_SESSION_CONTEXT_LOG ?? DEFAULT_SESSION // passed in, like ACS_ENVELOPE_LOG: server.ts reads no env itself. const otelTraceFile = process.env.ACS_OTEL_FILE; const otelTraceEndpoint = process.env.ACS_OTEL_ENDPOINT; +const otelAllowPlaintextEndpoint = process.env.ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT === "1"; // The proxy variables are environment too, so they are read and edited here // and never by the exporter. The warning judges them as the operator set // them, before the edit: Bun 1.3.11 ignores a runtime edit, and there the @@ -74,6 +75,7 @@ const guardian = await startGuardian({ sessionContextLog, otelTraceFile, otelTraceEndpoint, + otelAllowPlaintextEndpoint, }); console.log(`Guardian listening at ${guardian.url}`); console.log(`Envelope log: ${envelopeLogPath}`); diff --git a/reference-implementations/agt/packages/guardian/src/otel-mapping.ts b/reference-implementations/agt/packages/guardian/src/otel-mapping.ts index 0d9b900b6..ca96ce35b 100644 --- a/reference-implementations/agt/packages/guardian/src/otel-mapping.ts +++ b/reference-implementations/agt/packages/guardian/src/otel-mapping.ts @@ -219,6 +219,14 @@ export function asNumber(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) ? value : undefined; } +// An error code too large to be exact is kept at the nearest safe bound +// instead of being dropped, and a fraction is kept so it never matches a +// rejection code by accident. +export function asClampedErrorCode(value: unknown): number | undefined { + if (typeof value !== "number" || Number.isNaN(value)) return undefined; + return Math.max(Number.MIN_SAFE_INTEGER, Math.min(Number.MAX_SAFE_INTEGER, value)); +} + /** A non-empty array of strings, or nothing. An empty array is carried by * the wire (`policy_references: []` on an envelope-invalid deny) but says * nothing a reader can use, so it is not emitted. */ diff --git a/reference-implementations/agt/packages/guardian/src/otel-trace-exporter.ts b/reference-implementations/agt/packages/guardian/src/otel-trace-exporter.ts index be3b02659..4db94da54 100644 --- a/reference-implementations/agt/packages/guardian/src/otel-trace-exporter.ts +++ b/reference-implementations/agt/packages/guardian/src/otel-trace-exporter.ts @@ -9,8 +9,8 @@ * This file assembles the exporter. Three neighbors hold the rest: * otel-mapping.ts reads the mapping and says which envelope field feeds * which attribute, otlp-file-exporter.ts writes the OTLP/JSON file, and - * loopback-proxy.ts holds the proxy helpers main.ts applies before the - * Guardian starts. + * loopback-proxy.ts says which endpoints are loopback and holds the proxy + * helpers main.ts applies before the Guardian starts. * * Span lifetime follows the envelope log. `start` is called where the * request is recorded and hands back the span; `end` is called with that @@ -53,7 +53,7 @@ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"; import { resourceFromAttributes } from "@opentelemetry/resources"; import { AlwaysOnSampler, BasicTracerProvider, BatchSpanProcessor, type SpanExporter, type SpanLimits } from "@opentelemetry/sdk-trace-base"; import { - asNumber, + asClampedErrorCode, asObject, collect, CORRELATION_ATTRIBUTE_SOURCES, @@ -81,6 +81,7 @@ import { type OtelMapping, type RejectionReason, } from "./otel-mapping.ts"; +import { isLoopbackEndpoint } from "./loopback-proxy.ts"; import { createFileSpanExporter } from "./otlp-file-exporter.ts"; // Every name this module exported before the split, so existing importers @@ -229,6 +230,11 @@ export type CreateOtelTraceExporterOptions = { filePath?: string; /** OTLP/HTTP traces endpoint, e.g. `http://127.0.0.1:4318/v1/traces`. */ endpoint?: string; + /** Lets `endpoint` be plain http to a host that is not loopback. */ + allowPlaintextEndpoint?: boolean; + /** For tests. The SDK reads the headers variables from process.env, so any + * other value hides from the plain http check a header the SDK still sends. */ + env?: Record; /** A span exporter used beside (or instead of) the two above. Exists so * tests can read spans back in-process; not meant for production use. */ spanExporter?: SpanExporter; @@ -339,9 +345,54 @@ function rejectedAttributes(claimed: Attributes, reason: RejectionReason, errorC return attributes; } +const OTLP_HEADERS_VARIABLES = ["OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS"] as const; + +const PLAINTEXT_OPT_IN = "ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1"; + +/** + * A span carries reasoning text and provenance ids, so plain http to a host + * that is not loopback is refused unless the operator opted in (#283). With + * the opt-in it is still refused when the URL has a user name or password or + * a headers variable is set: those usually carry a credential, and the + * opt-in accepts unencrypted spans, not an unencrypted credential. The SDK + * reads the headers variables from the environment when the output is + * built, so they are read here at the same moment. + */ +function checkPlaintextEndpoint(endpoint: string, allowed: boolean, env: Record): string | undefined { + const { protocol, hostname, username, password } = new URL(endpoint); + if (protocol !== "http:" || isLoopbackEndpoint(endpoint)) { + return undefined; + } + if (!allowed) { + throw new Error( + `refusing plain http to ${hostname}, which is not a loopback host: spans would cross the network unencrypted. ` + + `Use an https endpoint, or set ${PLAINTEXT_OPT_IN} to send them anyway.`, + ); + } + if (username !== "" || password !== "") { + throw new Error( + `refusing plain http to ${hostname} even with ${PLAINTEXT_OPT_IN}: the endpoint URL carries a user name or password, ` + + "which would cross the network unencrypted. Use an https endpoint, or take them out of the URL.", + ); + } + const headers = OTLP_HEADERS_VARIABLES.find((name) => (env[name] ?? "").trim() !== ""); + if (headers !== undefined) { + throw new Error( + `refusing plain http to ${hostname} even with ${PLAINTEXT_OPT_IN}: ${headers} is set, and the headers it adds can carry credentials, ` + + `which would cross the network unencrypted. Use an https endpoint, or unset ${headers}.`, + ); + } + return ( + `otel trace export to ${endpoint}: ${PLAINTEXT_OPT_IN} is set, so spans go to ${hostname} over plain http, unencrypted. ` + + "Use an https endpoint unless every hop to that host is trusted." + ); +} + export function createOtelTraceExporter({ filePath, endpoint, + allowPlaintextEndpoint = false, + env = process.env, spanExporter, methodsEvaluated, timeoutConfig, @@ -404,10 +455,14 @@ export function createOtelTraceExporter({ // gzip the body. Headers from OTEL_EXPORTER_OTLP_*HEADERS are merged by // the SDK under any set here and cannot be refused, so the README lists // them as honored. - construct( - endpoint, - () => new OTLPTraceExporter({ url: endpoint, timeoutMillis: ENDPOINT_TIMEOUT_MS, compression: "none" as OtlpCompression }), - ); + construct(endpoint, () => { + // Inside construct, so a refusal costs this output alone. + const warning = checkPlaintextEndpoint(endpoint, allowPlaintextEndpoint, env); + if (warning !== undefined) { + console.error(warning); + } + return new OTLPTraceExporter({ url: endpoint, timeoutMillis: ENDPOINT_TIMEOUT_MS, compression: "none" as OtlpCompression }); + }); } if (spanExporter !== undefined) { construct("span exporter", () => spanExporter); @@ -453,15 +508,18 @@ export function createOtelTraceExporter({ // open span is never exported, and without this the step left no trace. const openSpans = new Set(); + const timeoutFor = (stepSpan: StepSpan): number | undefined => timeoutConfig?.per_method_ms?.[stepSpan.method] ?? timeoutConfig?.default_ms; + /** The failure event's attributes for one step, as this Guardian reports * them: its own posture, elapsed time since the span started, and the - * request's size when known. */ + * request's size when known. The elapsed time is rounded up, so a late + * step never reports exactly the timeout. */ function failureAttributes(stepSpan: StepSpan, failureClass: FailureClass, known: Partial = {}): Attributes { return decisionFailureAttributes({ class: failureClass, posture, reportedBy: "guardian", - elapsedMs: Math.round(performance.now() - stepSpan.startedAt), + elapsedMs: Math.ceil(performance.now() - stepSpan.startedAt), payloadBytes: stepSpan.payloadBytes, ...known, }); @@ -549,7 +607,7 @@ export function createOtelTraceExporter({ function finish(stepSpan: StepSpan, envelope: unknown, mapping: OtelMapping, rejection: RejectionReason | undefined): void { const { span } = stepSpan; const error = asObject(asObject(envelope)?.error); - const errorCode = asNumber(error?.code); + const errorCode = asClampedErrorCode(error?.code); // Rejected before the span opened, rejected by a check after it opened, // or answered with a code that only a rejection carries: each ends as a // rejected request, and no held attribute reaches it. @@ -578,7 +636,7 @@ export function createOtelTraceExporter({ // The second: a decision that finished after the host stopped waiting. // The host applied its posture at the timeout, so the decision above // probably never took effect, and a reader has to be told. - const timeoutMs = timeoutConfig?.per_method_ms?.[stepSpan.method] ?? timeoutConfig?.default_ms; + const timeoutMs = timeoutFor(stepSpan); if (timeoutMs !== undefined && performance.now() - stepSpan.startedAt > timeoutMs) { span.addEvent(DECISION_FAILURE_EVENT, failureAttributes(stepSpan, "timeout", { timeoutMs })); } @@ -645,9 +703,15 @@ export function createOtelTraceExporter({ continue; } stepSpan.span.setAttributes({ ...stepSpan.claimed, ...stepSpan.held }); + // Open past the host's timeout: the host already applied its + // posture, so timeout is the more exact class. + const timeoutMs = timeoutFor(stepSpan); + const timedOut = timeoutMs !== undefined && performance.now() - stepSpan.startedAt > timeoutMs; stepSpan.span.addEvent( DECISION_FAILURE_EVENT, - failureAttributes(stepSpan, "other", { detail: "the Guardian shut down before it answered this step" }), + timedOut + ? failureAttributes(stepSpan, "timeout", { timeoutMs }) + : failureAttributes(stepSpan, "other", { detail: "the Guardian shut down before it answered this step" }), ); stepSpan.span.setStatus({ code: SpanStatusCode.ERROR, message: "no response before shutdown" }); stepSpan.span.end(); diff --git a/reference-implementations/agt/packages/guardian/src/otlp-file-exporter.ts b/reference-implementations/agt/packages/guardian/src/otlp-file-exporter.ts index 2d524082a..569638738 100644 --- a/reference-implementations/agt/packages/guardian/src/otlp-file-exporter.ts +++ b/reference-implementations/agt/packages/guardian/src/otlp-file-exporter.ts @@ -3,8 +3,8 @@ * itself. The Guardian's exporter and the audit-log converter both use it, * so the two files share one shape. */ -import { mkdirSync } from "node:fs"; -import { appendFile } from "node:fs/promises"; +import { constants, mkdirSync } from "node:fs"; +import { lstat, open, type FileHandle } from "node:fs/promises"; import { dirname } from "node:path"; import { ExportResultCode } from "@opentelemetry/core"; import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer"; @@ -14,6 +14,107 @@ function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } +// O_NOFOLLOW makes the open fail on a symlink at the final path, so no check +// can be raced. O_NONBLOCK stops the open waiting on a FIFO with no reader. +// Windows has neither flag. +const POSIX_OPEN_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK; +const WINDOWS_OPEN_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT; + +function refusal(path: string, reason: string): Error { + return new Error(`refusing to write ${path}: ${reason}`); +} + +function ownedByThisUser(stats: { uid: number }): boolean { + return stats.uid === process.geteuid?.(); +} + +export async function checkTraceDirectory(path: string, windows = process.platform === "win32"): Promise { + // lstat follows a link named with a trailing "/" or "/.", so both are cut. + const directory = dirname(path).replace(/(?:\/\.?)+$/, "") || "/"; + const parent = await lstat(directory); + if (parent.isSymbolicLink()) { + throw refusal(path, `its directory ${directory} is a symbolic link`); + } + if (windows) { + return; + } + if (!ownedByThisUser(parent)) { + throw refusal(path, `its directory ${directory} is not owned by the user running this process`); + } + if ((parent.mode & 0o002) !== 0) { + throw refusal(path, `its directory ${directory} is writable by every user`); + } +} + +/** + * The trace file holds reasoning text and provenance source ids, so a line + * must not reach a file another user can read or a link put in its place + * (#283). In a directory every user can write to, another user can plant + * one before the Guardian starts, so the directory is checked first. Only + * the immediate parent is checked, because the macOS temp directory sits + * under a system symlink. Bun has no openat, so the directory is checked by + * name. The file checks still hold if it is swapped after that. + * + * Bun's appendFile follows a symlink even with O_NOFOLLOW, so the file is + * opened here and judged by its descriptor: the file checked is the file + * written. A mode wider than 0600 is narrowed, not refused, because a refusal + * would turn the trace off in the walkthrough (#274). + * + * Windows has no O_NOFOLLOW, so a symlink is found by looking before the + * open, and one put there in between is followed. No owner or mode is + * checked there: Windows decides access by ACL, which this leaves alone. + */ +async function appendLine(path: string, line: string, windows: boolean): Promise { + await checkTraceDirectory(path, windows); + if (windows) { + // A missing path is fine: the open creates it. + const existing = await lstat(path).catch(() => undefined); + if (existing?.isSymbolicLink()) { + throw refusal(path, "it is a symbolic link"); + } + } + + let handle: FileHandle; + try { + handle = await open(path, windows ? WINDOWS_OPEN_FLAGS : POSIX_OPEN_FLAGS, 0o600); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + // ELOOP is O_NOFOLLOW meeting a symlink. ENXIO is a FIFO with no reader. + if (code === "ELOOP") { + throw refusal(path, "it is a symbolic link"); + } + if (code === "ENXIO") { + throw refusal(path, "it is not a regular file"); + } + throw error; + } + try { + const stats = await handle.stat(); + if (!stats.isFile()) { + throw refusal(path, "it is not a regular file"); + } + if (stats.nlink > 1) { + throw refusal(path, "it has more than one hard link"); + } + if (!windows) { + if (!ownedByThisUser(stats)) { + throw refusal(path, "it is not owned by the user running this process"); + } + if ((stats.mode & 0o7777) !== 0o600) { + await handle.chmod(0o600); + } + } + await handle.appendFile(line); + } finally { + await handle.close(); + } +} + +export type FileSpanExporterOptions = { + /** Lets a test run the Windows branch on POSIX. */ + platform?: NodeJS.Platform; +}; + /** * Writes OTLP/JSON, one `ExportTraceServiceRequest` per line (the shape * the OpenTelemetry Collector's file exporter writes), serialised by the @@ -30,10 +131,11 @@ function asError(error: unknown): Error { * * 0o700 on the directory and 0o600 on the file: the file holds reasoning * text and provenance source ids, so other local users should not read it - * (#71 is the same problem in the envelope log). The mode applies when the - * exporter creates the path; an existing file keeps whatever it had. + * (#71 is the same problem in the envelope log). The directory's mode applies + * when the exporter creates it. Each append checks the file again and sets it + * to 0o600 (see appendLine). */ -export function createFileSpanExporter(path: string): SpanExporter { +export function createFileSpanExporter(path: string, { platform = process.platform }: FileSpanExporterOptions = {}): SpanExporter { mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); let chain: Promise = Promise.resolve(); return { @@ -49,7 +151,7 @@ export function createFileSpanExporter(path: string): SpanExporter { resultCallback({ code: ExportResultCode.FAILED, error: asError(error) }); return; } - const write = chain.then(() => appendFile(path, line, { mode: 0o600 })); + const write = chain.then(() => appendLine(path, line, platform === "win32")); chain = write.then( () => undefined, () => undefined, diff --git a/reference-implementations/agt/packages/guardian/src/server.ts b/reference-implementations/agt/packages/guardian/src/server.ts index 8a38eed4e..f304dd70f 100644 --- a/reference-implementations/agt/packages/guardian/src/server.ts +++ b/reference-implementations/agt/packages/guardian/src/server.ts @@ -343,6 +343,9 @@ export type StartGuardianOptions = { /** OTLP/HTTP traces endpoint. Omitted means no span is sent. main.ts * threads ACS_OTEL_ENDPOINT into this. */ otelTraceEndpoint?: string; + /** Lets `otelTraceEndpoint` be plain http to a host that is not loopback. + * main.ts threads ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT into this. */ + otelAllowPlaintextEndpoint?: boolean; /** Overrides the trace exporter entirely, bypassing both paths above. * Exists so a test can read spans back in-process or stand in one that * fails. Not meant for production use. */ @@ -416,6 +419,7 @@ export async function startGuardian({ sessionContextStore: sessionContextStoreOverride, otelTraceFile, otelTraceEndpoint, + otelAllowPlaintextEndpoint, traceExporter: traceExporterOverride, }: StartGuardianOptions): Promise { // Construct the bridge once at boot, not per request -- and through the @@ -453,6 +457,7 @@ export async function startGuardian({ ? createOtelTraceExporter({ filePath: otelTraceFile, endpoint: otelTraceEndpoint, + allowPlaintextEndpoint: otelAllowPlaintextEndpoint, methodsEvaluated: hello.methods_evaluated, timeoutConfig: hello.timeout_config, posture: hello.on_decision_failure === "deny" ? "fail_closed" : "fail_open", diff --git a/reference-implementations/agt/packages/guardian/test/main.test.ts b/reference-implementations/agt/packages/guardian/test/main.test.ts index b4d2f5ac3..9f77dccd0 100644 --- a/reference-implementations/agt/packages/guardian/test/main.test.ts +++ b/reference-implementations/agt/packages/guardian/test/main.test.ts @@ -176,3 +176,64 @@ describe("main.ts applies the loopback proxy exemption", () => { 15_000, ); }); + +// Issue #283: plain http to a host that is not loopback needs an explicit +// opt-in, and main.ts is the one place that reads it. No step is posted in +// these tests, so the Guardian has no span to send and nothing reaches +// 10.0.0.1. +describe("main.ts reads the plain http opt-in", () => { + const ENDPOINT = "http://10.0.0.1:4318/v1/traces"; + + /** Starts the Guardian against ENDPOINT and returns its stderr, read until + * `expected` shows up or the runtime's watchdog ends the process. */ + async function stderrUntil(expected: string, env: Record): Promise { + const proc = Bun.spawn([process.execPath, GUARDIAN], { + cwd: scratch(), + env: { + PATH: process.env.PATH ?? "", + HOME: process.env.HOME ?? "", + NO_COLOR: "1", + ACS_GUARDIAN_PORT: "0", + ACS_MANIFEST_PATH: MANIFEST, + ACS_OTEL_ENDPOINT: ENDPOINT, + ...env, + }, + stdout: "ignore", + stderr: "pipe", + timeout: 3_000, + }); + const decoder = new TextDecoder(); + let stderr = ""; + for await (const chunk of proc.stderr) { + stderr += decoder.decode(chunk, { stream: true }); + if (stderr.includes(expected)) { + proc.kill(); + } + } + proc.kill(); + await proc.exited; + return stderr; + } + + it("refuses the endpoint on stderr when ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT is unset", async () => { + const refused = + `otel trace export to ${ENDPOINT} disabled after failure: refusing plain http to 10.0.0.1, which is not a loopback host: ` + + "spans would cross the network unencrypted. Use an https endpoint, or set ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 to send them anyway."; + expect(await stderrUntil(refused, {})).toContain(refused); + }); + + it("warns on stderr instead when ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT is 1", async () => { + const warning = + `otel trace export to ${ENDPOINT}: ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 is set, so spans go to 10.0.0.1 over plain http, unencrypted. ` + + "Use an https endpoint unless every hop to that host is trusted."; + const stderr = await stderrUntil(warning, { ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT: "1" }); + expect(stderr).toContain(warning); + expect(stderr).not.toContain("refusing plain http"); + }); + + it("takes only the value 1 as the opt-in", async () => { + expect(await stderrUntil("refusing plain http to 10.0.0.1", { ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT: "true" })).toContain( + "refusing plain http to 10.0.0.1, which is not a loopback host", + ); + }); +}); diff --git a/reference-implementations/agt/packages/guardian/test/otel-trace-exporter.test.ts b/reference-implementations/agt/packages/guardian/test/otel-trace-exporter.test.ts index 80bed4e99..953a10ae4 100644 --- a/reference-implementations/agt/packages/guardian/test/otel-trace-exporter.test.ts +++ b/reference-implementations/agt/packages/guardian/test/otel-trace-exporter.test.ts @@ -1,14 +1,34 @@ import { afterEach, describe, expect, it, spyOn } from "bun:test"; -import { existsSync, mkdtempSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { + chmodSync, + closeSync, + constants, + existsSync, + linkSync, + mkdirSync, + mkdtempSync, + openSync, + readdirSync, + readFileSync, + rmdirSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { SpanStatusCode } from "@opentelemetry/api"; +import { ExportResultCode, type ExportResult } from "@opentelemetry/core"; import { InMemorySpanExporter, type ReadableSpan, type SpanExporter } from "@opentelemetry/sdk-trace-base"; import type { PolicyBridge } from "agt-bridge"; import { startGuardian, type GuardianSnapshot } from "../src/index.ts"; import { FAILURE_DETAIL_BY_KIND } from "../src/audit-to-otlp.ts"; import { buildServerHello } from "../src/handshake.ts"; +import { isLoopbackEndpoint } from "../src/loopback-proxy.ts"; +import { asClampedErrorCode } from "../src/otel-mapping.ts"; import { makeEnvelope, toolCallEnvelope } from "./helpers/envelopes.ts"; import { createFileSpanExporter, @@ -75,6 +95,22 @@ function throwingSpanExporter(): SpanExporter { }; } +/** A span exporter that keeps what it is handed. InMemorySpanExporter + * forgets its spans when it is shut down, and some tests read them after. */ +function keepingSpanExporter(): { exporter: SpanExporter; spans: ReadableSpan[] } { + const spans: ReadableSpan[] = []; + return { + spans, + exporter: { + export(batch, resultCallback): void { + spans.push(...batch); + resultCallback({ code: ExportResultCode.SUCCESS }); + }, + async shutdown(): Promise {}, + }, + }; +} + async function postRaw(url: string, body: unknown): Promise> { const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); return (await res.json()) as Record; @@ -836,6 +872,71 @@ describe("Guardian trace export wiring", () => { }); } + // The acceptance test on issue #283. The issue #274 premortem re-posted a + // real pair and found three events under it: the allow, a guardian_error + // and a deny. Here four re-posts, each refused by a different schema rule, + // leave the pair with its one span. + it("leaves exactly one span under a real pair after four rejected re-posts of it", async () => { + const { exporter, spans } = memoryExporter(); + const guardian = await startGuardian({ ...baseOptions, traceExporter: exporter }); + try { + const requestId = crypto.randomUUID(); + const sessionId = crypto.randomUUID(); + const repost = (id: number | null) => toolCallEnvelope("ls -la", { id, requestId, sessionId }); + const params = (envelope: Record) => envelope.params as Record; + // No JSON-RPC id. The Guardian has no id to answer under, so this one + // gets a bare error and the other three get a deny. + const noRpcId = repost(null); + // A required member missing. + const noTimestamp = repost(2); + delete params(noTimestamp).timestamp; + // A version that is not semver. + const badVersion = repost(3); + params(badVersion).acs_version = "1"; + // A payload the hook's own schema refuses. + const noArguments = repost(4); + delete (params(noArguments).payload as Record).arguments; + + const genuine = await postRaw(guardian.url, repost(1)); + const answers: Record[] = []; + for (const envelope of [noRpcId, noTimestamp, badVersion, noArguments]) { + answers.push(await postRaw(guardian.url, envelope)); + } + await exporter.flush(); + + expect((genuine.result as { decision?: string }).decision).toBe("allow"); + expect( + answers.map((answer) => (answer.error as { code?: number } | undefined)?.code ?? (answer.result as { reason_codes?: string[] }).reason_codes), + ).toEqual([-32010, ["envelope_invalid"], ["envelope_invalid"], ["envelope_invalid"]]); + + // Either id under its ACS name counts, not only the two together. + const underPair = spans().filter( + (span) => span.attributes["acs.request_id"] === requestId || span.attributes["acs.session.id"] === sessionId, + ); + expect(underPair).toHaveLength(1); + expect(underPair[0]?.name).toBe(TOOL_CALL_SPAN.span_name); + expect(underPair[0]?.events.map((event) => [event.name, event.attributes?.["acs.decision"]])).toEqual([ + [MAPPING.decisionEventName, "allow"], + ]); + + const rejected = spans().filter((span) => span !== underPair[0]); + expect(rejected.map((span) => ({ name: span.name, attributes: span.attributes, events: span.events }))).toEqual( + [-32010, undefined, undefined, undefined].map((errorCode) => ({ + name: REJECTED_SPAN_NAME, + attributes: { + "guardian.rejected.reason": "envelope_invalid", + "guardian.rejected.claimed_session_id": sessionId, + "guardian.rejected.claimed_request_id": requestId, + ...(errorCode === undefined ? {} : { "guardian.rejected.error_code": errorCode }), + }, + events: [], + })), + ); + } finally { + await guardian.close(); + } + }); + it("records a schema-invalid envelope for a method it does not dispatch as a rejected request too", async () => { const { exporter, spans } = memoryExporter(); const guardian = await startGuardian({ ...baseOptions, traceExporter: exporter }); @@ -983,7 +1084,10 @@ describe("Guardian trace export wiring", () => { // never exported: the step would leave no trace at all. Shutdown closes // it with an `other` failure event that says why. close() drains for the // negotiated timeout (5 s in the ServerHello) before it gives up on the - // handler, which is what bounds this test. + // handler, which is what bounds this test. This exporter is built with no + // timeouts, so the class is `other` however long the drain took. A Guardian + // that builds its own from the ServerHello writes `timeout` once the drain + // has outlasted the step's timeout. it("closes a step still open at shutdown with an other failure event and ERROR status", async () => { // The file, not an in-memory exporter: close() shuts the provider down, // and InMemorySpanExporter forgets its spans when it is shut down. @@ -1240,6 +1344,37 @@ describe("createOtelTraceExporter -- review fixes", () => { expect(span?.events[0]?.attributes?.["acs.failure.detail"]).toBeUndefined(); }); + it("clamps an error code past the safe range to the bound and keeps a fraction", () => { + const fourHundredDigits = "9".repeat(400); + expect(asClampedErrorCode(-1e21)).toBe(Number.MIN_SAFE_INTEGER); + expect(asClampedErrorCode(1e21)).toBe(Number.MAX_SAFE_INTEGER); + expect(asClampedErrorCode(JSON.parse(`-${fourHundredDigits}`))).toBe(Number.MIN_SAFE_INTEGER); + expect(asClampedErrorCode(JSON.parse(fourHundredDigits))).toBe(Number.MAX_SAFE_INTEGER); + expect(asClampedErrorCode(-32005.5)).toBe(-32005.5); + expect(asClampedErrorCode(Number.NaN)).toBeUndefined(); + expect(asClampedErrorCode("-32005")).toBeUndefined(); + }); + + for (const [code, expected] of [ + [-1e21, Number.MIN_SAFE_INTEGER], + [-32005.5, -32005.5], + ] as const) { + it(`keeps error code ${code} on the step as ${expected}`, async () => { + const { exporter, spans } = memoryExporter(); + exporter.end(exporter.start(toolCallEnvelope("ls", { id: 3 }), "steps/toolCallRequest", TRUSTED), { + jsonrpc: "2.0", + id: 3, + error: { code, message: "failed" }, + }); + await exporter.flush(); + + const [span] = spans(); + expect(span?.name).not.toBe(REJECTED_SPAN_NAME); + expect(span?.events[0]?.attributes?.["acs.failure.class"]).toBe("guardian_error"); + expect(span?.events[0]?.attributes?.["acs.failure.error_code"]).toBe(expected); + }); + } + // #228 and PR #273: a request rejected before it was trusted gets no // acs.decision.failure under its pair, because the pair may be a genuine // request's. That holds even when the check ran after the span opened, as @@ -1467,6 +1602,438 @@ describe("createOtelTraceExporter -- review fixes", () => { }); }); +// Issue #283, items 3 and 4. The host applied its posture when its timeout +// ran out, so a step it stopped waiting for is a timeout whether the decision +// came late or never came. +describe("createOtelTraceExporter -- a step the host stopped waiting for", () => { + /** Opens one step that arrived `ageMs` ago, shuts the exporter down, and + * returns the failure event the step was closed with. The age comes in + * through `receivedAt`, so no test here sleeps. */ + async function closedAtShutdown(ageMs: number, timeoutConfig?: CreateOtelTraceExporterOptions["timeoutConfig"]) { + const kept = keepingSpanExporter(); + const exporter = createOtelTraceExporter({ spanExporter: kept.exporter, methodsEvaluated: METHODS_EVALUATED, timeoutConfig }); + exporter.start(toolCallEnvelope("ls", { id: 1 }), "steps/toolCallRequest", { trusted: true, receivedAt: performance.now() - ageMs }); + await exporter.shutdown(); + + expect(kept.spans).toHaveLength(1); + expect(kept.spans[0]?.events.map((event) => event.name)).toEqual(["acs.decision.failure"]); + return kept.spans[0]?.events[0]?.attributes; + } + + it("closes a step older than the default timeout at shutdown as a timeout, with timeout_ms", async () => { + const failure = await closedAtShutdown(200, { default_ms: 50 }); + + expect(failure?.["acs.failure.class"]).toBe("timeout"); + expect(failure?.["acs.failure.timeout_ms"]).toBe(50); + expect(failure?.["acs.failure.elapsed_ms"]).toBeGreaterThanOrEqual(200); + expect(failure?.["acs.failure.detail"]).toBeUndefined(); + }); + + it("judges a step open at shutdown by its method's own timeout before the default", async () => { + const shortForMethod = await closedAtShutdown(200, { default_ms: 60_000, per_method_ms: { "steps/toolCallRequest": 50 } }); + expect([shortForMethod?.["acs.failure.class"], shortForMethod?.["acs.failure.timeout_ms"]]).toEqual(["timeout", 50]); + + const longForMethod = await closedAtShutdown(200, { default_ms: 50, per_method_ms: { "steps/toolCallRequest": 60_000 } }); + expect(longForMethod?.["acs.failure.class"]).toBe("other"); + }); + + it("keeps other, with its detail, for a step open for less than its timeout or with no timeout known", async () => { + for (const timeoutConfig of [{ default_ms: 60_000 }, undefined]) { + const failure = await closedAtShutdown(200, timeoutConfig); + + expect(failure?.["acs.failure.class"]).toBe("other"); + expect(failure?.["acs.failure.detail"]).toBe("the Guardian shut down before it answered this step"); + expect(failure?.["acs.failure.timeout_ms"]).toBeUndefined(); + } + }); + + // 50.3 ms against a 50 ms timeout is late, and rounding reported it as 50. + // The clock is held, so the elapsed time is 50.3 ms on any machine. + it("reports a decision 0.3 ms late with an elapsed_ms above timeout_ms, never equal to it", async () => { + const { exporter, spans } = memoryExporter({ timeoutConfig: { default_ms: 50 } }); + const clock = spyOn(performance, "now").mockReturnValue(1000); + try { + const handle = exporter.start(toolCallEnvelope("ls", { id: 1 }), "steps/toolCallRequest", { trusted: true, receivedAt: 1000 }); + clock.mockReturnValue(1050.3); + exporter.end(handle, decisionResponse(1, { decision: "allow" })); + } finally { + clock.mockRestore(); + } + await exporter.flush(); + + const failure = spans()[0]?.events.find((event) => event.name === "acs.decision.failure")?.attributes; + expect(failure?.["acs.failure.class"]).toBe("timeout"); + expect(failure?.["acs.failure.timeout_ms"]).toBe(50); + expect(failure?.["acs.failure.elapsed_ms"]).toBe(51); + }); +}); + +// Issue #283, item 1. The file exporter opens the path itself on every +// append, so it can refuse a link, or a file that is not the user's, before +// it writes a line of reasoning text into it. +describe("createFileSpanExporter -- what it will append to", () => { + // Ownership, modes and O_NOFOLLOW are POSIX. The Windows branch has its own + // tests at the end, and those run on every platform. + const WINDOWS = process.platform === "win32"; + + const scratch: string[] = []; + const scratchDir = (): string => { + const dir = mkdtempSync(join(tmpdir(), "acs-otel-open-")); + scratch.push(dir); + return dir; + }; + afterEach(() => { + for (const dir of scratch.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + /** Hands the exporter one finished span and resolves with what it reported. */ + async function exportTo(file: SpanExporter): Promise { + const { exporter, spans } = memoryExporter(); + exporter.end(exporter.start(toolCallEnvelope("ls", { id: 1 }), "steps/toolCallRequest", TRUSTED), decisionResponse(1, { decision: "allow" })); + await exporter.flush(); + const batch = [...spans()]; + await exporter.shutdown(); + return new Promise((resolve) => file.export(batch, resolve)); + } + + /** The span names on each line the exporter appended after `skip` lines. */ + const appendedSpanNames = (path: string, skip: number): string[][] => + readFileSync(path, "utf8") + .split("\n") + .filter((line) => line !== "") + .slice(skip) + .map((line) => otlpSpans([JSON.parse(line) as OtlpRequest]).map((span) => span.name)); + + it.skipIf(WINDOWS)("refuses a symlink at the final path and writes nothing through it", async () => { + for (const targetExists of [true, false]) { + const dir = scratchDir(); + const target = join(dir, "target.jsonl"); + if (targetExists) { + writeFileSync(target, "kept\n"); + } + const path = join(dir, "traces.jsonl"); + symlinkSync(target, path); + + const result = await exportTo(createFileSpanExporter(path)); + + expect(result.code).toBe(ExportResultCode.FAILED); + expect(result.error?.message).toBe(`refusing to write ${path}: it is a symbolic link`); + // An existing target is untouched, and a dangling link creates none. + expect(existsSync(target) ? readFileSync(target, "utf8") : null).toBe(targetExists ? "kept\n" : null); + } + }); + + it.skipIf(WINDOWS)("refuses a parent directory that is a symlink, and creates nothing where it points", async () => { + const dir = scratchDir(); + const real = join(dir, "real"); + mkdirSync(real, { mode: 0o700 }); + const linked = join(dir, "linked"); + symlinkSync(real, linked); + // However the path spells the directory: lstat follows a link named with + // a trailing "/." or "/". + for (const path of [join(linked, "traces.jsonl"), `${linked}/./traces.jsonl`, `${linked}//traces.jsonl`]) { + const result = await exportTo(createFileSpanExporter(path)); + + expect(result.code).toBe(ExportResultCode.FAILED); + expect(result.error?.message).toBe(`refusing to write ${path}: its directory ${linked} is a symbolic link`); + expect(readdirSync(real)).toEqual([]); + } + }); + + it.skipIf(WINDOWS)("refuses a file with a second hard link, and leaves its content and mode alone", async () => { + const dir = scratchDir(); + const original = join(dir, "original.jsonl"); + writeFileSync(original, "kept\n"); + chmodSync(original, 0o644); + const path = join(dir, "traces.jsonl"); + linkSync(original, path); + + const result = await exportTo(createFileSpanExporter(path)); + + expect(result.code).toBe(ExportResultCode.FAILED); + expect(result.error?.message).toBe(`refusing to write ${path}: it has more than one hard link`); + expect(readFileSync(original, "utf8")).toBe("kept\n"); + expect((statSync(original).mode & 0o777).toString(8)).toBe("644"); + }); + + // Tightened, not refused: PR #112 keeps existing file modes, and a refusal + // here would turn the trace off in the walkthrough (issue #274). + it.skipIf(WINDOWS)("tightens an existing 0644 file to 0600 and appends to it", async () => { + const path = join(scratchDir(), "traces.jsonl"); + writeFileSync(path, "earlier line\n"); + chmodSync(path, 0o644); + + const result = await exportTo(createFileSpanExporter(path)); + + expect(result.code).toBe(ExportResultCode.SUCCESS); + expect((statSync(path).mode & 0o777).toString(8)).toBe("600"); + expect(readFileSync(path, "utf8").startsWith("earlier line\n")).toBe(true); + expect(appendedSpanNames(path, 1)).toEqual([[TOOL_CALL_SPAN.span_name]]); + }); + + it.skipIf(WINDOWS)("appends to an existing file the user owns that has one link, on every export", async () => { + const path = join(scratchDir(), "traces.jsonl"); + writeFileSync(path, "earlier line\n", { mode: 0o600 }); + const file = createFileSpanExporter(path); + + const results = [await exportTo(file), await exportTo(file)]; + + expect(results.map((result) => result.code)).toEqual([ExportResultCode.SUCCESS, ExportResultCode.SUCCESS]); + expect(appendedSpanNames(path, 1)).toEqual([[TOOL_CALL_SPAN.span_name], [TOOL_CALL_SPAN.span_name]]); + }); + + // Every append, not only the first: the path can change under a Guardian + // that has been writing to it for hours. + it.skipIf(WINDOWS)("checks the path again on an append that follows a good one", async () => { + const dir = scratchDir(); + const path = join(dir, "traces.jsonl"); + const file = createFileSpanExporter(path); + expect((await exportTo(file)).code).toBe(ExportResultCode.SUCCESS); + + chmodSync(path, 0o644); + expect((await exportTo(file)).code).toBe(ExportResultCode.SUCCESS); + expect((statSync(path).mode & 0o777).toString(8)).toBe("600"); + + const target = join(dir, "target.jsonl"); + writeFileSync(target, "kept\n"); + unlinkSync(path); + symlinkSync(target, path); + expect((await exportTo(file)).error?.message).toBe(`refusing to write ${path}: it is a symbolic link`); + expect(readFileSync(target, "utf8")).toBe("kept\n"); + }); + + // A blocking open of a FIFO waits for a reader, on the event loop's own + // thread pool, for as long as none comes. + it.skipIf(WINDOWS)("refuses a FIFO at once instead of waiting for a reader, and refuses one that has a reader", async () => { + const path = join(scratchDir(), "traces.jsonl"); + expect(Bun.spawnSync(["mkfifo", path]).exitCode).toBe(0); + const file = createFileSpanExporter(path); + const outcome = async (): Promise => + Promise.race([exportTo(file).then((result) => result.error?.message), Bun.sleep(2000).then(() => "still waiting after 2 s")]); + const refused = `refusing to write ${path}: it is not a regular file`; + + expect(await outcome()).toBe(refused); + + // With a reader the open succeeds, so the descriptor's own type is what + // refuses it. + const reader = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK); + try { + expect(await outcome()).toBe(refused); + } finally { + closeSync(reader); + } + }); + + it.skipIf(WINDOWS)("refuses a parent directory every user can write to, and accepts one only its group can", async () => { + const dir = scratchDir(); + const path = join(dir, "traces.jsonl"); + const file = createFileSpanExporter(path); + + // 1777 is /tmp: the sticky bit stops a rename, not a file planted first. + // The chmod command sets the mode, because Bun's chmodSync drops the + // sticky bit. + for (const mode of ["777", "1777"]) { + expect(Bun.spawnSync(["chmod", mode, dir]).exitCode).toBe(0); + expect((statSync(dir).mode & 0o7777).toString(8)).toBe(mode); + const result = await exportTo(file); + expect(result.error?.message).toBe(`refusing to write ${path}: its directory ${dir} is writable by every user`); + expect(existsSync(path)).toBe(false); + } + + chmodSync(dir, 0o770); + expect((await exportTo(file)).code).toBe(ExportResultCode.SUCCESS); + }); + + // No test can make another user's file without root, so the effective uid + // is what changes here. + it.skipIf(WINDOWS)("refuses a directory, and then a file, that the effective user does not own", async () => { + const dir = scratchDir(); + const path = join(dir, "traces.jsonl"); + const file = createFileSpanExporter(path); + const me = process.geteuid!(); + const euid = spyOn(process, "geteuid"); + try { + euid.mockReturnValue(me + 1); + const inDirectory = await exportTo(file); + expect(inDirectory.error?.message).toBe(`refusing to write ${path}: its directory ${dir} is not owned by the user running this process`); + expect(existsSync(path)).toBe(false); + + // The directory is checked first and the opened file second, so only + // the second answer is the other user's. + writeFileSync(path, "kept\n"); + chmodSync(path, 0o644); + let asked = 0; + euid.mockImplementation(() => (asked++ === 0 ? me : me + 1)); + const onFile = await exportTo(file); + expect(onFile.error?.message).toBe(`refusing to write ${path}: it is not owned by the user running this process`); + expect(readFileSync(path, "utf8")).toBe("kept\n"); + expect((statSync(path).mode & 0o777).toString(8)).toBe("644"); + } finally { + euid.mockRestore(); + } + }); + + // The Windows branch, chosen by the platform option so it runs here too. + // It has no O_NOFOLLOW, so the link at the path is found by looking first. + it("on the Windows branch, refuses a symlink at the path or as its directory, and a second hard link", async () => { + const dir = scratchDir(); + const onWindows = (path: string): Promise => exportTo(createFileSpanExporter(path, { platform: "win32" })); + + const target = join(dir, "target.jsonl"); + writeFileSync(target, "kept\n"); + const link = join(dir, "link.jsonl"); + symlinkSync(target, link); + expect((await onWindows(link)).error?.message).toBe(`refusing to write ${link}: it is a symbolic link`); + expect(readFileSync(target, "utf8")).toBe("kept\n"); + + const nowhere = join(dir, "nowhere.jsonl"); + const dangling = join(dir, "dangling.jsonl"); + symlinkSync(nowhere, dangling); + expect((await onWindows(dangling)).error?.message).toBe(`refusing to write ${dangling}: it is a symbolic link`); + expect(existsSync(nowhere)).toBe(false); + + const real = join(dir, "real"); + mkdirSync(real); + const linked = join(dir, "linked"); + symlinkSync(real, linked); + const inLinked = join(linked, "traces.jsonl"); + expect((await onWindows(inLinked)).error?.message).toBe(`refusing to write ${inLinked}: its directory ${linked} is a symbolic link`); + expect(readdirSync(real)).toEqual([]); + + const second = join(dir, "second.jsonl"); + linkSync(target, second); + expect((await onWindows(second)).error?.message).toBe(`refusing to write ${second}: it has more than one hard link`); + expect(readFileSync(target, "utf8")).toBe("kept\n"); + }); + + // What the Windows branch does not do, pinned so its doc comment stays + // true: it judges no directory by its mode bits, and it changes no mode. + it("on the Windows branch, appends whatever the directory's mode bits say, and leaves the file's mode alone", async () => { + const dir = scratchDir(); + const path = join(dir, "traces.jsonl"); + writeFileSync(path, "earlier line\n"); + chmodSync(path, 0o644); + chmodSync(dir, 0o777); + const before = statSync(path).mode; + + const result = await exportTo(createFileSpanExporter(path, { platform: "win32" })); + + expect(result.code).toBe(ExportResultCode.SUCCESS); + expect(statSync(path).mode).toBe(before); + expect(appendedSpanNames(path, 1)).toEqual([[TOOL_CALL_SPAN.span_name]]); + }); +}); + +// Issue #283, item 2. A span carries reasoning text and provenance ids, and +// plain http to another host sends them across the network in clear text. +// No test here ends a span, so nothing is ever sent to 10.0.0.1: each one +// reads what was built and what was reported. +describe("createOtelTraceExporter -- plain http to a host that is not loopback", () => { + const REMOTE = "http://10.0.0.1:4318/v1/traces"; + const REFUSED = + `otel trace export to ${REMOTE} disabled after failure: refusing plain http to 10.0.0.1, which is not a loopback host: ` + + "spans would cross the network unencrypted. Use an https endpoint, or set ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 to send them anyway."; + const WARNING = + `otel trace export to ${REMOTE}: ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 is set, so spans go to 10.0.0.1 over plain http, unencrypted. ` + + "Use an https endpoint unless every hop to that host is trusted."; + const refusedForHeaders = (variable: string): string => + `otel trace export to ${REMOTE} disabled after failure: refusing plain http to 10.0.0.1 even with ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1: ` + + `${variable} is set, and the headers it adds can carry credentials, which would cross the network unencrypted. Use an https endpoint, or unset ${variable}.`; + + /** Builds an exporter for one endpoint and returns it with every line it + * printed. The environment is the test's own, never the process's. */ + function build(endpoint: string, options: Partial = {}): { exporter: OtelTraceExporter; printed: unknown[][] } { + const errorSpy = spyOn(console, "error").mockImplementation(() => {}); + try { + const exporter = createOtelTraceExporter({ endpoint, methodsEvaluated: METHODS_EVALUATED, env: {}, ...options }); + return { exporter, printed: [...errorSpy.mock.calls] }; + } finally { + errorSpy.mockRestore(); + } + } + + it("builds no endpoint output, and says why and how to opt in", () => { + const { exporter, printed } = build(REMOTE); + + // The endpoint was the only output asked for, so none at all is built. + expect(exporter).toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([[REFUSED]]); + }); + + it("keeps the file output when the endpoint beside it is refused", async () => { + const dir = mkdtempSync(join(tmpdir(), "acs-otel-refused-endpoint-")); + try { + const { exporter, printed } = build(REMOTE, { filePath: join(dir, "traces.jsonl") }); + + expect(exporter).not.toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([[REFUSED]]); + await exporter.shutdown(); + } finally { + rmdirSync(dir); + } + }); + + it("builds the output with the opt-in, and prints a warning", async () => { + const { exporter, printed } = build(REMOTE, { allowPlaintextEndpoint: true }); + + expect(exporter).not.toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([[WARNING]]); + await exporter.shutdown(); + }); + + it("refuses with the opt-in when either headers variable is set, because its headers can carry credentials", () => { + for (const variable of ["OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS"]) { + const { exporter, printed } = build(REMOTE, { allowPlaintextEndpoint: true, env: { [variable]: "authorization=Bearer synthetic" } }); + + expect(exporter).toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([[refusedForHeaders(variable)]]); + } + }); + + // The http client sends userinfo as a Basic Authorization header. + it("refuses with the opt-in when the endpoint URL carries a user name or password", () => { + for (const userinfo of ["user:synthetic", "user"]) { + const withCredential = `http://${userinfo}@10.0.0.1:4318/v1/traces`; + const { exporter, printed } = build(withCredential, { allowPlaintextEndpoint: true }); + + expect(exporter).toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([ + [ + `otel trace export to ${withCredential} disabled after failure: refusing plain http to 10.0.0.1 even with ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1: ` + + "the endpoint URL carries a user name or password, which would cross the network unencrypted. Use an https endpoint, or take them out of the URL.", + ], + ]); + } + }); + + it("treats an empty headers variable as unset, as the SDK does", async () => { + const { exporter, printed } = build(REMOTE, { allowPlaintextEndpoint: true, env: { OTEL_EXPORTER_OTLP_HEADERS: "", OTEL_EXPORTER_OTLP_TRACES_HEADERS: " " } }); + + expect(exporter).not.toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([[WARNING]]); + await exporter.shutdown(); + }); + + it("accepts every loopback form over plain http without the opt-in, and prints nothing", async () => { + for (const host of ["127.0.0.1", "127.1", "2130706433", "127.255.255.254", "[::1]", "[::ffff:127.0.0.1]", "localhost"]) { + const { exporter, printed } = build(`http://${host}:4318/v1/traces`, { env: { OTEL_EXPORTER_OTLP_HEADERS: "x-acs-probe=1" } }); + + expect({ host, built: exporter !== NULL_OTEL_TRACE_EXPORTER, printed }).toEqual({ host, built: true, printed: [] }); + await exporter.shutdown(); + } + }); + + it("needs no opt-in for https to another host, headers or not", async () => { + const { exporter, printed } = build("https://10.0.0.1:4318/v1/traces", { env: { OTEL_EXPORTER_OTLP_HEADERS: "authorization=Bearer synthetic" } }); + + expect(exporter).not.toBe(NULL_OTEL_TRACE_EXPORTER); + expect(printed).toEqual([]); + await exporter.shutdown(); + }); +}); + // Issue #274: nothing in the lab's shell changes what the Guardian exports. describe("the Guardian's exporter does not depend on its environment", () => { const saved: Record = {}; @@ -1605,6 +2172,52 @@ describe("the Guardian's exporter does not depend on its environment", () => { } }, 10_000); + // The one place the exporter reads the environment itself (issue #283): + // the SDK reads these variables from process.env when the endpoint output + // is built, so the check has to look there too. + it("refuses plain http to another host under the opt-in when the process environment sets a headers variable", () => { + unsetEnv("OTEL_EXPORTER_OTLP_HEADERS"); + setEnv({ OTEL_EXPORTER_OTLP_TRACES_HEADERS: "authorization=Bearer synthetic" }); + const errors: unknown[] = []; + const exporter = createOtelTraceExporter({ + endpoint: "http://10.0.0.1:4318/v1/traces", + allowPlaintextEndpoint: true, + methodsEvaluated: METHODS_EVALUATED, + onError: (error) => errors.push(error), + }); + + expect(exporter).toBe(NULL_OTEL_TRACE_EXPORTER); + expect(errors.map((error) => (error as Error).message)).toEqual([ + "refusing plain http to 10.0.0.1 even with ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1: OTEL_EXPORTER_OTLP_TRACES_HEADERS is set, " + + "and the headers it adds can carry credentials, which would cross the network unencrypted. " + + "Use an https endpoint, or unset OTEL_EXPORTER_OTLP_TRACES_HEADERS.", + ]); + }); + + // server.ts reads no environment, so the opt-in reaches the exporter as an + // option. No step is posted, so nothing is sent to 10.0.0.1. + it("carries the plain http opt-in from startGuardian to the exporter", async () => { + unsetEnv("OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS"); + const endpoint = "http://10.0.0.1:4318/v1/traces"; + const errorSpy = spyOn(console, "error").mockImplementation(() => {}); + try { + const printed: string[] = []; + for (const otelAllowPlaintextEndpoint of [undefined, false, true]) { + errorSpy.mockClear(); + const guardian = await startGuardian({ ...baseOptions, otelTraceEndpoint: endpoint, otelAllowPlaintextEndpoint }); + await guardian.close(); + printed.push(errorSpy.mock.calls.map((call) => String(call[0]).split(": ")[1]).join("|")); + } + expect(printed).toEqual([ + "refusing plain http to 10.0.0.1, which is not a loopback host", + "refusing plain http to 10.0.0.1, which is not a loopback host", + "ACS_OTEL_ALLOW_PLAINTEXT_ENDPOINT=1 is set, so spans go to 10.0.0.1 over plain http, unencrypted. Use an https endpoint unless every hop to that host is trusted.", + ]); + } finally { + errorSpy.mockRestore(); + } + }); + // The exemption is main.ts's to apply (Ariel's review on PR #286), so this // test applies it the way main.ts does, before the exporter is built. It // runs in a fresh child for the reason the routing test further down @@ -1761,6 +2374,17 @@ describe("keepLoopbackOffProxy", () => { expect([process.env.NO_PROXY, process.env.no_proxy]).toEqual(["a.internal,127.0.0.1", "b.internal,127.0.0.1"]); }); + // Issue #283: every host isLoopbackEndpoint accepts takes plain http with + // no opt-in, so each one has to stay off a proxy, not only three spellings. + it("adds the endpoint's own host for any other loopback address", () => { + reset(undefined); + keepLoopbackOffProxy("http://127.0.0.2:4318/v1/traces", process.env); + expect([process.env.NO_PROXY, process.env.no_proxy]).toEqual(["127.0.0.2", "127.0.0.2"]); + reset(undefined); + keepLoopbackOffProxy("http://[::ffff:127.0.0.1]:4318/v1/traces", process.env); + expect([process.env.NO_PROXY, process.env.no_proxy]).toEqual(["::ffff:7f00:1,[::ffff:7f00:1]", "::ffff:7f00:1,[::ffff:7f00:1]"]); + }); + it("does not duplicate the entry when called twice", () => { reset(undefined); keepLoopbackOffProxy("http://127.0.0.1:4318/v1/traces", process.env); @@ -1809,6 +2433,11 @@ describe("loopbackProxyWarning", () => { expect(loopbackProxyWarning("http://collector.example.com:4318/v1/traces", { HTTP_PROXY: "http://proxy:3128" })).toBeUndefined(); }); + it("warns for any other loopback address too", () => { + expect(loopbackProxyWarning("http://127.0.0.2:4318/v1/traces", { HTTP_PROXY: "http://proxy:3128" })).toContain("did not exempt 127.0.0.2,"); + expect(loopbackProxyWarning("http://[::ffff:127.0.0.1]:4318/v1/traces", { HTTP_PROXY: "http://proxy:3128" })).toContain("did not exempt [::ffff:7f00:1],"); + }); + it("wants the bracketed form for IPv6, the only one Bun matches", () => { const v6 = "http://[::1]:4318/v1/traces"; expect(loopbackProxyWarning(v6, { HTTP_PROXY: "http://proxy:3128", NO_PROXY: "::1" })).toBeDefined(); @@ -1816,6 +2445,68 @@ describe("loopbackProxyWarning", () => { }); }); +// Issue #283: which endpoints may take plain http without the opt-in. The +// URL parser normalizes the host first, so every spelling of one address is +// judged as that address. +describe("isLoopbackEndpoint", () => { + it("accepts 127.0.0.0/8, ::1, an IPv4-mapped 127 address and the name localhost, however they are spelled", () => { + for (const host of [ + "127.0.0.1", + "127.0.0.0", + "127.255.255.255", + "127.1", + "2130706433", + "0x7f.0.0.1", + "0177.0.0.1", + "[::1]", + "[0:0:0:0:0:0:0:1]", + "[::ffff:127.0.0.1]", + "[::ffff:7f00:1]", + "[::ffff:127.9.8.7]", + "[0:0:0:0:0:ffff:7fff:ffff]", + "localhost", + "LOCALHOST", + ]) { + expect({ host, loopback: isLoopbackEndpoint(`http://${host}:4318/v1/traces`) }).toEqual({ host, loopback: true }); + } + }); + + it("refuses every other address, and every other name", () => { + for (const host of [ + "10.0.0.1", + "126.255.255.255", + "128.0.0.1", + "0.0.0.0", + "1.0.0.127", + "[::]", + "[::2]", + "[1::1]", + "[::1:0:1]", + "[::ffff:10.0.0.1]", + "[::ffff:128.0.0.1]", + // 127.0.0.1 in the last 32 bits, but not under the ::ffff:0:0/96 prefix. + "[::7f00:1]", + "[::fffe:7f00:1]", + "[1::ffff:7f00:1]", + "[0:0:0:1:0:ffff:7f00:1]", + "[2001:db8::7f00:1]", + "127.0.0.1.example.com", + "localhost.example.com", + "localhost.", + "notlocalhost", + "collector.example.com", + ]) { + expect({ host, loopback: isLoopbackEndpoint(`http://${host}:4318/v1/traces`) }).toEqual({ host, loopback: false }); + } + }); + + it("judges the host the URL parser found, not one that only appears in the text", () => { + expect(isLoopbackEndpoint("http://127.0.0.1@collector.example.com:4318/v1/traces")).toBe(false); + expect(isLoopbackEndpoint("http://collector.example.com:4318/127.0.0.1")).toBe(false); + expect(isLoopbackEndpoint("http://user:secret@127.0.0.1:4318/v1/traces")).toBe(true); + }); +}); + // Routing, not strings. It runs in a fresh child with its environment set at // spawn, because Bun latches proxy variables across edits within a process, // which makes any in-process routing check pass for the wrong reason. Bun diff --git a/reference-implementations/agt/test/audit-to-otlp.test.ts b/reference-implementations/agt/test/audit-to-otlp.test.ts index dce62def2..1d81461c3 100644 --- a/reference-implementations/agt/test/audit-to-otlp.test.ts +++ b/reference-implementations/agt/test/audit-to-otlp.test.ts @@ -1,5 +1,20 @@ import { afterEach, describe, expect, it } from "bun:test"; -import { appendFileSync, existsSync, linkSync, mkdtempSync, readFileSync, rmdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { + appendFileSync, + chmodSync, + existsSync, + linkSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmdirSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -601,6 +616,24 @@ describe("audit-to-otlp: refuses an output that already exists", () => { expect(existsSync(out)).toBe(false); })); + // Issue #283: the exporter refuses these directories, and the converter + // asks before it creates its output, so nothing is left to block a rerun. + it.skipIf(process.platform === "win32")("creates no output in a directory the exporter refuses", () => + inScratch(async (dir, audit) => { + const open = join(dir, "open"); + mkdirSync(open); + chmodSync(open, 0o777); + await expect(convertAuditLog(audit, join(open, "otel.jsonl"))).rejects.toThrow(/writable by every user$/); + expect(readdirSync(open)).toEqual([]); + + const real = join(dir, "real"); + mkdirSync(real, { mode: 0o700 }); + const linked = join(dir, "linked"); + symlinkSync(real, linked); + await expect(convertAuditLog(audit, join(linked, "otel.jsonl"))).rejects.toThrow(/is a symbolic link$/); + expect(readdirSync(real)).toEqual([]); + })); + it("writes a new output owner-only, creating its directory owner-only", () => inScratch(async (dir, audit) => { const out = join(dir, "new-dir", "otel.jsonl"); From 60c5722bbc0bbb42e9f9b77cac5b08ede4d70978 Mon Sep 17 00:00:00 2001 From: Saba Siddique Date: Wed, 25 Nov 2026 23:32:54 +0500 Subject: [PATCH 2/2] Re-record the TypeScript cases for the changed Guardian source Signed-off-by: Saba Siddique --- .../agt-go/agtbridge/testdata/ts-cases.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reference-implementations/agt-go/agtbridge/testdata/ts-cases.json b/reference-implementations/agt-go/agtbridge/testdata/ts-cases.json index f76b301d2..831615c5b 100644 --- a/reference-implementations/agt-go/agtbridge/testdata/ts-cases.json +++ b/reference-implementations/agt-go/agtbridge/testdata/ts-cases.json @@ -4,7 +4,7 @@ "mapping.yaml": "3dac231d12196657ed186e3bce2bd3ef81be290a", "packages/agt-bridge/package.json": "89dd8140627b2d01abc67fc8f59e531cc0850c40", "packages/agt-bridge/src": "4cb957b4632fd795c54a9db379399c861cef2e45", - "packages/guardian/src": "c36b1af4422e6ecbe43707e7235cae1f99583110", + "packages/guardian/src": "da08784e89e4ce4763018fc1d1b6aed85b100332", "policy": "c6f34f789525f8a89a4c2fc1ba236fb1a0cd70d0" }, "cases": [