Skip to content

Commit 629bf6f

Browse files
authored
fix(otel): redact invalid collector URLs and suppress implicit exporters (#118635)
1 parent 1af8bdd commit 629bf6f

4 files changed

Lines changed: 434 additions & 45 deletions

File tree

‎extensions/diagnostics-otel/src/service-exporter.ts‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,28 +28,47 @@ function resolveOtelUrl(endpoint: string | undefined, path: string): string | un
2828
return endpoint;
2929
}
3030
if (/[?#]/u.test(endpoint)) {
31-
try {
32-
const url = new URL(endpoint);
33-
const basePath = url.pathname.replace(/\/+$/u, "");
34-
url.pathname = `${basePath}/${path}`;
35-
return url.toString();
36-
} catch {
37-
// Fall back to the historical concatenation path for non-URL test doubles.
38-
}
31+
const url = new URL(endpoint);
32+
const basePath = url.pathname.replace(/\/+$/u, "");
33+
url.pathname = `${basePath}/${path}`;
34+
return url.toString();
3935
}
4036
return `${endpoint}/${path}`;
4137
}
4238

4339
export function resolveSignalOtelUrl(params: {
4440
signalEndpoint?: string;
4541
signalEnvEndpoint?: string;
42+
sharedEnvEndpoint?: string;
4643
endpoint?: string;
4744
path: string;
4845
}): string | undefined {
49-
return resolveOtelUrl(
50-
normalizeEndpoint(params.signalEndpoint ?? params.signalEnvEndpoint) ?? params.endpoint,
51-
params.path,
52-
);
46+
const endpoint =
47+
normalizeEndpoint(params.signalEndpoint ?? params.signalEnvEndpoint) ?? params.endpoint;
48+
// OTLP parses nonblank env values verbatim even when explicit config takes precedence.
49+
const signalEnvEndpoint = params.signalEnvEndpoint?.trim() ? params.signalEnvEndpoint : undefined;
50+
const sharedEnvEndpoint = params.sharedEnvEndpoint?.trim() ? params.sharedEnvEndpoint : undefined;
51+
const consumedSharedEnvEndpoint = signalEnvEndpoint ? undefined : sharedEnvEndpoint;
52+
const appendedSharedEnvEndpoint = consumedSharedEnvEndpoint
53+
? `${consumedSharedEnvEndpoint}${consumedSharedEnvEndpoint.endsWith("/") ? "" : "/"}${params.path}`
54+
: undefined;
55+
const resolvedEndpoint =
56+
endpoint && URL.canParse(endpoint) ? resolveOtelUrl(endpoint, params.path) : endpoint;
57+
58+
for (const candidate of [
59+
endpoint,
60+
signalEnvEndpoint ?? sharedEnvEndpoint,
61+
appendedSharedEnvEndpoint,
62+
resolvedEndpoint,
63+
]) {
64+
if (candidate && !URL.canParse(candidate)) {
65+
throw new Error(
66+
"Configured OpenTelemetry collector endpoint is invalid; check the collector URL",
67+
);
68+
}
69+
}
70+
71+
return resolvedEndpoint;
5372
}
5473

5574
function readOtelEnvFile(params: {

‎extensions/diagnostics-otel/src/service.otlp-export.test.ts‎

Lines changed: 242 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
// test feeds in, collapsing the diagnostic and OTel id spaces into one value. That hides
66
// a parent lookup keyed by one id space and queried with the other.
77
//
8-
// It drives the service through the OPENCLAW_OTEL_PRELOADED seam so the plugin uses this
9-
// file's tracer provider instead of starting its own NodeSDK. trace.disable() in teardown
10-
// then fully releases the global API slot; a NodeSDK cannot be unregistered, and the
11-
// leftover dead provider would make any later real-SDK test export nothing.
12-
import { trace } from "@opentelemetry/api";
8+
// Trace cases use the OPENCLAW_OTEL_PRELOADED seam to retain this file's tracer provider.
9+
// Collector-boundary cases start the real NodeSDK, so teardown restores every global SDK
10+
// registration; otherwise a shutdown provider would poison later real-SDK cases.
11+
import { context, diag, DiagLogLevel, metrics, propagation, trace } from "@opentelemetry/api";
12+
import { logs } from "@opentelemetry/api-logs";
1313
import {
1414
BasicTracerProvider,
1515
InMemorySpanExporter,
@@ -23,17 +23,58 @@ import {
2323
resetDiagnosticEventsForTest,
2424
waitForDiagnosticEventsDrained,
2525
} from "openclaw/plugin-sdk/diagnostic-runtime";
26-
import { afterEach, beforeEach, expect, test } from "vitest";
27-
import { startOtelService, stopStartedOtelServices } from "./service.test-helpers.js";
26+
import { afterEach, beforeEach, expect, test, vi } from "vitest";
27+
import { createDiagnosticsOtelService } from "./service.js";
28+
import {
29+
createOtelContext,
30+
startOtelService,
31+
stopStartedOtelServices,
32+
} from "./service.test-helpers.js";
2833

2934
const PRELOAD_ENV = "OPENCLAW_OTEL_PRELOADED";
35+
const ENDPOINT_ENV_KEYS = [
36+
"OTEL_EXPORTER_OTLP_ENDPOINT",
37+
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
38+
"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
39+
"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
40+
"OTEL_LOG_LEVEL",
41+
] as const;
42+
const OTEL_GLOBAL_API_KEY = Symbol.for("opentelemetry.js.api.1");
43+
const OTEL_GLOBAL_LOGS_KEY = Symbol.for("io.opentelemetry.js.api.logs");
44+
45+
type OtelGlobalRegistrations = {
46+
context?: Parameters<typeof context.setGlobalContextManager>[0];
47+
diag?: Parameters<typeof diag.setLogger>[0];
48+
metrics?: Parameters<typeof metrics.setGlobalMeterProvider>[0];
49+
propagation?: Parameters<typeof propagation.setGlobalPropagator>[0];
50+
trace?: Parameters<typeof trace.setGlobalTracerProvider>[0];
51+
};
3052

3153
let exporter: InMemorySpanExporter;
3254
let provider: BasicTracerProvider;
3355
let originalPreloaded: string | undefined;
56+
let originalEndpointEnv: Record<(typeof ENDPOINT_ENV_KEYS)[number], string | undefined>;
57+
let originalOtelGlobals: OtelGlobalRegistrations;
58+
let originalLogsProvider: ReturnType<typeof logs.getLoggerProvider> | undefined;
59+
60+
function registeredOtelGlobals(): OtelGlobalRegistrations | undefined {
61+
return (globalThis as unknown as Record<symbol, OtelGlobalRegistrations | undefined>)[
62+
OTEL_GLOBAL_API_KEY
63+
];
64+
}
3465

3566
beforeEach(() => {
3667
originalPreloaded = process.env[PRELOAD_ENV];
68+
originalEndpointEnv = Object.fromEntries(
69+
ENDPOINT_ENV_KEYS.map((key) => [key, process.env[key]]),
70+
) as Record<(typeof ENDPOINT_ENV_KEYS)[number], string | undefined>;
71+
for (const key of ENDPOINT_ENV_KEYS) {
72+
delete process.env[key];
73+
}
74+
originalOtelGlobals = { ...registeredOtelGlobals() };
75+
originalLogsProvider = Object.hasOwn(globalThis, OTEL_GLOBAL_LOGS_KEY)
76+
? logs.getLoggerProvider()
77+
: undefined;
3778
process.env[PRELOAD_ENV] = "1";
3879
exporter = new InMemorySpanExporter();
3980
provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] });
@@ -43,13 +84,58 @@ beforeEach(() => {
4384
afterEach(async () => {
4485
await stopStartedOtelServices();
4586
await provider.shutdown();
46-
trace.disable();
87+
const currentGlobals = registeredOtelGlobals();
88+
if (currentGlobals?.context !== originalOtelGlobals.context) {
89+
context.disable();
90+
if (originalOtelGlobals.context) {
91+
context.setGlobalContextManager(originalOtelGlobals.context);
92+
}
93+
}
94+
if (currentGlobals?.propagation !== originalOtelGlobals.propagation) {
95+
propagation.disable();
96+
if (originalOtelGlobals.propagation) {
97+
propagation.setGlobalPropagator(originalOtelGlobals.propagation);
98+
}
99+
}
100+
if (currentGlobals?.metrics !== originalOtelGlobals.metrics) {
101+
metrics.disable();
102+
if (originalOtelGlobals.metrics) {
103+
metrics.setGlobalMeterProvider(originalOtelGlobals.metrics);
104+
}
105+
}
106+
if (currentGlobals?.trace !== originalOtelGlobals.trace) {
107+
trace.disable();
108+
if (originalOtelGlobals.trace) {
109+
trace.setGlobalTracerProvider(originalOtelGlobals.trace);
110+
}
111+
}
112+
if (Object.hasOwn(globalThis, OTEL_GLOBAL_LOGS_KEY) || originalLogsProvider) {
113+
logs.disable();
114+
if (originalLogsProvider) {
115+
logs.setGlobalLoggerProvider(originalLogsProvider);
116+
}
117+
}
47118
exporter.reset();
48119
if (originalPreloaded === undefined) {
49120
delete process.env[PRELOAD_ENV];
50121
} else {
51122
process.env[PRELOAD_ENV] = originalPreloaded;
52123
}
124+
for (const key of ENDPOINT_ENV_KEYS) {
125+
const value = originalEndpointEnv[key];
126+
if (value === undefined) {
127+
delete process.env[key];
128+
} else {
129+
process.env[key] = value;
130+
}
131+
}
132+
diag.disable();
133+
if (originalOtelGlobals.diag) {
134+
diag.setLogger(originalOtelGlobals.diag, {
135+
logLevel: DiagLogLevel.ALL,
136+
suppressOverrideMessage: true,
137+
});
138+
}
53139
resetDiagnosticEventsForTest();
54140
});
55141

@@ -60,6 +146,24 @@ function spanNamed(spans: ReadableSpan[], name: string) {
60146
return spans.find((span) => span.name === name);
61147
}
62148

149+
function captureOtelDiagnostics(): string[] {
150+
const messages: string[] = [];
151+
const capture = (...args: unknown[]) => {
152+
messages.push(args.map((value) => String(value)).join(" "));
153+
};
154+
diag.setLogger(
155+
{
156+
debug: () => {},
157+
error: capture,
158+
info: () => {},
159+
verbose: () => {},
160+
warn: capture,
161+
},
162+
{ logLevel: DiagLogLevel.ALL, suppressOverrideMessage: true },
163+
);
164+
return messages;
165+
}
166+
63167
// Covers all three completeTrackedLifecycleSpan owners: run.completed,
64168
// harness.run.completed, and message.processed. The mocked suite cannot tell the two id
65169
// spaces apart, so a regression at any one of them is only visible here.
@@ -237,3 +341,133 @@ test("leaves exec spans parentless rather than naming a span nobody exported", a
237341
expect(execSpan).toBeDefined();
238342
expect(execSpan?.parentSpanContext).toBeUndefined();
239343
}, 30_000);
344+
345+
const OTEL_ENDPOINT_SIGNAL_CASES = [
346+
{
347+
signal: "traces",
348+
envKey: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
349+
configKey: "tracesEndpoint",
350+
flags: { traces: true, metrics: false, logs: false },
351+
},
352+
{
353+
signal: "metrics",
354+
envKey: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
355+
configKey: "metricsEndpoint",
356+
flags: { traces: false, metrics: true, logs: false },
357+
},
358+
{
359+
signal: "logs",
360+
envKey: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
361+
configKey: "logsEndpoint",
362+
flags: { traces: false, metrics: false, logs: true },
363+
},
364+
] as const;
365+
366+
const OTEL_ENDPOINT_SECURITY_CASES = OTEL_ENDPOINT_SIGNAL_CASES.flatMap((signal) =>
367+
(
368+
[
369+
"shared configuration",
370+
"signal configuration",
371+
"signal environment",
372+
"shared environment",
373+
"Unicode-prefixed signal environment",
374+
"Unicode-prefixed shared environment",
375+
"path-concatenated shared environment",
376+
"path-concatenated shared configuration",
377+
"path-concatenated signal configuration",
378+
] as const
379+
).map((source) => Object.assign({ source }, signal)),
380+
);
381+
382+
test.each(OTEL_ENDPOINT_SECURITY_CASES)(
383+
"rejects malformed $signal collector $source before the real SDK can expose credentials",
384+
async ({ signal, envKey, configKey, flags, source }) => {
385+
process.env[PRELOAD_ENV] = "0";
386+
const credential = `qa-otel-${signal}-endpoint-password-sentinel`;
387+
const malformedEndpoint = source.startsWith("Unicode-prefixed")
388+
? `\u00a0https://operator:${credential}@collector.example.com/otlp`
389+
: source === "path-concatenated shared environment"
390+
? `https://operator:${credential}@collector.example.com: `
391+
: source.startsWith("path-concatenated")
392+
? `https://operator:${credential}@collector.example.com /`
393+
: `https://operator:${credential}@[`;
394+
const configuredEndpoint = source.endsWith("shared configuration")
395+
? malformedEndpoint
396+
: "https://collector.example.com/otlp";
397+
if (source.endsWith("signal environment")) {
398+
process.env[envKey] = malformedEndpoint;
399+
} else if (source.endsWith("shared environment")) {
400+
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = malformedEndpoint;
401+
}
402+
403+
const diagnostics = captureOtelDiagnostics();
404+
const ctx = createOtelContext(configuredEndpoint, flags);
405+
if (source.endsWith("signal configuration") || source.endsWith("signal environment")) {
406+
ctx.config.diagnostics!.otel![configKey] = source.endsWith("signal configuration")
407+
? malformedEndpoint
408+
: "https://signal.example.com/otlp";
409+
}
410+
ctx.internalDiagnostics!.emit = () => {};
411+
const service = createDiagnosticsOtelService();
412+
let failure: unknown;
413+
try {
414+
await service.start(ctx);
415+
} catch (error) {
416+
failure = error;
417+
} finally {
418+
await service.stop?.(ctx);
419+
}
420+
421+
expect(diagnostics.join("\n")).not.toContain(credential);
422+
expect(failure).toBeInstanceOf(Error);
423+
const startupError = failure as Error;
424+
expect(startupError.message).toBe(
425+
"Configured OpenTelemetry collector endpoint is invalid; check the collector URL",
426+
);
427+
expect(startupError.stack).not.toContain(credential);
428+
expect(startupError).not.toHaveProperty("cause");
429+
expect(JSON.stringify(vi.mocked(ctx.logger.error).mock.calls)).not.toContain(credential);
430+
expect(JSON.stringify(vi.mocked(ctx.logger.warn).mock.calls)).not.toContain(credential);
431+
},
432+
);
433+
434+
test.each([
435+
{
436+
disabledSignal: "metrics",
437+
envKey: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
438+
flags: { traces: true, metrics: false, logs: false },
439+
},
440+
{
441+
disabledSignal: "traces",
442+
envKey: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
443+
flags: { traces: false, metrics: true, logs: false },
444+
},
445+
{
446+
disabledSignal: "logs",
447+
envKey: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
448+
flags: { traces: true, metrics: false, logs: false },
449+
},
450+
{
451+
disabledSignal: "stdout-only logs",
452+
envKey: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
453+
flags: { traces: true, metrics: false, logs: true, logsExporter: "stdout" },
454+
},
455+
] as const)(
456+
"does not auto-create an undeclared $disabledSignal OTLP exporter",
457+
async ({ disabledSignal, envKey, flags }) => {
458+
process.env[PRELOAD_ENV] = "0";
459+
const credential = `qa-otel-${disabledSignal.replaceAll(" ", "-")}-disabled-password`;
460+
process.env[envKey] = `https://operator:${credential}@[`;
461+
const diagnostics = captureOtelDiagnostics();
462+
const ctx = createOtelContext("https://collector.example.com/otlp", flags);
463+
ctx.internalDiagnostics!.emit = () => {};
464+
const service = createDiagnosticsOtelService();
465+
466+
try {
467+
await service.start(ctx);
468+
expect(diagnostics.join("\n")).not.toContain(credential);
469+
} finally {
470+
await service.stop?.(ctx);
471+
}
472+
},
473+
);

0 commit comments

Comments
 (0)