Skip to content

Commit 731d543

Browse files
committed
fix(otel): fail closed when configured TLS material is invalid
1 parent 8d1fe4f commit 731d543

5 files changed

Lines changed: 335 additions & 40 deletions

File tree

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

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
import type {
1111
OtelHttpAgentFactory,
1212
OtelHttpAgentOptions,
13-
OtelLogger,
1413
OtelSignalIdentifier,
1514
} from "./service-types.js";
1615

@@ -75,8 +74,7 @@ function readOtelEnvFile(params: {
7574
signalIdentifier: OtelSignalIdentifier;
7675
signalSuffix: "CERTIFICATE" | "CLIENT_CERTIFICATE" | "CLIENT_KEY";
7776
sharedEnvName: string;
78-
logger: OtelLogger;
79-
warning: string;
77+
label: string;
8078
}): Buffer | undefined {
8179
const signalEnvName = `OTEL_EXPORTER_OTLP_${params.signalIdentifier}_${params.signalSuffix}`;
8280
const filePath =
@@ -86,48 +84,53 @@ function readOtelEnvFile(params: {
8684
return undefined;
8785
}
8886
try {
89-
return readFileSync(nodePath.resolve(process.cwd(), filePath));
87+
const material = readFileSync(nodePath.resolve(process.cwd(), filePath));
88+
if (material.length > 0) {
89+
return material;
90+
}
9091
} catch {
91-
params.logger.warn(`diagnostics-otel: ${params.warning}`);
92-
return undefined;
92+
// Never expose certificate paths or silently downgrade to system trust.
9393
}
94+
throw new Error(
95+
`Configured OpenTelemetry ${params.label} file is missing, empty, or unreadable; refusing insecure export`,
96+
);
9497
}
9598

9699
function normalizeOtelEnvValue(value: string | undefined): string | undefined {
97-
const trimmed = value?.trim();
98-
return trimmed ? trimmed : undefined;
100+
return value?.trim() ? value : undefined;
99101
}
100102

101103
export function resolveOtelHttpAgentOptions(params: {
102104
url: string | undefined;
103105
signalIdentifier: OtelSignalIdentifier;
104-
logger: OtelLogger;
105-
}): OtelHttpAgentFactory | undefined {
106-
const { url, signalIdentifier, logger } = params;
107-
if (!url) {
108-
return undefined;
109-
}
106+
}): OtelHttpAgentFactory | OtelHttpAgentOptions | undefined {
107+
const { url, signalIdentifier } = params;
110108
const ca = readOtelEnvFile({
111109
signalIdentifier,
112110
signalSuffix: "CERTIFICATE",
113111
sharedEnvName: OTEL_EXPORTER_OTLP_CERTIFICATE_ENV,
114-
logger,
115-
warning: "failed to read root certificate file",
112+
label: "TLS root certificate",
116113
});
117114
const cert = readOtelEnvFile({
118115
signalIdentifier,
119116
signalSuffix: "CLIENT_CERTIFICATE",
120117
sharedEnvName: OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE_ENV,
121-
logger,
122-
warning: "failed to read client certificate chain file",
118+
label: "mTLS client certificate",
123119
});
124120
const key = readOtelEnvFile({
125121
signalIdentifier,
126122
signalSuffix: "CLIENT_KEY",
127123
sharedEnvName: OTEL_EXPORTER_OTLP_CLIENT_KEY_ENV,
128-
logger,
129-
warning: "failed to read client certificate private key file",
124+
label: "mTLS client private key",
130125
});
126+
if ((cert === undefined) !== (key === undefined)) {
127+
throw new Error(
128+
"Configured OpenTelemetry mTLS requires both a client certificate and private key; refusing insecure export",
129+
);
130+
}
131+
if (!url) {
132+
return undefined;
133+
}
131134
const agentOptions: OtelHttpAgentOptions = {
132135
keepAlive: true,
133136
...(ca !== undefined ? { ca } : {}),
@@ -136,10 +139,13 @@ export function resolveOtelHttpAgentOptions(params: {
136139
};
137140
try {
138141
const agent = createNodeProxyAgent({ mode: "env", targetUrl: url, agentOptions });
139-
return agent ? () => agent : undefined;
142+
if (agent) {
143+
return () => agent;
144+
}
140145
} catch {
141146
throw new Error("Configured telemetry proxy is invalid or unsupported; refusing direct export");
142147
}
148+
return (ca || cert || key) && new URL(url).protocol === "https:" ? agentOptions : undefined;
143149
}
144150

145151
export function resolveSampleRate(value: number | undefined): number | undefined {

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

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,16 @@ import {
2020
normalizeOtelLogString,
2121
type OtelContentCapturePolicy,
2222
} from "./service-content-normalization.js";
23-
import { errorCategory, formatError, resolveOtelHttpAgentOptions } from "./service-exporter.js";
23+
import { errorCategory, formatError } from "./service-exporter.js";
2424
import {
2525
addTraceAttributes,
2626
contextForTrustedTraceContext,
2727
normalizedTrustedTraceContext,
2828
} from "./service-trace-context.js";
2929
import type {
3030
BuiltOtelLogRecord,
31+
OtelHttpAgentFactory,
32+
OtelHttpAgentOptions,
3133
OtelLogger,
3234
TelemetryExporterDiagnosticEvent,
3335
} from "./service-types.js";
@@ -50,6 +52,7 @@ export function createDiagnosticsLogExporter(params: {
5052
logsEnabled: boolean;
5153
logsToOtlp: boolean;
5254
logsToStdout: boolean;
55+
logHttpAgentOptions?: OtelHttpAgentFactory | OtelHttpAgentOptions;
5356
logUrl?: string;
5457
resource: Resource;
5558
serviceName: string;
@@ -63,6 +66,7 @@ export function createDiagnosticsLogExporter(params: {
6366
logsEnabled,
6467
logsToOtlp,
6568
logsToStdout,
69+
logHttpAgentOptions,
6670
logUrl,
6771
resource,
6872
serviceName,
@@ -86,11 +90,6 @@ export function createDiagnosticsLogExporter(params: {
8690

8791
let otelLogger: { emit: (logRecord: LogRecord) => void } | undefined;
8892
if (logsToOtlp) {
89-
const logHttpAgentOptions = resolveOtelHttpAgentOptions({
90-
url: logUrl,
91-
signalIdentifier: "LOGS",
92-
logger,
93-
});
9493
const logExporter = new OTLPLogExporter({
9594
...(logUrl ? { url: logUrl } : {}),
9695
...(headers ? { headers } : {}),

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

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
// Trace cases use the OPENCLAW_OTEL_PRELOADED seam to retain this file's tracer provider.
99
// Collector-boundary cases start the real NodeSDK, so teardown restores every global SDK
1010
// registration; otherwise a shutdown provider would poison later real-SDK cases.
11+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
12+
import { tmpdir } from "node:os";
13+
import path from "node:path";
1114
import { context, diag, DiagLogLevel, metrics, propagation, trace } from "@opentelemetry/api";
1215
import { logs } from "@opentelemetry/api-logs";
1316
import {
@@ -37,6 +40,18 @@ const ENDPOINT_ENV_KEYS = [
3740
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
3841
"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
3942
"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
43+
"OTEL_EXPORTER_OTLP_CERTIFICATE",
44+
"OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE",
45+
"OTEL_EXPORTER_OTLP_CLIENT_KEY",
46+
"OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE",
47+
"OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE",
48+
"OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY",
49+
"OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE",
50+
"OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE",
51+
"OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY",
52+
"OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE",
53+
"OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE",
54+
"OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY",
4055
"OTEL_LOG_LEVEL",
4156
] as const;
4257
const OTEL_GLOBAL_API_KEY = Symbol.for("opentelemetry.js.api.1");
@@ -471,3 +486,144 @@ test.each([
471486
}
472487
},
473488
);
489+
490+
const OTEL_TLS_MATERIAL_CASES = [
491+
{ suffix: "CERTIFICATE", label: "TLS root certificate" },
492+
{ suffix: "CLIENT_CERTIFICATE", label: "mTLS client certificate" },
493+
{ suffix: "CLIENT_KEY", label: "mTLS client private key" },
494+
] as const;
495+
496+
const OTEL_TLS_FILE_SECURITY_CASES = OTEL_ENDPOINT_SIGNAL_CASES.flatMap((signal) =>
497+
OTEL_TLS_MATERIAL_CASES.flatMap((material) =>
498+
(["shared", "signal"] as const).map((scope) => Object.assign({ scope }, signal, material)),
499+
),
500+
);
501+
502+
test.each(OTEL_TLS_FILE_SECURITY_CASES)(
503+
"refuses the real $signal exporter when its $scope $label file cannot be read",
504+
async ({ signal, suffix, label, scope, flags }) => {
505+
process.env[PRELOAD_ENV] = "0";
506+
const pathSentinel = `qa-otel-${signal}-${suffix.toLowerCase()}-file-sentinel`;
507+
const missingPath = `/definitely-missing/${pathSentinel}.pem`;
508+
const envKey =
509+
scope === "shared"
510+
? `OTEL_EXPORTER_OTLP_${suffix}`
511+
: `OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_${suffix}`;
512+
process.env[envKey] = missingPath;
513+
514+
const diagnostics = captureOtelDiagnostics();
515+
const ctx = createOtelContext("https://collector.example.com/otlp", flags);
516+
ctx.internalDiagnostics!.emit = () => {};
517+
const service = createDiagnosticsOtelService();
518+
let failure: unknown;
519+
try {
520+
await service.start(ctx);
521+
} catch (error) {
522+
failure = error;
523+
} finally {
524+
await service.stop?.(ctx);
525+
}
526+
527+
expect(failure).toBeInstanceOf(Error);
528+
const startupError = failure as Error;
529+
expect(startupError.message).toBe(
530+
`Configured OpenTelemetry ${label} file is missing, empty, or unreadable; refusing insecure export`,
531+
);
532+
expect(startupError.stack).not.toContain(pathSentinel);
533+
expect(startupError).not.toHaveProperty("cause");
534+
expect(diagnostics.join("\n")).not.toContain(pathSentinel);
535+
expect(JSON.stringify(vi.mocked(ctx.logger.error).mock.calls)).not.toContain(pathSentinel);
536+
expect(JSON.stringify(vi.mocked(ctx.logger.warn).mock.calls)).not.toContain(pathSentinel);
537+
},
538+
);
539+
540+
test.each(OTEL_ENDPOINT_SIGNAL_CASES)(
541+
"refuses invalid TLS material before the real default $signal exporter is constructed",
542+
async ({ signal, flags }) => {
543+
process.env[PRELOAD_ENV] = "0";
544+
process.env[`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_CERTIFICATE`] =
545+
"/definitely-missing/qa-otel-default-root.pem";
546+
const ctx = createOtelContext("", flags);
547+
ctx.internalDiagnostics!.emit = () => {};
548+
const service = createDiagnosticsOtelService();
549+
550+
try {
551+
await expect(service.start(ctx)).rejects.toThrow(
552+
"Configured OpenTelemetry TLS root certificate file is missing, empty, or unreadable; refusing insecure export",
553+
);
554+
} finally {
555+
await service.stop?.(ctx);
556+
}
557+
},
558+
);
559+
560+
test.each(
561+
OTEL_ENDPOINT_SIGNAL_CASES.flatMap((signal) =>
562+
OTEL_TLS_MATERIAL_CASES.map((material) => Object.assign({}, signal, material)),
563+
),
564+
)(
565+
"rejects an empty $signal $label file before the SDK can silently downgrade trust",
566+
async ({ signal, suffix, label, flags }) => {
567+
process.env[PRELOAD_ENV] = "0";
568+
const certDir = mkdtempSync(path.join(tmpdir(), "openclaw-otel-empty-tls-"));
569+
const emptyMaterialPath = path.join(certDir, "empty.pem");
570+
writeFileSync(emptyMaterialPath, "");
571+
process.env[`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_${suffix}`] = emptyMaterialPath;
572+
const ctx = createOtelContext("https://collector.example.com/otlp", flags);
573+
ctx.internalDiagnostics!.emit = () => {};
574+
const service = createDiagnosticsOtelService();
575+
576+
try {
577+
await expect(service.start(ctx)).rejects.toThrow(
578+
`Configured OpenTelemetry ${label} file is missing, empty, or unreadable; refusing insecure export`,
579+
);
580+
} finally {
581+
await service.stop?.(ctx);
582+
rmSync(certDir, { force: true, recursive: true });
583+
}
584+
},
585+
);
586+
587+
test.each(OTEL_ENDPOINT_SIGNAL_CASES)(
588+
"rejects the raw whitespace-padded $signal TLS certificate path the SDK cannot read",
589+
async ({ signal, flags }) => {
590+
process.env[PRELOAD_ENV] = "0";
591+
process.env[`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_CERTIFICATE`] = ` ${process.execPath} `;
592+
const ctx = createOtelContext("https://collector.example.com/otlp", flags);
593+
ctx.internalDiagnostics!.emit = () => {};
594+
const service = createDiagnosticsOtelService();
595+
596+
try {
597+
await expect(service.start(ctx)).rejects.toThrow(
598+
"Configured OpenTelemetry TLS root certificate file is missing, empty, or unreadable; refusing insecure export",
599+
);
600+
} finally {
601+
await service.stop?.(ctx);
602+
}
603+
},
604+
);
605+
606+
test.each(
607+
OTEL_ENDPOINT_SIGNAL_CASES.flatMap((signal) =>
608+
(["CLIENT_CERTIFICATE", "CLIENT_KEY"] as const).map((suffix) =>
609+
Object.assign({ suffix }, signal),
610+
),
611+
),
612+
)(
613+
"rejects the real $signal exporter when only $suffix mTLS material is configured",
614+
async ({ signal, suffix, flags }) => {
615+
process.env[PRELOAD_ENV] = "0";
616+
process.env[`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_${suffix}`] = process.execPath;
617+
const ctx = createOtelContext("https://collector.example.com/otlp", flags);
618+
ctx.internalDiagnostics!.emit = () => {};
619+
const service = createDiagnosticsOtelService();
620+
621+
try {
622+
await expect(service.start(ctx)).rejects.toThrow(
623+
"Configured OpenTelemetry mTLS requires both a client certificate and private key; refusing insecure export",
624+
);
625+
} finally {
626+
await service.stop?.(ctx);
627+
}
628+
},
629+
);

0 commit comments

Comments
 (0)