-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathweb.spec.js
More file actions
1039 lines (814 loc) · 33.4 KB
/
Copy pathweb.spec.js
File metadata and controls
1039 lines (814 loc) · 33.4 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
'use strict'
const assert = require('node:assert/strict')
const { describe, it, beforeEach } = require('mocha')
const sinon = require('sinon')
require('../../setup/core')
const tagsExt = require('../../../../../ext/tags')
const ERROR = tagsExt.ERROR
const HTTP_CLIENT_IP = tagsExt.HTTP_CLIENT_IP
const HTTP_ENDPOINT = tagsExt.HTTP_ENDPOINT
const HTTP_REQUEST_HEADERS = tagsExt.HTTP_REQUEST_HEADERS
const HTTP_RESPONSE_HEADERS = tagsExt.HTTP_RESPONSE_HEADERS
const HTTP_ROUTE = tagsExt.HTTP_ROUTE
const RESOURCE_NAME = tagsExt.RESOURCE_NAME
describe('plugins/util/web', () => {
let web
let tracer
let span
let req
let res
let end
let config
let tags
beforeEach(() => {
req = {
method: 'GET',
headers: {
host: 'localhost',
date: 'now',
},
}
end = sinon.stub()
res = {
statusCode: 200,
end,
getHeader: sinon.stub(),
getHeaders: sinon.stub().returns({}),
setHeader: sinon.spy(),
writeHead: () => {},
}
res.getHeader.withArgs('server').returns('test')
config = { hooks: {} }
tracer = require('../../..').init({ plugins: false })
web = require('../../../src/plugins/util/web')
config = web.normalizeConfig(config)
})
describe('normalizeConfig', () => {
it('should set the correct defaults', () => {
const config = web.normalizeConfig({})
assert.ok(Object.hasOwn(config, 'headers'))
assert.ok(Array.isArray(config.headers))
assert.ok(Object.hasOwn(config, 'validateStatus'))
assert.strictEqual(typeof config.validateStatus, 'function')
assert.strictEqual(config.validateStatus(200), true)
assert.strictEqual(config.validateStatus(499), true)
assert.strictEqual(config.validateStatus(500), false)
assert.strictEqual(config.validateStatus(599), false)
assert.ok(Object.hasOwn(config, 'hooks'))
assert.ok(typeof config.hooks === 'object' && config.hooks !== null)
assert.ok(Object.hasOwn(config.hooks, 'request'))
assert.strictEqual(typeof config.hooks.request, 'function')
assert.strictEqual(config.queryStringObfuscation, true)
})
it('should use the shared config if set', () => {
const config = web.normalizeConfig({
headers: ['test'],
DD_TRACE_HTTP_SERVER_ERROR_STATUSES: '200',
validateStatus: code => code === 200,
hooks: {
request: () => 'test',
},
})
assert.deepStrictEqual(config.headers, [['test', undefined]])
assert.strictEqual(config.validateStatus(200), true)
assert.ok(Object.hasOwn(config, 'hooks'))
assert.strictEqual(config.hooks.request(), 'test')
})
it('should mark configured HTTP server status codes as errors', () => {
const config = web.normalizeConfig({
DD_TRACE_HTTP_SERVER_ERROR_STATUSES: ' 200 - 201, 202, 250-249 ',
})
assert.strictEqual(config.validateStatus(199), true)
assert.strictEqual(config.validateStatus(200), false)
assert.strictEqual(config.validateStatus(201), false)
assert.strictEqual(config.validateStatus(202), false)
assert.strictEqual(config.validateStatus(203), true)
assert.strictEqual(config.validateStatus(248), true)
assert.strictEqual(config.validateStatus(249), false)
assert.strictEqual(config.validateStatus(250), false)
assert.strictEqual(config.validateStatus(251), true)
assert.strictEqual(config.validateStatus(500), true)
})
it('should combine overlapping HTTP server status code ranges', () => {
const config = web.normalizeConfig({
DD_TRACE_HTTP_SERVER_ERROR_STATUSES: '250-300,420,240-260',
})
assert.strictEqual(config.validateStatus(239), true)
assert.strictEqual(config.validateStatus(240), false)
assert.strictEqual(config.validateStatus(255), false)
})
it('should only configure valid HTTP status codes', () => {
const config = web.normalizeConfig({ DD_TRACE_HTTP_SERVER_ERROR_STATUSES: '100,599' })
assert.strictEqual(config.validateStatus(100), false)
assert.strictEqual(config.validateStatus(599), false)
})
for (const value of ['500-599', ' 500 - 599 ']) {
it(`should use the default matcher for the explicit default range ${JSON.stringify(value)}`, () => {
const config = web.normalizeConfig({ DD_TRACE_HTTP_SERVER_ERROR_STATUSES: value })
assert.strictEqual(config.validateStatus(499), true)
assert.strictEqual(config.validateStatus(500), false)
assert.strictEqual(config.validateStatus(599), false)
})
}
for (const value of ['', '99', '600', '99-100', '599-600', '600-599', '200,,202', '200-']) {
it(`should use the default HTTP server error statuses for ${JSON.stringify(value)}`, () => {
const config = web.normalizeConfig({ DD_TRACE_HTTP_SERVER_ERROR_STATUSES: value })
assert.strictEqual(config.validateStatus(499), true)
assert.strictEqual(config.validateStatus(500), false)
assert.strictEqual(config.validateStatus(599), false)
})
}
it('should use the default HTTP server error statuses for a non-string value', () => {
const config = web.normalizeConfig({ DD_TRACE_HTTP_SERVER_ERROR_STATUSES: 200 })
assert.strictEqual(config.validateStatus(499), true)
assert.strictEqual(config.validateStatus(500), false)
})
it('should apply configured HTTP server error statuses when validateStatus is invalid', () => {
const config = web.normalizeConfig({
DD_TRACE_HTTP_SERVER_ERROR_STATUSES: '200',
validateStatus: true,
})
assert.strictEqual(config.validateStatus(200), false)
assert.strictEqual(config.validateStatus(500), true)
})
describe('queryStringObfuscation', () => {
it('should keep booleans as is', () => {
const config = web.normalizeConfig({
queryStringObfuscation: false,
})
assert.strictEqual(config.queryStringObfuscation, false)
})
it('should change to false when passed empty string', () => {
const config = web.normalizeConfig({
queryStringObfuscation: '',
})
assert.strictEqual(config.queryStringObfuscation, false)
})
it('should change to true when passed ".*"', () => {
const config = web.normalizeConfig({
queryStringObfuscation: '.*',
})
assert.strictEqual(config.queryStringObfuscation, true)
})
it('should convert to regex when passed valid string', () => {
const config = web.normalizeConfig({
queryStringObfuscation: 'a*',
})
assert.ok('queryStringObfuscation' in config)
assert.deepStrictEqual(config.queryStringObfuscation, /a*/gi)
})
it('should default to true when passed a bad regex', () => {
const config = web.normalizeConfig({
queryStringObfuscation: '(?)',
})
assert.strictEqual(config.queryStringObfuscation, true)
})
})
describe('clientIpEnabled', () => {
it('leaves extractIp undefined when clientIpEnabled is not set', () => {
const config = web.normalizeConfig({})
assert.strictEqual(config.extractIp, undefined)
})
it('resolves extractIp to the ip_extractor implementation when clientIpEnabled is true', () => {
const config = web.normalizeConfig({ clientIpEnabled: true })
const { extractIp } = require('../../../src/plugins/util/ip_extractor')
assert.strictEqual(config.extractIp, extractIp)
})
})
})
describe('startSpan client IP extraction', () => {
it('tags the span with the extracted client IP when clientIpEnabled is set', () => {
const config = web.normalizeConfig({ clientIpEnabled: true })
req.headers['x-forwarded-for'] = '8.8.8.8'
const span = web.startSpan(tracer, config, req, res, 'test.request')
assert.strictEqual(span.context().getTag(HTTP_CLIENT_IP), '8.8.8.8')
})
it('leaves the client IP tag unset when clientIpEnabled is not set', () => {
const config = web.normalizeConfig({})
req.headers['x-forwarded-for'] = '8.8.8.8'
const span = web.startSpan(tracer, config, req, res, 'test.request')
assert.strictEqual(span.context().hasTag(HTTP_CLIENT_IP), false)
})
// Regression for the per-plugin scoping fix: a later normalizeConfig call
// for a different plugin must not disable IP extraction on the earlier
// plugin's config. Used to fail because extractIp lived on the module.
it('keeps extraction enabled on the first config after a second plugin normalizes without clientIpEnabled',
() => {
const enabledConfig = web.normalizeConfig({ clientIpEnabled: true })
web.normalizeConfig({})
req.headers['x-forwarded-for'] = '8.8.8.8'
const span = web.startSpan(tracer, enabledConfig, req, res, 'test.request')
assert.strictEqual(span.context().getTag(HTTP_CLIENT_IP), '8.8.8.8')
})
})
describe('extractIncomingServerContext', () => {
it('passes propagation headers to the configured tracer extractor', () => {
const headers = {
traceparent: '00-00000000000000000000000000000001-0000000000000002-01',
}
const context = {}
const tracer = {
extract: sinon.stub().returns(context),
}
assert.strictEqual(web.extractIncomingServerContext(tracer, headers), context)
sinon.assert.calledOnceWithExactly(tracer.extract, 'http_headers', headers)
})
it('returns the configured extractor result', () => {
const headers = {
traceparent: '00-00000000000000000000000000000001-0000000000000002-01',
}
const tracer = {
extract: sinon.stub(),
}
assert.strictEqual(web.extractIncomingServerContext(tracer, headers), undefined)
sinon.assert.calledOnceWithExactly(tracer.extract, 'http_headers', headers)
})
it('normalizes Web Headers before extraction', () => {
const entries = {
'x-datadog-trace-id': '123',
'x-datadog-parent-id': '456',
traceparent: '00-00000000000000000000000000000001-0000000000000002-01',
}
const headers = {
get: name => entries[name.toLowerCase()],
[Symbol.iterator]: function * () {
yield * Object.entries(entries)
},
}
const context = {}
const tracer = {
extract: sinon.stub().returns(context),
}
assert.strictEqual(web.extractIncomingServerContext(tracer, headers), context)
sinon.assert.calledOnceWithExactly(tracer.extract, 'http_headers', entries)
})
})
describe('OTel semantics network.peer.address', () => {
// The HTTP tag renames happen centrally in span_format; only network.peer.address
// is set here (the socket isn't available at serialization).
it('sets network.peer.address from the socket when OTel semantics are enabled', () => {
const otelConfig = web.normalizeConfig({ DD_TRACE_OTEL_SEMANTICS_ENABLED: true })
req.socket = { remoteAddress: '10.0.0.1' }
const span = web.startSpan(tracer, otelConfig, req, res, 'test.request')
assert.strictEqual(span.context().getTag('network.peer.address'), '10.0.0.1')
})
it('does not set network.peer.address when OTel semantics are disabled', () => {
req.socket = { remoteAddress: '10.0.0.1' }
const span = web.startSpan(tracer, config, req, res, 'test.request')
assert.strictEqual(span.context().hasTag('network.peer.address'), false)
})
})
describe('root', () => {
it('should return null when not yet instrumented', () => {
assert.strictEqual(web.root(req), null)
})
})
describe('active', () => {
it('should return null when not yet instrumented', () => {
assert.strictEqual(web.active(req), null)
})
})
describe('addError', () => {
beforeEach(() => {
span = tracer.startSpan('test.request')
tags = span.context().getTags()
web.patch(req)
const context = web.getContext(req)
context.span = span
context.req = req
context.res = res
context.config = config
})
it('should add an error to the request span', () => {
const error = new Error('boom')
web.addError(req, error)
web.addStatusError(req, 500)
assert.strictEqual(tags[ERROR], error)
})
it('should override an existing error', () => {
const error = new Error('boom')
web.addError(req, new Error('prrr'))
web.addError(req, error)
web.addStatusError(req, 500)
assert.strictEqual(tags[ERROR], error)
})
})
describe('addStatusError', () => {
beforeEach(() => {
span = tracer.startSpan('test.request')
tags = span.context().getTags()
web.patch(req)
const context = web.getContext(req)
context.span = span
context.req = req
context.res = res
context.config = config
})
it('should flag the request as an error', () => {
web.addStatusError(req, 500)
assert.strictEqual(tags[ERROR], true)
})
it('should only flag requests as an error for configured status codes', () => {
config.validateStatus = () => true
web.addStatusError(req, 500)
assert.ok(!(ERROR in tags))
})
})
describe('setConfig service', () => {
const SVC_SRC_KEY = '_dd.svc_src'
beforeEach(() => {
req.url = '/'
web.plugin = null
})
it('writes service.name from config.service onto the span', () => {
const customConfig = web.normalizeConfig({ service: 'integration-svc' })
const span = web.startSpan(tracer, customConfig, req, res, 'test.request')
const spanContext = span.context()
assert.strictEqual(spanContext.getTag('service.name'), 'integration-svc')
})
it('stamps the integration claim so a user override is flagged manual at finish', () => {
const customConfig = web.normalizeConfig({ service: 'integration-svc' })
const span = web.startSpan(tracer, customConfig, req, res, 'test.request')
const spanContext = span.context()
span.setTag('service.name', 'user-override')
span.finish()
assert.strictEqual(spanContext.getTag('service.name'), 'user-override')
assert.strictEqual(spanContext.getTag(SVC_SRC_KEY), 'm')
})
it('does not stamp manual when the user does not override the integration service', () => {
const customConfig = web.normalizeConfig({ service: 'integration-svc' })
const span = web.startSpan(tracer, customConfig, req, res, 'test.request')
const spanContext = span.context()
span.finish()
assert.strictEqual(spanContext.getTag('service.name'), 'integration-svc')
assert.strictEqual(spanContext.getTag(SVC_SRC_KEY), undefined)
})
})
describe('allowlistFilter', () => {
beforeEach(() => {
config = { allowlist: ['/_okay'] }
config = web.normalizeConfig(config)
})
it('should not filter the url', () => {
const filtered = config.filter('/_okay')
assert.strictEqual(filtered, true)
})
it('should filter the url', () => {
const filtered = config.filter('/_notokay')
assert.strictEqual(filtered, false)
})
})
describe('whitelistFilter', () => {
beforeEach(() => {
config = { whitelist: ['/_okay'] }
config = web.normalizeConfig(config)
})
it('should not filter the url', () => {
const filtered = config.filter('/_okay')
assert.strictEqual(filtered, true)
})
it('should filter the url', () => {
const filtered = config.filter('/_notokay')
assert.strictEqual(filtered, false)
})
})
describe('blocklistFilter', () => {
beforeEach(() => {
config = { blocklist: ['/_notokay'] }
config = web.normalizeConfig(config)
})
it('should not filter the url', () => {
const filtered = config.filter('/_okay')
assert.strictEqual(filtered, true)
})
it('should filter the url', () => {
const filtered = config.filter('/_notokay')
assert.strictEqual(filtered, false)
})
})
describe('blacklistFilter', () => {
beforeEach(() => {
config = { blacklist: ['/_notokay'] }
config = web.normalizeConfig(config)
})
it('should not filter the url', () => {
const filtered = config.filter('/_okay')
assert.strictEqual(filtered, true)
})
it('should filter the url', () => {
const filtered = config.filter('/_notokay')
assert.strictEqual(filtered, false)
})
})
describe('http.endpoint tagging', () => {
beforeEach(() => {
span = tracer.startSpan('test.request')
tags = span.context().getTags()
req.url = '/'
web.patch(req)
const context = web.getContext(req)
context.span = span
context.req = req
context.res = res
context.config = config
})
it('should derive http.endpoint when no framework route is available', () => {
config = web.normalizeConfig({ resourceRenamingEnabled: true })
req.method = 'GET'
req.url = '/api/orders/12345/items?foo=bar'
const context = web.getContext(req)
context.config = config
web.finishAll(context)
assert.ok(!Object.hasOwn(tags, HTTP_ROUTE))
assert.strictEqual(tags[HTTP_ENDPOINT], '/api/orders/{param:int}/items')
})
it('should not set http.endpoint when resource renaming is disabled', () => {
config = web.normalizeConfig({ resourceRenamingEnabled: false })
req.method = 'GET'
req.url = '/api/orders/12345/items'
const context = web.getContext(req)
context.config = config
web.finishAll(context)
assert.ok(!Object.hasOwn(tags, HTTP_ENDPOINT))
assert.ok(!Object.hasOwn(tags, HTTP_ROUTE))
assert.strictEqual(tags[RESOURCE_NAME], 'GET')
})
})
describe('security testing headers', () => {
const SCAN_TAG = 'http.request.headers.x-datadog-endpoint-scan'
const TEST_TAG = 'http.request.headers.x-datadog-security-test'
beforeEach(() => {
span = tracer.startSpan('test.request')
tags = span.context().getTags()
req.url = '/'
web.patch(req)
const context = web.getContext(req)
context.span = span
context.req = req
context.res = res
context.config = config
})
it('should tag x-datadog-endpoint-scan and x-datadog-security-test on the entry span', () => {
req.headers['x-datadog-endpoint-scan'] = 'scan-uuid-1'
req.headers['x-datadog-security-test'] = 'test-uuid-2'
req.headers['x-other-header'] = 'ignored'
web.finishAll(web.getContext(req))
assert.deepStrictEqual(
{ scan: tags[SCAN_TAG], test: tags[TEST_TAG], other: tags['http.request.headers.x-other-header'] },
{ scan: 'scan-uuid-1', test: 'test-uuid-2', other: undefined }
)
})
it('should not set tags when the headers are not in the request', () => {
web.finishAll(web.getContext(req))
assert.deepStrictEqual(
{ scan: tags[SCAN_TAG], test: tags[TEST_TAG] },
{ scan: undefined, test: undefined }
)
})
it('should tag the headers even when DD_TRACE_HEADER_TAGS is set to unrelated headers', () => {
config = web.normalizeConfig({ headers: ['x-other-header'] })
const context = web.getContext(req)
context.config = config
req.headers['x-datadog-endpoint-scan'] = 'scan-uuid'
req.headers['x-datadog-security-test'] = 'test-uuid'
req.headers['x-other-header'] = 'other'
web.finishAll(context)
assert.deepStrictEqual(
{
scan: tags[SCAN_TAG],
test: tags[TEST_TAG],
other: tags['http.request.headers.x-other-header'],
},
{ scan: 'scan-uuid', test: 'test-uuid', other: 'other' }
)
})
it('should tag the headers even when their value is an empty string', () => {
req.headers['x-datadog-endpoint-scan'] = ''
req.headers['x-datadog-security-test'] = 'ok'
web.finishAll(web.getContext(req))
assert.deepStrictEqual(
{ scan: tags[SCAN_TAG], test: tags[TEST_TAG] },
{ scan: '', test: 'ok' }
)
})
})
describe('setRouteOrEndpointTag http.route fast path', () => {
let context
beforeEach(() => {
span = tracer.startSpan('test.request')
tags = span.context().getTags()
req.url = '/'
web.patch(req)
context = web.getContext(req)
context.span = span
context.req = req
context.res = res
context.config = config
})
it('leaves http.route unset when no segments were collected', () => {
context.paths = []
web.setRouteOrEndpointTag(req)
assert.ok(!Object.hasOwn(tags, HTTP_ROUTE))
})
it('uses the single segment directly without entering Array.join', () => {
context.paths = ['/users/:id']
web.setRouteOrEndpointTag(req)
assert.strictEqual(tags[HTTP_ROUTE], '/users/:id')
})
it('leaves http.route unset for a single empty-string segment', () => {
context.paths = ['']
web.setRouteOrEndpointTag(req)
assert.ok(!Object.hasOwn(tags, HTTP_ROUTE))
})
it('joins two segments byte-identical to the legacy join shape', () => {
context.paths = ['/api', '/users/:id']
web.setRouteOrEndpointTag(req)
assert.strictEqual(tags[HTTP_ROUTE], '/api/users/:id')
})
it('joins three segments byte-identical to the legacy join shape', () => {
context.paths = ['/api', '/users', '/:id/items']
web.setRouteOrEndpointTag(req)
assert.strictEqual(tags[HTTP_ROUTE], '/api/users/:id/items')
})
})
describe('route resolved after the AppSec pre-finish endpoint fallback', () => {
let context
beforeEach(() => {
config = web.normalizeConfig({ resourceRenamingEnabled: true })
req.method = 'GET'
req.url = '/users/123'
span = web.startSpan(tracer, config, req, res, 'test.request')
tags = span.context().getTags()
context = web.getContext(req)
})
it('keeps http.route when the framework resolves the route after http.endpoint was stamped', () => {
// AppSec's incomingHttpRequestEnd hook stamps http.endpoint while the
// framework route is still unresolved.
web.setRouteOrEndpointTag(req)
assert.ok(Object.hasOwn(tags, HTTP_ENDPOINT))
assert.ok(!Object.hasOwn(tags, HTTP_ROUTE))
// The framework resolves the route between the pre-finish hook and finish.
web.setRoute(req, '/users/:id')
web.finishAll(context)
assert.strictEqual(tags[HTTP_ROUTE], '/users/:id')
assert.strictEqual(tags[RESOURCE_NAME], 'GET /users/:id')
})
it('uses http.route alone when the route resolves before the pre-finish hook', () => {
web.setRoute(req, '/users/:id')
web.setRouteOrEndpointTag(req)
assert.ok(!Object.hasOwn(tags, HTTP_ENDPOINT))
web.finishAll(context)
assert.strictEqual(tags[HTTP_ROUTE], '/users/:id')
assert.ok(!Object.hasOwn(tags, HTTP_ENDPOINT))
assert.strictEqual(tags[RESOURCE_NAME], 'GET /users/:id')
})
it('keeps the http.endpoint fallback when no route ever resolves', () => {
web.setRouteOrEndpointTag(req)
const endpoint = tags[HTTP_ENDPOINT]
assert.ok(endpoint)
web.finishAll(context)
assert.strictEqual(tags[HTTP_ENDPOINT], endpoint)
assert.ok(!Object.hasOwn(tags, HTTP_ROUTE))
assert.strictEqual(tags[RESOURCE_NAME], 'GET')
})
})
describe('configured header tagging across the request lifecycle', () => {
const USER_AGENT_TAG = `${HTTP_REQUEST_HEADERS}.user-agent`
const SERVER_TAG = `${HTTP_RESPONSE_HEADERS}.server`
beforeEach(() => {
req.url = '/users'
req.headers['user-agent'] = 'test'
})
it('honours headers added to the plugin config after startSpan', () => {
const httpConfig = web.normalizeConfig({})
const frameworkConfig = web.normalizeConfig({ headers: ['user-agent', 'server'] })
web.startSpan(tracer, httpConfig, req, res, 'test.request')
span = web.root(req)
tags = span.context().getTags()
assert.ok(Object.hasOwn(tags, 'http.url'))
assert.ok(!Object.hasOwn(tags, USER_AGENT_TAG))
web.setFramework(req, 'test-framework', frameworkConfig)
web.finishAll(web.getContext(req))
assert.strictEqual(tags[USER_AGENT_TAG], 'test')
assert.strictEqual(tags[SERVER_TAG], 'test')
})
it('still tags headers when the http-side config already lists them', () => {
const httpConfig = web.normalizeConfig({ headers: ['user-agent'] })
web.startSpan(tracer, httpConfig, req, res, 'test.request')
span = web.root(req)
tags = span.context().getTags()
web.finishAll(web.getContext(req))
assert.strictEqual(tags[USER_AGENT_TAG], 'test')
})
})
describe('normalizeConfig clientIpEnabled', () => {
beforeEach(() => {
req.url = '/'
req.headers['x-forwarded-for'] = '203.0.113.5'
})
it('does not tag http.client_ip when clientIpEnabled is not set', () => {
const httpConfig = web.normalizeConfig({})
web.startSpan(tracer, httpConfig, req, res, 'test.request')
span = web.root(req)
web.finishAll(web.getContext(req))
assert.ok(!span.context().hasTag(HTTP_CLIENT_IP))
})
it('tags http.client_ip when clientIpEnabled is true', () => {
const httpConfig = web.normalizeConfig({ clientIpEnabled: true })
web.startSpan(tracer, httpConfig, req, res, 'test.request')
span = web.root(req)
web.finishAll(web.getContext(req))
assert.strictEqual(span.context().getTag(HTTP_CLIENT_IP), '203.0.113.5')
})
})
describe('wrapWriteHead', () => {
const ALLOW_HEADERS = 'access-control-allow-headers'
const ALLOW_ORIGIN = 'access-control-allow-origin'
let context
beforeEach(() => {
span = tracer.startSpan('test.request')
web.patch(req)
context = web.getContext(req)
context.span = span
context.req = req
context.res = res
context.config = config
})
it('does not touch CORS headers for non-OPTIONS requests', () => {
req.method = 'GET'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id'
res.getHeaders.returns({ [ALLOW_ORIGIN]: '*' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(res.writeHead.firstCall.args, [200])
})
it('skips allow-header tagging on OPTIONS when the origin is not allowed', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://evil.example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id'
res.getHeaders.returns({ [ALLOW_ORIGIN]: 'https://good.example.com' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(res.writeHead.firstCall.args, [200])
})
it('merges datadog allow-headers on OPTIONS when allow-origin is *', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] =
'x-datadog-trace-id, x-datadog-parent-id, x-other'
res.getHeaders.returns({ [ALLOW_ORIGIN]: '*' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, { [ALLOW_HEADERS]: 'x-datadog-parent-id,x-datadog-trace-id' }]
)
})
it('merges W3C tracing allow-headers on OPTIONS when allow-origin is *', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'baggage, traceparent, tracestate, x-other'
res.getHeaders.returns({ [ALLOW_ORIGIN]: '*' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, { [ALLOW_HEADERS]: 'baggage,traceparent,tracestate' }]
)
})
it('honours headers passed as the second writeHead argument', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id'
res.getHeaders.returns({})
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200, { [ALLOW_ORIGIN]: 'https://example.com' })
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, { [ALLOW_ORIGIN]: 'https://example.com', [ALLOW_HEADERS]: 'x-datadog-trace-id' }]
)
})
it('honours headers passed as the third writeHead argument with a status message', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id'
res.getHeaders.returns({})
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200, 'OK', { [ALLOW_ORIGIN]: '*' })
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, 'OK', { [ALLOW_ORIGIN]: '*', [ALLOW_HEADERS]: 'x-datadog-trace-id' }]
)
})
it('honours headers passed as a flat array in rawHeaders format', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id'
res.getHeaders.returns({})
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200, [ALLOW_ORIGIN, '*'])
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, { [ALLOW_ORIGIN]: '*', [ALLOW_HEADERS]: 'x-datadog-trace-id' }]
)
})
it('treats lowercase req.method "options" as OPTIONS', () => {
req.method = 'options'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id'
res.getHeaders.returns({ [ALLOW_ORIGIN]: '*' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, { [ALLOW_HEADERS]: 'x-datadog-trace-id' }]
)
})
it('preserves existing allow-headers and de-duplicates datadog additions', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'x-datadog-trace-id, x-datadog-trace-id'
res.getHeaders.returns({
[ALLOW_ORIGIN]: '*',
[ALLOW_HEADERS]: 'content-type, x-datadog-trace-id',
})
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,
[200, { [ALLOW_HEADERS]: 'content-type,x-datadog-trace-id' }]
)
})
it('leaves allow-headers untouched when no supported tracing header was requested', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
req.headers['access-control-request-headers'] = 'content-type, x-other'
res.getHeaders.returns({ [ALLOW_ORIGIN]: '*' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 200)
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(res.writeHead.firstCall.args, [200])
})
it('delegates to the original writeHead with the same arguments', () => {
req.method = 'OPTIONS'
req.headers.origin = 'https://example.com'
res.getHeaders.returns({ [ALLOW_ORIGIN]: '*' })
res.writeHead = sinon.spy()
const wrapped = web.wrapWriteHead(context)
wrapped.call(res, 204, 'No Content', { 'x-test': '1' })
assert.ok(res.writeHead.calledOnce)
assert.deepStrictEqual(
res.writeHead.firstCall.args,