Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

test(telemetry): add tests for HTTP instrumentation and semconv opt-in

Victor Hugo dos Santose3530c797598
diff --git a/backend/src/lib/telemetry/http-instrumentation.test.ts b/backend/src/lib/telemetry/http-instrumentation.test.ts
new file mode 100644
index 0000000000..7a8bc1a37a
--- /dev/null
+++ b/backend/src/lib/telemetry/http-instrumentation.test.ts
@@ -0,0 +1,146 @@
+import { createRequire } from "node:module";
+
+import opentelemetry from "@opentelemetry/api";
+import { registerInstrumentations } from "@opentelemetry/instrumentation";
+import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
+import {
+ AggregationTemporality,
+ createAllowListAttributesProcessor,
+ InMemoryMetricExporter,
+ MeterProvider,
+ type MetricData,
+ PeriodicExportingMetricReader,
+ type ResourceMetrics
+} from "@opentelemetry/sdk-metrics";
+
+import {
+ HTTP_INSTRUMENTATION_METER_ATTRIBUTES,
+ HTTP_INSTRUMENTATION_METER_NAME,
+ resolveHttpSemconvOptIn
+} from "./telemetry-attributes";
+
+describe("resolveHttpSemconvOptIn", () => {
+ test("forces the http token when nothing is set", () => {
+ expect(resolveHttpSemconvOptIn(undefined)).toBe("http");
+ expect(resolveHttpSemconvOptIn("")).toBe("http");
+ });
+
+ test("preserves tokens for other namespaces", () => {
+ expect(resolveHttpSemconvOptIn("database,messaging")).toBe("database,messaging,http");
+ });
+
+ // http/dup emits the old attribute set alongside the stable one, which puts net.host.name back.
+ test("strips http/dup rather than letting it through", () => {
+ expect(resolveHttpSemconvOptIn("http/dup")).toBe("http");
+ expect(resolveHttpSemconvOptIn("database,HTTP/DUP")).toBe("database,http");
+ });
+
+ test("does not duplicate an http token that is already present", () => {
+ expect(resolveHttpSemconvOptIn("http")).toBe("http");
+ });
+});
+
+// The instrumentation reads OTEL_SEMCONV_STABILITY_OPT_IN in its constructor and patches node:http on
+// require, and neither is undone reliably by unregistering. So the pipeline is built once per file, and
+// the opposite configuration lives in http-semconv-baseline.test.ts, where Vitest's file isolation gives
+// it a fresh module registry. Both files together are the regression test: this one asserts the
+// production configuration is bounded, that one asserts it would not be bounded without the opt-in.
+const getWithHost = (http: typeof import("node:http"), port: number, host: string) =>
+ new Promise<void>((resolve, reject) => {
+ http
+ .get({ host: "127.0.0.1", port, path: "/probe", headers: { Host: host } }, (res) => {
+ res.resume();
+ res.on("end", resolve);
+ })
+ .on("error", reject);
+ });
+
+describe("HttpInstrumentation under the production configuration", () => {
+ let snapshot: ResourceMetrics;
+ let server: import("node:http").Server;
+ let http: typeof import("node:http");
+ let port: number;
+
+ beforeAll(async () => {
+ process.env.OTEL_SEMCONV_STABILITY_OPT_IN = resolveHttpSemconvOptIn(process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+ // Collected once into a snapshot below: the reader is delta, so the first collect() drains the
+ // points and every later one comes back empty.
+ const reader = new PeriodicExportingMetricReader({
+ exporter: new InMemoryMetricExporter(AggregationTemporality.CUMULATIVE),
+ exportIntervalMillis: 60_000
+ });
+ const meterProvider = new MeterProvider({
+ readers: [reader],
+ views: [
+ {
+ meterName: HTTP_INSTRUMENTATION_METER_NAME,
+ attributesProcessors: [createAllowListAttributesProcessor(HTTP_INSTRUMENTATION_METER_ATTRIBUTES)]
+ }
+ ]
+ });
+ opentelemetry.metrics.setGlobalMeterProvider(meterProvider);
+ registerInstrumentations({ instrumentations: [new HttpInstrumentation()], meterProvider });
+
+ http = createRequire(`${process.cwd()}/`)("http") as typeof import("node:http");
+ server = http.createServer((_req, res) => {
+ res.statusCode = 200;
+ res.end("ok");
+ });
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ port = (server.address() as { port: number }).port;
+
+ // Three requests, three different Host headers. Under the old conventions this is three series.
+ for (const host of ["probe-a.invalid", "probe-b.invalid", "probe-c.invalid"]) {
+ // eslint-disable-next-line no-await-in-loop
+ await getWithHost(http, port, host);
+ }
+
+ snapshot = (await reader.collect()).resourceMetrics;
+ });
+
+ afterAll(async () => {
+ opentelemetry.metrics.disable();
+ await new Promise<void>((resolve) => {
+ if (!server) {
+ resolve();
+ return;
+ }
+ server.close(() => resolve());
+ });
+ });
+
+ const metric = (name: string): MetricData | undefined =>
+ snapshot.scopeMetrics.flatMap((scope) => scope.metrics).find((m) => m.descriptor.name === name);
+ const labelKeys = (name: string) =>
+ new Set(metric(name)?.dataPoints.flatMap((point) => Object.keys(point.attributes)) ?? []);
+
+ test("exports the stable metric and not the old one", () => {
+ expect(metric("http.server.request.duration")).toBeDefined();
+ expect(metric("http.server.duration")).toBeUndefined();
+ });
+
+ test("never carries net.host.name, and distinct Host headers collapse onto one series", () => {
+ const keys = labelKeys("http.server.request.duration");
+ expect(keys.has("net.host.name")).toBe(false);
+ expect(metric("http.server.request.duration")?.dataPoints).toHaveLength(1);
+ });
+
+ test("the View strips the constants stable semconv still carries", () => {
+ const keys = labelKeys("http.server.request.duration");
+ expect(keys.has("url.scheme")).toBe(false);
+ expect(keys.has("network.protocol.version")).toBe(false);
+ expect([...keys].every((key) => HTTP_INSTRUMENTATION_METER_ATTRIBUTES.includes(key))).toBe(true);
+ });
+
+ // Stable semconv drops the host from the SERVER metric but keeps server.address on the CLIENT metric,
+ // which is every outbound hostname the instance calls: webhooks, sync destinations, IdPs. The allowlist
+ // is the only thing bounding that, so this is the case that must not regress.
+ test("the View strips server.address from the client metric", () => {
+ const keys = labelKeys("http.client.request.duration");
+ expect(keys.size).toBeGreaterThan(0);
+ expect(keys.has("server.address")).toBe(false);
+ expect(keys.has("server.port")).toBe(false);
+ });
+});
diff --git a/backend/src/lib/telemetry/http-metrics.test.ts b/backend/src/lib/telemetry/http-metrics.test.ts
index 75c111b3de..087cf70d01 100644
--- a/backend/src/lib/telemetry/http-metrics.test.ts
+++ b/backend/src/lib/telemetry/http-metrics.test.ts
@@ -10,12 +10,7 @@ import {
} from "@opentelemetry/sdk-metrics";
import Fastify, { type FastifyInstance } from "fastify";
-import {
- HIGH_CARDINALITY_METER_NAMES,
- HTTP_INSTRUMENTATION_METER_ATTRIBUTES,
- HTTP_INSTRUMENTATION_METER_NAME,
- INFISICAL_CORE_METER_ATTRIBUTES
-} from "./telemetry-attributes";
+import { HIGH_CARDINALITY_METER_NAMES, INFISICAL_CORE_METER_ATTRIBUTES } from "./telemetry-attributes";
const mockConfig = {
OTEL_TELEMETRY_COLLECTION_ENABLED: true,
@@ -32,8 +27,11 @@ const LEGACY_REQUEST_COUNT = "infisical.http.server.request.count";
let reader: PeriodicExportingMetricReader;
-// Mirrors initTelemetryInstrumentation() in instrumentation.ts. The Views are the thing under test as
-// much as the plugin is: an attribute added at a call site is only bounded because the allowlist drops it.
+// Mirrors the InfisicalCore half of initTelemetryInstrumentation(). The View is under test as much as the
+// plugin is: an attribute added at a call site is only bounded because the allowlist drops it. The HTTP
+// instrumentation meter is deliberately NOT wired up here, because nothing in this file registers
+// HttpInstrumentation and a View with no instrument behind it would imply coverage that does not exist.
+// That pipeline is covered by http-instrumentation.test.ts and http-semconv-baseline.test.ts.
//
// Two things make a per-test provider necessary, and both fail silently rather than erroring:
// the OpenTelemetry API ignores a second setGlobalMeterProvider() unless the global is disabled first,
@@ -46,10 +44,6 @@ const installMeterProvider = () => {
{
meterName: "InfisicalCore",
attributesProcessors: [createAllowListAttributesProcessor(INFISICAL_CORE_METER_ATTRIBUTES)]
- },
- {
- meterName: HTTP_INSTRUMENTATION_METER_NAME,
- attributesProcessors: [createAllowListAttributesProcessor(HTTP_INSTRUMENTATION_METER_ATTRIBUTES)]
}
];
if (mockConfig.OTEL_DROP_HIGH_CARDINALITY_METERS) {
diff --git a/backend/src/lib/telemetry/http-semconv-baseline.test.ts b/backend/src/lib/telemetry/http-semconv-baseline.test.ts
new file mode 100644
index 0000000000..dbdae65a93
--- /dev/null
+++ b/backend/src/lib/telemetry/http-semconv-baseline.test.ts
@@ -0,0 +1,95 @@
+import { createRequire } from "node:module";
+
+import opentelemetry from "@opentelemetry/api";
+import { registerInstrumentations } from "@opentelemetry/instrumentation";
+import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
+import {
+ AggregationTemporality,
+ InMemoryMetricExporter,
+ MeterProvider,
+ PeriodicExportingMetricReader,
+ type ResourceMetrics
+} from "@opentelemetry/sdk-metrics";
+
+// The negative half of the HttpInstrumentation regression test. Its counterpart,
+// http-instrumentation.test.ts, asserts the production configuration is bounded; this one asserts the
+// same traffic is UNBOUNDED without the semconv opt-in, so that a change which quietly stops applying
+// the opt-in fails here instead of leaving a green suite that proves nothing.
+//
+// It lives in its own file because the instrumentation reads OTEL_SEMCONV_STABILITY_OPT_IN in its
+// constructor and patches node:http on require, neither of which unregistering reliably undoes. Vitest
+// isolates by file, so this gets a fresh module registry.
+const getWithHost = (http: typeof import("node:http"), port: number, host: string) =>
+ new Promise<void>((resolve, reject) => {
+ http
+ .get({ host: "127.0.0.1", port, path: "/probe", headers: { Host: host } }, (res) => {
+ res.resume();
+ res.on("end", resolve);
+ })
+ .on("error", reject);
+ });
+
+describe("HttpInstrumentation without the semconv opt-in", () => {
+ let snapshot: ResourceMetrics;
+ let server: import("node:http").Server;
+
+ beforeAll(async () => {
+ delete process.env.OTEL_SEMCONV_STABILITY_OPT_IN;
+
+ const reader = new PeriodicExportingMetricReader({
+ exporter: new InMemoryMetricExporter(AggregationTemporality.CUMULATIVE),
+ exportIntervalMillis: 60_000
+ });
+ const meterProvider = new MeterProvider({ readers: [reader] });
+ opentelemetry.metrics.setGlobalMeterProvider(meterProvider);
+ registerInstrumentations({ instrumentations: [new HttpInstrumentation()], meterProvider });
+
+ const http = createRequire(`${process.cwd()}/`)("http") as typeof import("node:http");
+ server = http.createServer((_req, res) => {
+ res.statusCode = 200;
+ res.end("ok");
+ });
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const { port } = server.address() as { port: number };
+
+ for (const host of ["probe-a.invalid", "probe-b.invalid", "probe-c.invalid"]) {
+ // eslint-disable-next-line no-await-in-loop
+ await getWithHost(http, port, host);
+ }
+
+ snapshot = (await reader.collect()).resourceMetrics;
+ });
+
+ afterAll(async () => {
+ opentelemetry.metrics.disable();
+ await new Promise<void>((resolve) => {
+ if (!server) {
+ resolve();
+ return;
+ }
+ server.close(() => resolve());
+ });
+ });
+
+ test("falls back to the old metric name", () => {
+ const names = snapshot.scopeMetrics.flatMap((scope) => scope.metrics).map((m) => m.descriptor.name);
+ expect(names).toContain("http.server.duration");
+ expect(names).not.toContain("http.server.request.duration");
+ });
+
+ test("labels the metric with the client-controlled Host header, one series per value", () => {
+ const duration = snapshot.scopeMetrics
+ .flatMap((scope) => scope.metrics)
+ .find((m) => m.descriptor.name === "http.server.duration");
+
+ const keys = new Set(duration?.dataPoints.flatMap((point) => Object.keys(point.attributes)) ?? []);
+ expect(keys.has("net.host.name")).toBe(true);
+
+ // Three Host headers, three series. This is the growth that killed the collector.
+ expect(duration?.dataPoints).toHaveLength(3);
+ const hosts = duration?.dataPoints.map((point) => point.attributes["net.host.name"]);
+ expect(new Set(hosts).size).toBe(3);
+ });
+});
diff --git a/backend/src/lib/telemetry/instrumentation.ts b/backend/src/lib/telemetry/instrumentation.ts
index e33186cf9a..8e839e66b5 100644
--- a/backend/src/lib/telemetry/instrumentation.ts
+++ b/backend/src/lib/telemetry/instrumentation.ts
@@ -22,7 +22,8 @@ import {
HIGH_CARDINALITY_METER_NAMES,
HTTP_INSTRUMENTATION_METER_ATTRIBUTES,
HTTP_INSTRUMENTATION_METER_NAME,
- INFISICAL_CORE_METER_ATTRIBUTES
+ INFISICAL_CORE_METER_ATTRIBUTES,
+ resolveHttpSemconvOptIn
} from "./telemetry-attributes";
dotenv.config();
@@ -116,19 +117,7 @@ const initTelemetryInstrumentation = ({
opentelemetry.metrics.setGlobalMeterProvider(meterProvider);
- // HttpInstrumentation reads this in its constructor and exposes no config equivalent, so it has to be set
- // here rather than left to the deployment. Unset means the old HTTP semconv, whose http.server.duration
- // carries net.host.name, the raw client-controlled Host header, and so grows a new series for every value
- // a scanner sends. Stable drops it, normalizes the method to a fixed set, and adds error.type.
- // Assigning it (rather than defaulting it) keeps one metric name across cloud and self-hosted, and shuts
- // out "http/dup", which would emit both attribute sets and double the cardinality this is here to bound.
- // Other namespace tokens are preserved: the value is a comma-separated list and a future
- // instrumentation may read its own namespace out of it.
- const semconvOptIn = (process.env.OTEL_SEMCONV_STABILITY_OPT_IN ?? "")
- .split(",")
- .map((token) => token.trim())
- .filter((token) => token && token.toLowerCase() !== "http" && token.toLowerCase() !== "http/dup");
- process.env.OTEL_SEMCONV_STABILITY_OPT_IN = [...semconvOptIn, "http"].join(",");
+ process.env.OTEL_SEMCONV_STABILITY_OPT_IN = resolveHttpSemconvOptIn(process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
registerInstrumentations({
instrumentations: [new HttpInstrumentation(), new RuntimeNodeInstrumentation()]
diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.ts
index 7ef42c1e21..baf703d96a 100644
--- a/backend/src/lib/telemetry/telemetry-attributes.ts
+++ b/backend/src/lib/telemetry/telemetry-attributes.ts
@@ -58,6 +58,16 @@ export const HIGH_CARDINALITY_METER_NAMES = ["Infisical", "API", "SecretSyncs",
// Meter used by @opentelemetry/instrumentation-http for http.server.duration / http.client.duration.
export const HTTP_INSTRUMENTATION_METER_NAME = "@opentelemetry/instrumentation-http";
+// HttpInstrumentation reads OTEL_SEMCONV_STABILITY_OPT_IN in its constructor (no config hook), so instrumentation.ts
+// forces the "http" token via resolveHttpSemconvOptIn — not "http/dup", which doubles cardinality; other namespaces are preserved.
+export const resolveHttpSemconvOptIn = (current?: string): string => {
+ const otherNamespaces = (current ?? "")
+ .split(",")
+ .map((token) => token.trim())
+ .filter((token) => token && token.toLowerCase() !== "http" && token.toLowerCase() !== "http/dup");
+ return [...otherNamespaces, "http"].join(",");
+};
+
// This View keeps http.server.duration bounded if an upgrade reintroduces unbounded host related attributes like net.host.name and constant labels like url.scheme
export const HTTP_INSTRUMENTATION_METER_ATTRIBUTES = [
"http.request.method",