Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
58 changes: 54 additions & 4 deletions reference-implementations/agt/packages/guardian/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<number>(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[] =>
Expand Down
2 changes: 2 additions & 0 deletions reference-implementations/agt/packages/guardian/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -74,6 +75,7 @@ const guardian = await startGuardian({
sessionContextLog,
otelTraceFile,
otelTraceEndpoint,
otelAllowPlaintextEndpoint,
});
console.log(`Guardian listening at ${guardian.url}`);
console.log(`Envelope log: ${envelopeLogPath}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<string, string | undefined>;
/** 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;
Expand Down Expand Up @@ -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, string | undefined>): 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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -453,15 +508,18 @@ export function createOtelTraceExporter({
// open span is never exported, and without this the step left no trace.
const openSpans = new Set<StepSpan>();

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<DecisionFailure> = {}): 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,
});
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 }));
}
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading