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 " ;
1313import {
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
2934const 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
3153let exporter : InMemorySpanExporter ;
3254let provider : BasicTracerProvider ;
3355let 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
3566beforeEach ( ( ) => {
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(() => {
4384afterEach ( 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