-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathUIMetricsEndpoint.test.ts
More file actions
1746 lines (1658 loc) · 62 KB
/
Copy pathUIMetricsEndpoint.test.ts
File metadata and controls
1746 lines (1658 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file Tests for the Prometheus /metrics endpoint on UIHttpServer (issue #851)
* @description End-to-end behavior, security inheritance, PII reject-list, exposition-format escaping and the cardinality soft cap warning.
*/
import type { IncomingMessage, Server } from 'node:http'
import type { mock } from 'node:test'
import type { Registry } from 'prom-client'
import assert from 'node:assert/strict'
import { afterEach, beforeEach, describe, it } from 'node:test'
import type {
ChargingStationData,
TemplateStatistics,
UIServerConfiguration,
} from '../../../src/types/index.js'
import {
AbstractUIServer,
isMetricsAllowedLabelName,
METRICS_ALLOWED_LABEL_NAMES,
METRICS_SOFT_CAP_WARN_PREFIX,
METRICS_SOFT_SAMPLE_CAP,
} from '../../../src/charging-station/ui-server/AbstractUIServer.js'
import { UIHttpServer } from '../../../src/charging-station/ui-server/UIHttpServer.js'
import { UIWebSocketServer } from '../../../src/charging-station/ui-server/UIWebSocketServer.js'
import { BaseError } from '../../../src/exception/index.js'
import {
ApplicationProtocol,
AuthenticationType,
ConnectorStatusEnum,
OCPP16AvailabilityType,
OCPPVersion,
} from '../../../src/types/index.js'
import { logger } from '../../../src/utils/index.js'
import { standardCleanup } from '../../helpers/TestLifecycleHelpers.js'
import {
awaitFinish,
createMockBootstrap,
createMockIncomingMessage,
createMockUIServerConfiguration,
drainResponses,
MockServerResponse,
} from './UIServerTestUtils.js'
// eslint-disable-next-line @typescript-eslint/no-deprecated
class TestableUIHttpServer extends UIHttpServer {
public constructor (config: UIServerConfiguration) {
// eslint-disable-next-line @typescript-eslint/no-deprecated
super(config, createMockBootstrap())
}
public addStation (data: ChargingStationData): void {
this.setChargingStationData(data.stationInfo.hashId, data)
}
public emitRequest (req: IncomingMessage, res: MockServerResponse): void {
const httpServer = Reflect.get(this, 'httpServer') as {
emit: (eventName: string, req: IncomingMessage, res: MockServerResponse) => boolean
listen: (...args: unknown[]) => unknown
removeAllListeners: () => void
}
httpServer.emit('request', req, res)
}
public override getMetricsRegistry (): Registry | undefined {
// eslint-disable-next-line @typescript-eslint/no-deprecated
return super.getMetricsRegistry()
}
public mockListen (t: { mock: { method: typeof mock.method } }): void {
const httpServer = Reflect.get(this, 'httpServer') as object
t.mock.method(httpServer as never, 'listen' as never, ((): unknown => httpServer) as never)
}
}
const createMetricsConfig = (
overrides: Partial<UIServerConfiguration> = {}
): UIServerConfiguration =>
createMockUIServerConfiguration({
metrics: { enabled: true },
options: { host: '127.0.0.1', port: 0 },
type: ApplicationProtocol.HTTP,
...overrides,
})
const buildStationData = (
hashId: string,
overrides: Partial<ChargingStationData> = {}
): ChargingStationData =>
({
connectors: [
{
connectorId: 1,
connectorStatus: {
availability: OCPP16AvailabilityType.Operative,
status: ConnectorStatusEnum.Available,
transactionStarted: false,
},
evseId: 1,
},
],
evses: [],
ocppConfiguration: { configurationKey: [] },
started: true,
stationInfo: {
chargePointModel: 'TestModel',
chargePointVendor: 'TestVendor',
chargingStationId: hashId,
hashId,
maximumAmperage: 32,
maximumPower: 22000,
ocppVersion: OCPPVersion.VERSION_16,
templateIndex: 0,
templateName: 'test-template',
},
supervisionUrl: 'ws://test.example.com/OCPP16',
timestamp: 1_700_000_000_000,
wsState: 1,
...overrides,
}) as ChargingStationData
const enrichBootstrap = (server: TestableUIHttpServer, version = '4.9.0'): void => {
const bootstrap = server.getBootstrap()
const templateStats: TemplateStatistics = {
added: 1,
configured: 5,
indexes: new Set([0]),
provisioned: 2,
started: 1,
}
Reflect.set(bootstrap, 'getState', () => ({
configuration: undefined,
started: true,
templateStatistics: new Map<string, TemplateStatistics>([['test-template', templateStats]]),
version,
}))
}
const buildMetricsRequest = (overrides: Partial<IncomingMessage> = {}): IncomingMessage =>
createMockIncomingMessage({
complete: true,
headers: { host: 'localhost' },
method: 'GET',
socket: { encrypted: false, remoteAddress: '127.0.0.1' } as never,
url: '/metrics',
...overrides,
})
const populateLiveState = (
server: TestableUIHttpServer
): { uiSvc: { stop: () => void; stopCalled: number } } => {
const uiSvc = {
stop (): void {
this.stopCalled++
},
stopCalled: 0,
}
;(Reflect.get(server, 'uiServices') as Map<unknown, unknown>).set('1.1', uiSvc)
;(Reflect.get(server, 'responseHandlers') as Map<unknown, unknown>).set('uuid-probe', {})
;(Reflect.get(server, 'chargingStations') as Map<string, unknown>).set('h-probe', {
hashId: 'h-probe',
})
;(Reflect.get(server, 'chargingStationTemplates') as Set<string>).add('tpl-probe')
return { uiSvc }
}
await describe('UIHttpServer /metrics endpoint (issue #851)', async () => {
let server: TestableUIHttpServer
beforeEach(() => {
server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server)
})
afterEach(() => {
server.stop()
standardCleanup()
})
await it('should serve Prometheus exposition on GET /metrics when enabled', async t => {
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
assert.strictEqual(res.statusCode, 200)
assert.match(res.headers['Content-Type'] ?? '', /^text\/plain;\s*version=0\.0\.4/)
assert.match(res.body ?? '', /^# HELP /m)
assert.match(res.body ?? '', /^# TYPE /m)
})
await it('should fall through to 400 on GET /metrics when metrics block is absent', t => {
const plainServer = new TestableUIHttpServer(
createMockUIServerConfiguration({ type: ApplicationProtocol.HTTP })
)
enrichBootstrap(plainServer)
plainServer.mockListen(t)
try {
plainServer.start()
const res = new MockServerResponse()
plainServer.emitRequest(buildMetricsRequest(), res)
assert.strictEqual(res.statusCode, 400)
} finally {
plainServer.stop()
}
})
await it('should fall through to 400 on GET /metrics when metrics.enabled is false', t => {
const offServer = new TestableUIHttpServer(
createMockUIServerConfiguration({
metrics: { enabled: false },
type: ApplicationProtocol.HTTP,
})
)
enrichBootstrap(offServer)
offServer.mockListen(t)
try {
offServer.start()
const res = new MockServerResponse()
offServer.emitRequest(buildMetricsRequest(), res)
assert.strictEqual(res.statusCode, 400)
} finally {
offServer.stop()
}
})
await it('should serve global gauges from Bootstrap.getState().templateStatistics', async t => {
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
assert.match(body, /^simulator_charging_stations_configured_total\s+5$/m)
assert.match(body, /^simulator_charging_stations_provisioned_total\s+2$/m)
assert.match(body, /^simulator_charging_stations_added_total\s+1$/m)
assert.match(body, /^simulator_charging_stations_started_total\s+1$/m)
assert.match(body, /^simulator_charging_station_templates_total\s+1$/m)
})
await it('should serve per-station gauges from chargingStations Map', async t => {
server.addStation(buildStationData('station-T5'))
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
assert.match(body, /simulator_station_started\{[^}]*hash_id="station-T5"[^}]*\}\s+1/)
assert.match(body, /simulator_station_ws_state\{[^}]*hash_id="station-T5"[^}]*\}\s+1/)
assert.match(body, /simulator_station_connectors_total\{[^}]*hash_id="station-T5"[^}]*\}\s+1/)
})
await it('should serve per-connector status_info one-hot', async t => {
server.addStation(buildStationData('station-T6'))
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
const line = body
.split('\n')
.find(l => l.startsWith('simulator_connector_status_info{') && l.endsWith(' 1'))
assert.ok(line != null, 'simulator_connector_status_info value line not found')
assert.match(line, /hash_id="station-T6"/)
assert.match(line, /connector_id="1"/)
assert.match(line, /status="Available"/)
})
await it('should reject POST /metrics with non-200 (existing 400 path)', t => {
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest({ method: 'POST' }), res)
assert.notStrictEqual(res.statusCode, 200)
})
await it('should inherit AccessPolicy denial — 403 on non-loopback without TLS', t => {
const gatedServer = new TestableUIHttpServer(
createMetricsConfig({
accessPolicy: {
allowedHosts: ['gateway.example.com'],
allowedOrigins: [],
allowLoopbackProxy: false,
requireTlsForNonLoopback: true,
trustedProxies: [],
},
})
)
enrichBootstrap(gatedServer)
gatedServer.mockListen(t)
try {
gatedServer.start()
const res = new MockServerResponse()
gatedServer.emitRequest(
buildMetricsRequest({
headers: { host: 'gateway.example.com' },
socket: { encrypted: false, remoteAddress: '203.0.113.10' } as never,
}),
res
)
assert.strictEqual(res.statusCode, 403)
} finally {
gatedServer.stop()
}
})
await it('should inherit rate-limit — eventual 429 on burst', t => {
server.mockListen(t)
server.start()
const statuses: (number | undefined)[] = []
for (let i = 0; i < 200; i++) {
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
statuses.push(res.statusCode)
}
assert.ok(
statuses.some(s => s === 429),
`Expected at least one 429 in burst on allowed /metrics path; saw ${JSON.stringify(statuses.slice(0, 5))}…`
)
})
await it('should inherit BASIC_AUTH — 401 on missing credentials', t => {
const authServer = new TestableUIHttpServer(
createMetricsConfig({
authentication: {
enabled: true,
password: 'pw',
type: AuthenticationType.BASIC_AUTH,
username: 'user',
},
})
)
enrichBootstrap(authServer)
authServer.mockListen(t)
try {
authServer.start()
const res = new MockServerResponse()
authServer.emitRequest(buildMetricsRequest(), res)
assert.strictEqual(res.statusCode, 401)
assert.strictEqual(res.headers['WWW-Authenticate'], 'Basic realm=users')
} finally {
authServer.stop()
}
})
await it('should inherit BASIC_AUTH — 200 on valid credentials', async t => {
const authServer = new TestableUIHttpServer(
createMetricsConfig({
authentication: {
enabled: true,
password: 'pw',
type: AuthenticationType.BASIC_AUTH,
username: 'user',
},
})
)
enrichBootstrap(authServer)
authServer.mockListen(t)
try {
authServer.start()
const credentials = Buffer.from('user:pw').toString('base64')
const res = new MockServerResponse()
authServer.emitRequest(
buildMetricsRequest({
headers: { authorization: `Basic ${credentials}`, host: 'localhost' },
}),
res
)
await awaitFinish(res)
assert.strictEqual(res.statusCode, 200)
} finally {
authServer.stop()
}
})
await it('should not leak PII (idTag, serial, supervisionUrl) in body', async t => {
server.addStation(
buildStationData('station-T12', {
connectors: [
{
connectorId: 1,
connectorStatus: {
authorizeIdTag: 'SECRET-IDTAG-12345',
availability: OCPP16AvailabilityType.Operative,
localAuthorizeIdTag: 'SECRET-LOCAL-IDTAG',
MeterValues: [],
status: ConnectorStatusEnum.Available,
transactionIdTag: 'SECRET-TX-IDTAG',
},
evseId: 1,
},
],
stationInfo: {
baseName: 'test',
chargeBoxSerialNumber: 'SECRET-SERIAL-1',
chargePointModel: 'TestModel',
chargePointSerialNumber: 'SECRET-CP-SERIAL',
chargePointVendor: 'TestVendor',
chargingStationId: 'station-T12',
hashId: 'station-T12',
iccid: 'SECRET-ICCID',
imsi: 'SECRET-IMSI',
meterSerialNumber: 'SECRET-METER',
ocppVersion: OCPPVersion.VERSION_16,
templateIndex: 0,
templateName: 'test-template',
},
supervisionUrl: 'ws://user:password@evil.example.com/OCPP',
})
)
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
for (const secret of [
'SECRET-IDTAG-12345',
'SECRET-LOCAL-IDTAG',
'SECRET-TX-IDTAG',
'SECRET-SERIAL-1',
'SECRET-CP-SERIAL',
'SECRET-METER',
'SECRET-ICCID',
'SECRET-IMSI',
'user:password',
'evil.example.com',
]) {
assert.ok(!body.includes(secret), `Body must not contain '${secret}'`)
}
assert.ok(!body.includes('://'), 'Body must not contain any URL scheme')
})
await it('should escape adversarial label values (no injected # HELP)', async t => {
server.addStation(
buildStationData('station-T13', {
stationInfo: {
baseName: 'test',
chargePointModel: 'TestModel',
chargePointVendor: 'TestVendor',
chargingStationId:
'evil"\n# HELP fake_metric injected\n# TYPE fake_metric gauge\nfake_metric 999\n',
hashId: 'station-T13',
ocppVersion: OCPPVersion.VERSION_16,
templateIndex: 0,
templateName: 'test-template',
},
})
)
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
assert.ok(
!/^fake_metric\b/m.test(body),
'Adversarial label injection produced a fake metric line'
)
assert.ok(
!/^# HELP fake_metric/m.test(body),
'Adversarial label injection produced a fake HELP line'
)
})
await it('should not register a UUID in responseHandlers', t => {
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
const responseHandlers = Reflect.get(server, 'responseHandlers') as Map<string, unknown>
assert.strictEqual(responseHandlers.size, 0)
})
await it('should clear registry on stop()', t => {
server.mockListen(t)
server.start()
server.stop()
assert.strictEqual(server.getMetricsRegistry(), undefined)
})
await it('should fire soft-warn when sample count exceeds METRICS_SOFT_SAMPLE_CAP', async t => {
// Each station emits ≈ 14 samples on the per-station gauges (no connectors yet)
// plus 1 sample on info, that is ~15 per station. To cross 5 000 we add 400+ stations.
const stationCount = Math.max(400, Math.ceil(METRICS_SOFT_SAMPLE_CAP / 15) + 50)
for (let i = 0; i < stationCount; i++) {
server.addStation(buildStationData(`station-T16-${i.toString()}`))
}
const warnSpy = t.mock.method(logger, 'warn', () => undefined)
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
assert.strictEqual(res.statusCode, 200)
const matchingCalls = warnSpy.mock.calls.filter(call => {
const message: unknown = call.arguments[0]
return typeof message === 'string' && message.includes(METRICS_SOFT_CAP_WARN_PREFIX)
})
assert.ok(
matchingCalls.length > 0,
`Expected at least one logger.warn 'soft cap' call after ${stationCount.toString()} stations; got ${warnSpy.mock.calls.length.toString()} warn calls total`
)
})
await it('should omit simulator_station_ws_state line when wsState is undefined', async t => {
server.addStation(buildStationData('station-Mws', { wsState: undefined }))
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
assert.ok(
!/simulator_station_ws_state\{[^}]*hash_id="station-Mws"[^}]*\}/.test(body),
'simulator_station_ws_state line must be absent when wsState is undefined'
)
assert.match(body, /simulator_station_started\{[^}]*hash_id="station-Mws"[^}]*\}\s+1/)
})
await it('should serve per-connector metrics in EVSE-mode (OCPP 2.0.x) station', async t => {
server.addStation(
buildStationData('station-T18', {
connectors: [],
evses: [
{
evseId: 1,
evseStatus: {
availability: OCPP16AvailabilityType.Operative,
connectors: new Map([
[
1,
{
availability: OCPP16AvailabilityType.Operative,
MeterValues: [],
status: ConnectorStatusEnum.Available,
},
],
]),
MeterValues: [],
},
},
] as ChargingStationData['evses'],
})
)
server.mockListen(t)
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
assert.match(body, /simulator_station_connectors_total\{[^}]*hash_id="station-T18"[^}]*\}\s+1/)
const statusLine = body
.split('\n')
.find(
l =>
l.startsWith('simulator_connector_status_info{') &&
l.includes('hash_id="station-T18"') &&
l.endsWith(' 1')
)
assert.ok(statusLine != null, 'simulator_connector_status_info value line not found')
assert.match(statusLine, /connector_id="1"/)
assert.match(statusLine, /status="Available"/)
})
await it('should detect off-by-one at soft cap boundary (strict-greater-than semantics)', async t => {
const warnSpy = t.mock.method(logger, 'warn', () => undefined)
// Phase 1: probe — very high cap, count actual samples produced (no warn expected).
const probeServer = new TestableUIHttpServer(
createMetricsConfig({ metrics: { enabled: true, softSampleCap: 1_000_000 } })
)
enrichBootstrap(probeServer)
for (let i = 0; i < 5; i++) {
probeServer.addStation(buildStationData(`station-T19-probe-${i.toString()}`))
}
probeServer.mockListen(t)
probeServer.start()
const probeRes = new MockServerResponse()
probeServer.emitRequest(buildMetricsRequest(), probeRes)
await awaitFinish(probeRes)
const probedSampleCount = (probeRes.body ?? '')
.split('\n')
.filter(line => line.length > 0 && !line.startsWith('#')).length
probeServer.stop()
warnSpy.mock.resetCalls()
assert.ok(probedSampleCount > 0, 'probe scrape produced no samples')
// Phase 2: cap === probedSampleCount → NO warn (count IS NOT > cap, strict).
const exactServer = new TestableUIHttpServer(
createMetricsConfig({ metrics: { enabled: true, softSampleCap: probedSampleCount } })
)
enrichBootstrap(exactServer)
for (let i = 0; i < 5; i++) {
exactServer.addStation(buildStationData(`station-T19-exact-${i.toString()}`))
}
exactServer.mockListen(t)
exactServer.start()
const exactRes = new MockServerResponse()
exactServer.emitRequest(buildMetricsRequest(), exactRes)
await awaitFinish(exactRes)
const exactSoftCapCalls = warnSpy.mock.calls.filter(call => {
const message: unknown = call.arguments[0]
return typeof message === 'string' && message.includes(METRICS_SOFT_CAP_WARN_PREFIX)
}).length
exactServer.stop()
assert.strictEqual(
exactSoftCapCalls,
0,
`Expected 0 'soft cap' warns at exact boundary (count=cap=${probedSampleCount.toString()}); got ${exactSoftCapCalls.toString()} — would fail if '>' becomes '>='`
)
warnSpy.mock.resetCalls()
// Phase 3: cap === probedSampleCount - 1 → WARN (count IS > cap).
const belowServer = new TestableUIHttpServer(
createMetricsConfig({
metrics: { enabled: true, softSampleCap: probedSampleCount - 1 },
})
)
enrichBootstrap(belowServer)
for (let i = 0; i < 5; i++) {
belowServer.addStation(buildStationData(`station-T19-below-${i.toString()}`))
}
belowServer.mockListen(t)
belowServer.start()
const belowRes = new MockServerResponse()
belowServer.emitRequest(buildMetricsRequest(), belowRes)
await awaitFinish(belowRes)
const belowSoftCapCalls = warnSpy.mock.calls.filter(call => {
const message: unknown = call.arguments[0]
return typeof message === 'string' && message.includes(METRICS_SOFT_CAP_WARN_PREFIX)
}).length
belowServer.stop()
assert.ok(
belowSoftCapCalls >= 1,
`Expected ≥1 'soft cap' warn when cap=${(probedSampleCount - 1).toString()} < count=${probedSampleCount.toString()}; got ${belowSoftCapCalls.toString()}`
)
})
await it('should serialize concurrent /metrics scrapes (no shared-counter race)', async t => {
// R1+R2 lock: two simultaneous GET /metrics must each produce a complete,
// well-formed body and a coherent sample count. Without `metricsScrapeChain`
// serialization, both scrapes' `collect()` callbacks would interleave on
// `metricsSampleCount`, racing the soft cap check and corrupting the
// exposition body. Configure the cap to the per-scrape sample count so an
// honest serialized run produces ZERO warns; a broken (concurrent) run
// would either spuriously warn (counter doubled) or truncate.
const probeServer = new TestableUIHttpServer(
createMetricsConfig({ metrics: { enabled: true, softSampleCap: 1_000_000 } })
)
enrichBootstrap(probeServer)
for (let i = 0; i < 5; i++) {
probeServer.addStation(buildStationData(`station-T20-probe-${i.toString()}`))
}
probeServer.mockListen(t)
probeServer.start()
const probeRes = new MockServerResponse()
probeServer.emitRequest(buildMetricsRequest(), probeRes)
await awaitFinish(probeRes)
const probedSampleCount = (probeRes.body ?? '')
.split('\n')
.filter(line => line.length > 0 && !line.startsWith('#')).length
probeServer.stop()
assert.ok(probedSampleCount > 0, 'probe scrape produced no samples')
const warnSpy = t.mock.method(logger, 'warn', () => undefined)
const concurrentServer = new TestableUIHttpServer(
createMetricsConfig({ metrics: { enabled: true, softSampleCap: probedSampleCount } })
)
enrichBootstrap(concurrentServer)
for (let i = 0; i < 5; i++) {
concurrentServer.addStation(buildStationData(`station-T20-${i.toString()}`))
}
concurrentServer.mockListen(t)
concurrentServer.start()
const resA = new MockServerResponse()
const resB = new MockServerResponse()
concurrentServer.emitRequest(buildMetricsRequest(), resA)
concurrentServer.emitRequest(buildMetricsRequest(), resB)
await drainResponses([resA, resB])
concurrentServer.stop()
assert.strictEqual(resA.statusCode, 200)
assert.strictEqual(resB.statusCode, 200)
const bodyA = resA.body ?? ''
const bodyB = resB.body ?? ''
const sampleLines = (body: string): number =>
body.split('\n').filter(line => line.length > 0 && !line.startsWith('#')).length
assert.strictEqual(
sampleLines(bodyA),
probedSampleCount,
`scrape A must emit exactly ${probedSampleCount.toString()} sample lines (no truncation, no double-count); got ${sampleLines(bodyA).toString()}`
)
assert.strictEqual(
sampleLines(bodyB),
probedSampleCount,
`scrape B must emit exactly ${probedSampleCount.toString()} sample lines (no truncation, no double-count); got ${sampleLines(bodyB).toString()}`
)
const softCapCalls = warnSpy.mock.calls.filter(call => {
const message: unknown = call.arguments[0]
return typeof message === 'string' && message.includes(METRICS_SOFT_CAP_WARN_PREFIX)
}).length
assert.strictEqual(
softCapCalls,
0,
`Expected 0 'soft cap' warns under serialized concurrent scrapes (cap=count=${probedSampleCount.toString()}); got ${softCapCalls.toString()} — would fail if metricsScrapeChain serialization were removed`
)
})
await it('should not warn about transport-restriction when metrics.enabled=true && type=ws (issue #1917)', t => {
const warnSpy = t.mock.method(logger, 'warn', () => undefined)
const wsServer = new UIWebSocketServer(
createMockUIServerConfiguration({
metrics: { enabled: true },
options: { host: 'localhost', port: 0 },
type: ApplicationProtocol.WS,
}),
createMockBootstrap()
)
try {
const matchingCalls = warnSpy.mock.calls.filter(call => {
const message: unknown = call.arguments[0]
return (
typeof message === 'string' &&
/metrics\.enabled=true/i.test(message) &&
/honored only/i.test(message)
)
})
assert.strictEqual(
matchingCalls.length,
0,
`Metrics endpoint is now transport-agnostic; transport-restriction warning must not be emitted. Saw ${matchingCalls.length.toString()} matching warn(s).`
)
} finally {
wsServer.stop()
void AbstractUIServer
}
})
await it('start() runs buildMetricsRegistryIfEnabled THEN attachTransport THEN httpServer.listen (strict template-method ordering)', t => {
const server = new TestableUIHttpServer(createMetricsConfig())
const order: string[] = []
const proto = Reflect.getPrototypeOf(server) as {
attachTransport: () => void
buildMetricsRegistryIfEnabled: () => void
}
const origBuild = proto.buildMetricsRegistryIfEnabled.bind(server)
const origAttach = proto.attachTransport.bind(server)
;(
server as unknown as { buildMetricsRegistryIfEnabled: () => void }
).buildMetricsRegistryIfEnabled = () => {
order.push('build')
origBuild()
}
;(server as unknown as { attachTransport: () => void }).attachTransport = () => {
order.push('attach')
origAttach()
}
const httpServer = Reflect.get(server, 'httpServer') as {
listen: (...args: unknown[]) => unknown
}
t.mock.method(
httpServer as never,
'listen' as never,
((): unknown => {
order.push('listen')
return httpServer
}) as never
)
try {
server.start()
assert.deepStrictEqual(
order,
['build', 'attach', 'listen'],
'strict template-method ordering: build → attach → listen'
)
} finally {
server.stop()
}
})
await it('start() is one-shot — a second call throws BaseError and does not re-attach', t => {
const server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server)
server.mockListen(t)
try {
server.start()
const registry1 = server.getMetricsRegistry()
const httpServer = Reflect.get(server, 'httpServer') as {
listenerCount: (event: string) => number
}
const listeners1 = httpServer.listenerCount('request')
assert.throws(
() => {
server.start()
},
(err: unknown) => err instanceof BaseError,
'second start() must throw BaseError'
)
assert.strictEqual(
server.getMetricsRegistry(),
registry1,
'metricsRegistry reference must be preserved after the rejected second start()'
)
assert.strictEqual(
httpServer.listenerCount('request'),
listeners1,
'request listeners must not be doubled by the rejected second start()'
)
} finally {
server.stop()
}
})
await it('Content-Length equals UTF-8 byte count of body, not codepoint count (non-ASCII version label)', async t => {
const server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server, '1.0.0-✓')
server.mockListen(t)
try {
server.start()
const res = new MockServerResponse()
server.emitRequest(buildMetricsRequest(), res)
await awaitFinish(res)
const body = res.body ?? ''
assert.ok(body.includes('1.0.0-✓'), 'non-ASCII version must propagate into exposition body')
const checkMarkOccurrences = (body.match(/✓/gu) ?? []).length
assert.ok(checkMarkOccurrences >= 1, 'at least one ✓ must appear in the body')
const charLen = body.length
const byteLen = Buffer.byteLength(body, 'utf8')
assert.notStrictEqual(charLen, byteLen, 'non-ASCII body must have byteLen !== charLen')
assert.strictEqual(
byteLen - charLen,
checkMarkOccurrences * 2,
'each ✓ contributes +2 bytes (U+2713 = 3-byte UTF-8 vs 1 codepoint)'
)
assert.strictEqual(
Number(res.headers['Content-Length']),
byteLen,
'Content-Length header must equal UTF-8 byte length, not codepoint count'
)
} finally {
server.stop()
}
})
await it('stop() invokes detachTransport BEFORE stopHttpServer (lifecycle symmetry)', t => {
const server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server)
server.mockListen(t)
const order: string[] = []
const proto = Reflect.getPrototypeOf(server) as {
detachTransport: () => void
stopHttpServer: () => void
}
const origDetach = proto.detachTransport.bind(server)
const origStopHttp = proto.stopHttpServer.bind(server)
;(server as unknown as { detachTransport: () => void }).detachTransport = (): void => {
order.push('detachTransport')
origDetach()
}
;(server as unknown as { stopHttpServer: () => void }).stopHttpServer = (): void => {
order.push('stopHttpServer')
origStopHttp()
}
server.start()
server.stop()
assert.deepStrictEqual(
order,
['detachTransport', 'stopHttpServer'],
'detachTransport must be called before stopHttpServer for symmetric teardown'
)
})
await it('handleMetricsHttpRequest error path is a no-op when res.writableEnded after the scrape rejected post-end()', async t => {
const server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server)
server.mockListen(t)
try {
server.start()
const res = new MockServerResponse()
let writeHeadCount = 0
const origWriteHead = res.writeHead.bind(res)
;(
res as MockServerResponse & {
writeHead: (status: number, headers?: Record<string, string>) => MockServerResponse
}
).writeHead = (status: number, headers?: Record<string, string>): MockServerResponse => {
writeHeadCount += 1
return origWriteHead(status, headers)
}
Reflect.set(
server,
'runMetricsScrape',
(_req: IncomingMessage, r: MockServerResponse): Promise<void> => {
r.writeHead(200, { 'Content-Type': 'text/plain' }).end('partial')
return Promise.reject(new Error('post-end fail'))
}
)
server.emitRequest(buildMetricsRequest(), res)
await new Promise<void>(resolve => {
setImmediate(resolve)
})
await new Promise<void>(resolve => {
setImmediate(resolve)
})
assert.strictEqual(res.statusCode, 200, 'partial 200 must NOT be rewritten to 500')
assert.strictEqual(
writeHeadCount,
1,
'writeHead must run exactly once — no double-write after end()'
)
assert.strictEqual(res.body, 'partial', 'body must not be overwritten by the error path')
} finally {
server.stop()
}
})
await it('stop() removes all httpServer listeners AND clears the registry when httpServer.listening === true', t => {
const server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server)
server.mockListen(t)
server.start()
const httpServer = Reflect.get(server, 'httpServer') as {
close: () => unknown
listenerCount: (event: string) => number
listening: boolean
}
t.mock.method(httpServer as never, 'close' as never, ((): unknown => httpServer) as never)
Object.defineProperty(httpServer, 'listening', { configurable: true, value: true })
const requestListenersBefore = httpServer.listenerCount('request')
assert.ok(requestListenersBefore >= 1, 'precondition: request listener attached')
assert.notStrictEqual(server.getMetricsRegistry(), undefined)
server.stop()
assert.strictEqual(
httpServer.listenerCount('request'),
0,
'stopHttpServer must removeAllListeners() when listening was true'
)
assert.strictEqual(
server.getMetricsRegistry(),
undefined,
'metricsRegistry reference must be released by stop()'
)
})
await it('exposition body emits only labels listed in METRICS_ALLOWED_LABEL_NAMES (PII guardian)', t => {
const server = new TestableUIHttpServer(createMetricsConfig())
enrichBootstrap(server)
server.addStation(buildStationData('station-PII'))
server.mockListen(t)
try {
server.start()
const registry = server.getMetricsRegistry()
assert(registry !== undefined, 'precondition: registry must be built')
const metrics = registry.getMetricsAsArray()
const leaked: string[] = []
for (const metric of metrics) {
const declared = (metric as { labelNames?: readonly string[] }).labelNames ?? []
for (const labelName of declared) {
if (!isMetricsAllowedLabelName(labelName)) leaked.push(labelName)
}
}
assert.deepStrictEqual(
leaked,
[],
`Label PII allowlist violated. Labels not in METRICS_ALLOWED_LABEL_NAMES: ${leaked.join(', ')}. If intentional, add to METRICS_ALLOWED_LABEL_NAMES with security review.`
)
} finally {
server.stop()
}
})
await it('METRICS_ALLOWED_LABEL_NAMES is a runtime-immutable frozen tuple', () => {
assert.ok(
Object.isFrozen(METRICS_ALLOWED_LABEL_NAMES),
'METRICS_ALLOWED_LABEL_NAMES must be Object.frozen (honest on arrays, blocks push/length/index)'
)