-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathGatewayBridgeSpecification.groovy
More file actions
1689 lines (1445 loc) · 56.6 KB
/
GatewayBridgeSpecification.groovy
File metadata and controls
1689 lines (1445 loc) · 56.6 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
package com.datadog.appsec.gateway
import com.datadog.appsec.AppSecSystem
import com.datadog.appsec.api.security.ApiSecurityDownstreamSampler
import com.datadog.appsec.api.security.ApiSecuritySamplerImpl
import com.datadog.appsec.config.TraceSegmentPostProcessor
import com.datadog.appsec.event.EventDispatcher
import com.datadog.appsec.event.EventProducerService
import com.datadog.appsec.event.data.DataBundle
import com.datadog.appsec.event.data.KnownAddresses
import com.datadog.appsec.report.AppSecEvent
import com.datadog.appsec.report.AppSecEventWrapper
import datadog.trace.api.ProductTraceSource
import datadog.trace.api.TagMap
import datadog.trace.api.appsec.HttpClientRequest
import datadog.trace.api.appsec.HttpClientResponse
import datadog.trace.api.appsec.MediaType
import datadog.trace.api.config.GeneralConfig
import datadog.trace.api.function.TriConsumer
import datadog.trace.api.function.TriFunction
import datadog.appsec.api.blocking.BlockingContentType
import datadog.trace.api.gateway.BlockResponseFunction
import datadog.trace.api.gateway.Flow
import datadog.trace.api.gateway.IGSpanInfo
import datadog.trace.api.gateway.RequestContext
import datadog.trace.api.gateway.RequestContextSlot
import datadog.trace.api.gateway.SubscriptionService
import datadog.trace.api.http.StoredBodySupplier
import datadog.trace.api.internal.TraceSegment
import datadog.trace.api.telemetry.LoginEvent
import datadog.trace.api.telemetry.RuleType
import datadog.trace.api.telemetry.WafMetricCollector
import datadog.trace.bootstrap.instrumentation.api.AgentSpan
import datadog.trace.bootstrap.instrumentation.api.Tags
import datadog.trace.bootstrap.instrumentation.api.URIDataAdapter
import datadog.trace.bootstrap.instrumentation.api.URIDataAdapterBase
import datadog.trace.test.util.DDSpecification
import spock.lang.Shared
import java.util.function.BiConsumer
import java.util.function.BiFunction
import java.util.function.Function
import java.util.function.Supplier
import static datadog.trace.api.gateway.Events.EVENTS
import static datadog.trace.api.telemetry.LoginEvent.LOGIN_FAILURE
import static datadog.trace.api.telemetry.LoginEvent.LOGIN_SUCCESS
import static datadog.trace.api.telemetry.LoginEvent.SIGN_UP
@SuppressWarnings('UnusedVariable')
class GatewayBridgeSpecification extends DDSpecification {
@Shared
protected static final ORIGINAL_METRIC_COLLECTOR = WafMetricCollector.get()
private static final String USER_ID = 'user'
SubscriptionService ig = Mock()
EventDispatcher eventDispatcher = Mock()
AppSecRequestContext arCtx = new AppSecRequestContext()
TraceSegment traceSegment = Mock()
RequestContext ctx = new RequestContext() {
final AppSecRequestContext data = arCtx
BlockResponseFunction blockResponseFunction
@Override
Object getData(RequestContextSlot slot) {
slot == RequestContextSlot.APPSEC ? data : null
}
@Override
final TraceSegment getTraceSegment() {
GatewayBridgeSpecification.this.traceSegment
}
@Override
def getOrCreateMetaStructTop(String key, Function defaultValue) {
return null
}
@Override
void close() throws IOException {}
}
EventProducerService.DataSubscriberInfo nonEmptyDsInfo = {
EventProducerService.DataSubscriberInfo i = Stub()
i.empty >> false
i
}()
EventProducerService.DataSubscriberInfo emptyDsInfo = Stub {
isEmpty() >> true
}
TraceSegmentPostProcessor pp = Mock()
ApiSecuritySamplerImpl requestSampler = Mock(ApiSecuritySamplerImpl)
ApiSecurityDownstreamSampler downstreamSampler = Mock(ApiSecurityDownstreamSampler)
GatewayBridge bridge = new GatewayBridge(ig, eventDispatcher, () -> requestSampler, downstreamSampler, [pp])
Supplier<Flow<AppSecRequestContext>> requestStartedCB
BiFunction<RequestContext, AgentSpan, Flow<Void>> requestEndedCB
TriConsumer<RequestContext, String, String> reqHeaderCB
Function<RequestContext, Flow<Void>> reqHeadersDoneCB
TriFunction<RequestContext, String, URIDataAdapter, Flow<Void>> requestMethodURICB
BiFunction<RequestContext, Map<String, Object>, Flow<Void>> pathParamsCB
TriFunction<RequestContext, String, Integer, Flow<Void>> requestSocketAddressCB
BiFunction<RequestContext, String, Flow<Void>> requestInferredAddressCB
BiFunction<RequestContext, StoredBodySupplier, Void> requestBodyStartCB
BiFunction<RequestContext, StoredBodySupplier, Flow<Void>> requestBodyDoneCB
BiFunction<RequestContext, Object, Flow<Void>> requestBodyProcessedCB
BiFunction<RequestContext, Object, Flow<Void>> responseBodyCB
BiFunction<RequestContext, Integer, Flow<Void>> responseStartedCB
TriConsumer<RequestContext, String, String> respHeaderCB
Function<RequestContext, Flow<Void>> respHeadersDoneCB
BiFunction<RequestContext, String, Flow<Void>> grpcServerMethodCB
BiFunction<RequestContext, Object, Flow<Void>> grpcServerRequestMessageCB
BiFunction<RequestContext, Map<String, Object>, Flow<Void>> graphqlServerRequestMessageCB
BiConsumer<RequestContext, String> databaseConnectionCB
BiFunction<RequestContext, String, Flow<Void>> databaseSqlQueryCB
BiFunction<RequestContext, HttpClientRequest, Flow<Void>> httpClientRequestCB
BiFunction<RequestContext, HttpClientResponse, Flow<Void>> httpClientResponseCB
BiFunction<RequestContext, Long, Flow<Void>> httpClientSamplingCB
BiFunction<RequestContext, String, Flow<Void>> fileLoadedCB
BiFunction<RequestContext, String, Flow<Void>> requestSessionCB
BiFunction<RequestContext, String[], Flow<Void>> execCmdCB
BiFunction<RequestContext, String, Flow<Void>> shellCmdCB
BiFunction<RequestContext, String, Flow<Void>> userCB
TriFunction<RequestContext, LoginEvent, String, Flow<Void>> loginEventCB
BiConsumer<RequestContext, String> httpRouteCB
WafMetricCollector wafMetricCollector = Mock(WafMetricCollector)
void setup() {
callInitAndCaptureCBs()
AppSecSystem.active = true
WafMetricCollector.INSTANCE = wafMetricCollector
}
void cleanup() {
WafMetricCollector.INSTANCE = ORIGINAL_METRIC_COLLECTOR
bridge.stop()
}
void 'request_start produces appsec context and publishes event'() {
when:
Flow<AppSecRequestContext> startFlow = requestStartedCB.get()
then:
Object producedCtx = startFlow.getResult()
producedCtx instanceof AppSecRequestContext
startFlow.action == Flow.Action.Noop.INSTANCE
}
void 'request_start returns null context if appsec is disabled'() {
setup:
AppSecSystem.active = false
when:
Flow<AppSecRequestContext> startFlow = requestStartedCB.get()
then:
Object producedCtx = startFlow.getResult()
producedCtx == null
0 * _._
cleanup:
AppSecSystem.active = true
}
void 'request_end closes context reports attacks and publishes event'() {
AppSecEvent event = Mock()
AppSecRequestContext mockAppSecCtx = Mock(AppSecRequestContext)
mockAppSecCtx.requestHeaders >> ['accept': ['header_value']]
mockAppSecCtx.responseHeaders >> [
'some-header' : ['123'],
'content-type': ['text/html; charset=UTF-8']]
RequestContext mockCtx = Stub(RequestContext) {
getData(RequestContextSlot.APPSEC) >> mockAppSecCtx
getTraceSegment() >> traceSegment
}
IGSpanInfo spanInfo = Mock(AgentSpan)
when:
def flow = requestEndedCB.apply(mockCtx, spanInfo)
then:
1 * spanInfo.getTags() >> TagMap.fromMap(['http.client_ip': '1.1.1.1'])
1 * mockAppSecCtx.transferCollectedEvents() >> [event]
1 * mockAppSecCtx.peerAddress >> '2001::1'
1 * mockAppSecCtx.close()
1 * traceSegment.setTagTop("_dd.appsec.enabled", 1)
1 * traceSegment.setTagTop("_dd.runtime_family", "jvm")
1 * traceSegment.setTagTop('appsec.event', true)
1 * traceSegment.setDataTop('appsec', new AppSecEventWrapper([event]))
1 * traceSegment.setTagTop('http.request.headers.accept', 'header_value')
1 * traceSegment.setTagTop('http.response.headers.content-type', 'text/html; charset=UTF-8')
1 * traceSegment.setTagTop('network.client.ip', '2001::1')
1 * mockAppSecCtx.isWafBlocked()
1 * mockAppSecCtx.hasWafErrors()
1 * mockAppSecCtx.getWafTimeouts()
1 * mockAppSecCtx.isWafRequestBlockFailure()
1 * mockAppSecCtx.isWafRateLimited()
1 * mockAppSecCtx.isWafTruncated()
1 * wafMetricCollector.wafRequest(_, _, _, _, _, _, _) // call waf request metric
flow.result == null
flow.action == Flow.Action.Noop.INSTANCE
}
void 'actor ip calculated from headers'() {
AppSecRequestContext mockAppSecCtx = Mock(AppSecRequestContext)
mockAppSecCtx.requestHeaders >> [
'x-real-ip': ['10.0.0.1'],
forwarded : ['for=127.0.0.1', 'for="[::1]", for=8.8.8.8'],
]
RequestContext mockCtx = Stub(RequestContext) {
getData(RequestContextSlot.APPSEC) >> mockAppSecCtx
getTraceSegment() >> traceSegment
}
IGSpanInfo spanInfo = Mock(AgentSpan)
when:
requestEndedCB.apply(mockCtx, spanInfo)
then:
1 * mockAppSecCtx.transferCollectedEvents() >> [Stub(AppSecEvent)]
1 * spanInfo.getTags() >> TagMap.fromMap(['http.client_ip': '8.8.8.8'])
1 * traceSegment.setTagTop('actor.ip', '8.8.8.8')
}
void 'request_end writes response headers even when no appsec events'() {
AppSecRequestContext mockAppSecCtx = Mock(AppSecRequestContext)
mockAppSecCtx.requestHeaders >> [:]
mockAppSecCtx.responseHeaders >> ['content-type': ['text/plain']]
RequestContext mockCtx = Stub(RequestContext) {
getData(RequestContextSlot.APPSEC) >> mockAppSecCtx
getTraceSegment() >> traceSegment
}
IGSpanInfo spanInfo = Mock(AgentSpan)
when:
def flow = requestEndedCB.apply(mockCtx, spanInfo)
then:
1 * spanInfo.getTags() >> TagMap.fromMap([:])
1 * mockAppSecCtx.transferCollectedEvents() >> []
1 * mockAppSecCtx.close()
1 * traceSegment.setTagTop("_dd.appsec.enabled", 1)
1 * traceSegment.setTagTop("_dd.runtime_family", "jvm")
1 * traceSegment.setTagTop('http.response.headers.content-type', 'text/plain')
1 * wafMetricCollector.wafRequest(_, _, _, _, _, _, _)
flow.result == null
flow.action == Flow.Action.Noop.INSTANCE
}
void 'response_header_done clears response headers for blocking when WAF blocks'() {
given:
def blockingFlow = Stub(Flow) {
getAction() >> new Flow.Action.RequestBlockingAction(403, BlockingContentType.AUTO)
}
eventDispatcher.getDataSubscribers(_) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> blockingFlow
when:
respHeaderCB.accept(ctx, 'content-type', 'text/html')
responseStartedCB.apply(ctx, 403)
respHeadersDoneCB.apply(ctx)
then:
ctx.data.responseHeaders.isEmpty()
!ctx.data.finishedResponseHeaders
}
void 'bridge can collect headers'() {
when:
reqHeaderCB.accept(ctx, 'header1', 'value 1.1')
reqHeaderCB.accept(ctx, 'header1', 'value 1.2')
reqHeaderCB.accept(ctx, 'Header1', 'value 1.3')
reqHeaderCB.accept(ctx, 'header2', 'value 2')
respHeaderCB.accept(ctx, 'header3', 'value 3.1')
respHeaderCB.accept(ctx, 'header3', 'value 3.2')
respHeaderCB.accept(ctx, 'header3', 'value 3.3')
respHeaderCB.accept(ctx, 'header4', 'value 4')
then:
def reqHeaders = ctx.data.requestHeaders
assert reqHeaders['header1'] == ['value 1.1', 'value 1.2', 'value 1.3']
assert reqHeaders['header2'] == ['value 2']
def respHeaders = ctx.data.responseHeaders
assert respHeaders['header3'] == ['value 3.1', 'value 3.2', 'value 3.3']
assert respHeaders['header4'] == ['value 4']
}
void 'headers are split between cookies and non cookies'() {
when:
reqHeaderCB.accept(ctx, 'Cookie', 'foo=bar;foo2=bar2')
reqHeaderCB.accept(ctx, 'Cookie', 'foo3=bar3')
reqHeaderCB.accept(ctx, 'Another-Header', 'another value')
then:
def collectedHeaders = ctx.data.requestHeaders
assert collectedHeaders['another-header'] == ['another value']
assert !collectedHeaders.containsKey('cookie')
def cookies = ctx.data.cookies
assert cookies['foo'] == ['bar']
assert cookies['foo2'] == ['bar2']
assert cookies['foo3'] == ['bar3']
}
void 'headers provided after headers ended are ignored'() {
DataBundle bundle
when:
ctx.data.rawURI = '/'
ctx.data.peerAddress = '0.0.0.0'
eventDispatcher.getDataSubscribers(_) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; NoopFlow.INSTANCE
}
and:
reqHeadersDoneCB.apply(ctx)
reqHeaderCB.accept(ctx, 'header', 'value')
then:
thrown(IllegalStateException)
def data = bundle.get(KnownAddresses.HEADERS_NO_COOKIES)
assert data == null || data.isEmpty()
}
void 'the socket address is distributed'() {
DataBundle bundle
GatewayContext gatewayContext
when:
eventDispatcher.getDataSubscribers(_) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
reqHeadersDoneCB.apply(ctx)
requestMethodURICB.apply(ctx, 'GET', TestURIDataAdapter.create('/a'))
requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
then:
bundle.get(KnownAddresses.REQUEST_CLIENT_IP) == '0.0.0.0'
bundle.get(KnownAddresses.REQUEST_CLIENT_PORT) == 5555
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'the inferred ip address is distributed if published before the socket address'() {
DataBundle bundle
GatewayContext gatewayContext
when:
eventDispatcher.getDataSubscribers(_) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
reqHeadersDoneCB.apply(ctx)
requestMethodURICB.apply(ctx, 'GET', TestURIDataAdapter.create('/a'))
requestInferredAddressCB.apply(ctx, '1.2.3.4')
requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
then:
bundle.get(KnownAddresses.REQUEST_INFERRED_CLIENT_IP) == '1.2.3.4'
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'setting headers then request uri triggers initial data event'() {
DataBundle bundle
GatewayContext gatewayContext
when:
eventDispatcher.getDataSubscribers(_) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
reqHeadersDoneCB.apply(ctx)
requestMethodURICB.apply(ctx, 'GET', TestURIDataAdapter.create('/a'))
requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
then:
bundle.get(KnownAddresses.REQUEST_URI_RAW) == '/a'
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'the raw request uri is provided and decoded'() {
DataBundle bundle
GatewayContext gatewayContext
def adapter = TestURIDataAdapter.create(uri, supportsRaw)
when:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_URI_RAW in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
requestMethodURICB.apply(ctx, 'GET', adapter)
reqHeadersDoneCB.apply(ctx)
requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
then:
bundle.get(KnownAddresses.REQUEST_URI_RAW) == expected
gatewayContext.isTransient == false
gatewayContext.isRasp == false
if (null != uri) {
def query = bundle.get(KnownAddresses.REQUEST_QUERY)
assert query['foo'] == ['bar 1', 'bar 2']
assert query['xpto'] == ['']
}
where:
uri | supportsRaw | expected
'/foo%6f?foo=bar+1&fo%6f=b%61r+2&xpto' | true | '/foo%6f?foo=bar+1&fo%6f=b%61r+2&xpto'
'/fooo?foo=bar 1&foo=bar 2&xpto' | false | '/fooo?foo=bar%201&foo=bar%202&xpto'
null | false | ''
}
void 'exercise all decoding paths'() {
DataBundle bundle
GatewayContext gatewayContext
String uri = "/?foo=$encoded"
def adapter = TestURIDataAdapter.create(uri)
when:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_URI_RAW in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
requestMethodURICB.apply(ctx, 'GET', adapter)
reqHeadersDoneCB.apply(ctx)
requestSocketAddressCB.apply(ctx, '0.0.0.0', 80)
then:
def query = bundle.get(KnownAddresses.REQUEST_QUERY)
query['foo'] == [decoded]
gatewayContext.isTransient == false
gatewayContext.isRasp == false
where:
encoded | decoded
'%80' | '\uFFFD' // repl. char: not a valid UTF-8 code unit sequence
'%8' | '%8'
'%8G' | '%8G'
'%G8' | '%G8'
'%G8' | '%G8'
'%0:' | '%0:'
'%0A' | '\n'
'%0a' | '\n'
'%C2%80' | '\u0080'
}
void 'path params are published'() {
DataBundle bundle
GatewayContext gatewayContext
when:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_PATH_PARAMS in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
pathParamsCB.apply(ctx, [a: 'b'])
then:
bundle.get(KnownAddresses.REQUEST_PATH_PARAMS) == [a: 'b']
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'path params is not published twice'() {
Flow flow
setup:
pathParamsCB.apply(ctx, [a: 'b'])
when:
flow = pathParamsCB.apply(ctx, [c: 'd'])
then:
flow == NoopFlow.INSTANCE
0 * eventDispatcher.getDataSubscribers(KnownAddresses.REQUEST_PATH_PARAMS)
0 * eventDispatcher.publishDataEvent(*_)
}
void callInitAndCaptureCBs() {
// force all callbacks to be registered
_ * eventDispatcher.allSubscribedDataAddresses() >> [KnownAddresses.REQUEST_PATH_PARAMS, KnownAddresses.REQUEST_BODY_OBJECT]
1 * ig.registerCallback(EVENTS.requestStarted(), _) >> {
requestStartedCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestEnded(), _) >> {
requestEndedCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestMethodUriRaw(), _) >> {
requestMethodURICB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestPathParams(), _) >> {
pathParamsCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestHeader(), _) >> {
reqHeaderCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestHeaderDone(), _) >> {
reqHeadersDoneCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestClientSocketAddress(), _) >> {
requestSocketAddressCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestInferredClientAddress(), _) >> {
requestInferredAddressCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestBodyStart(), _) >> {
requestBodyStartCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestBodyDone(), _) >> {
requestBodyDoneCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestBodyProcessed(), _) >> {
requestBodyProcessedCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.responseBody(), _) >> {
responseBodyCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.responseStarted(), _) >> {
responseStartedCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.responseHeader(), _) >> {
respHeaderCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.responseHeaderDone(), _) >> {
respHeadersDoneCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.grpcServerMethod(), _) >> {
grpcServerMethodCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.grpcServerRequestMessage(), _) >> {
grpcServerRequestMessageCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.graphqlServerRequestMessage(), _) >> {
graphqlServerRequestMessageCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.databaseConnection(), _) >> {
databaseConnectionCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.databaseSqlQuery(), _) >> {
databaseSqlQueryCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.httpClientRequest(), _) >> {
httpClientRequestCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.httpClientResponse(), _) >> {
httpClientResponseCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.httpClientSampling(), _) >> {
httpClientSamplingCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.fileLoaded(), _) >> {
fileLoadedCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.requestSession(), _) >> {
requestSessionCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.execCmd(), _) >> {
execCmdCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.shellCmd(), _) >> {
shellCmdCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.user(), _) >> {
userCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.loginEvent(), _) >> {
loginEventCB = it[1]; null
}
1 * ig.registerCallback(EVENTS.httpRoute(), _) >> {
httpRouteCB = it[1]; null
}
0 * ig.registerCallback(_, _)
bridge.init()
}
private static abstract class TestURIDataAdapter extends URIDataAdapterBase {
static URIDataAdapter create(String uri, boolean supportsRaw = true) {
if (supportsRaw) {
new TestRawAdapter(uri)
} else {
new TestNoRawAdapter(uri)
}
}
private final String p
private final String q
private final String scheme
private final String host
private final int port
protected TestURIDataAdapter(String uri) {
if (null == uri) {
p = null
q = null
scheme = null
host = null
port = 0
} else {
def parts = uri.split("\\?")
p = parts[0]
q = parts.length == 2 ? parts[1] : null
scheme = ((uri =~ /\A.+(?=:\/\/)/) ?: [null])[0]
host = ((uri =~ /(?<=:\/\/).+(?=:|\/)/) ?: [null])[0]
def m = uri =~ /(?<=:)\d+(?=\/|\z)/
port = m ? m[0] as int : (scheme == 'http' ? 80 : 443)
}
}
@Override
String scheme() {
scheme
}
@Override
String host() {
host
}
@Override
int port() {
port
}
@Override
String path() {
supportsRaw() ? null : p
}
@Override
String fragment() {
null
}
@Override
String query() {
supportsRaw() ? null : q
}
@Override
String rawPath() {
supportsRaw() ? p : null
}
@Override
boolean hasPlusEncodedSpaces() {
false
}
@Override
String rawQuery() {
supportsRaw() ? q : null
}
private static class TestRawAdapter extends TestURIDataAdapter {
TestRawAdapter(String uri) {
super(uri)
}
@Override
boolean supportsRaw() {
true
}
}
private static class TestNoRawAdapter extends TestURIDataAdapter {
TestNoRawAdapter(String uri) {
super(uri)
}
@Override
boolean supportsRaw() {
false
}
}
}
void 'forwards request body start events and stores the supplier'() {
StoredBodySupplier supplier = Stub()
setup:
supplier.get() >> 'foobar'
expect:
ctx.data.storedRequestBody == null
when:
requestBodyStartCB.apply(ctx, supplier)
then:
ctx.data.storedRequestBody == 'foobar'
}
void 'forwards request body done events and distributes the body contents'() {
DataBundle bundle
GatewayContext gatewayContext
StoredBodySupplier supplier = Stub()
setup:
supplier.get() >> 'foobar'
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_BODY_RAW in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
when:
requestBodyDoneCB.apply(ctx, supplier)
then:
bundle.get(KnownAddresses.REQUEST_BODY_RAW) == 'foobar'
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'request body does not get published twice'() {
StoredBodySupplier supplier = Stub()
Flow flow
given:
supplier.get() >> 'foobar'
when:
ctx.data.setRawReqBodyPublished(true)
flow = requestBodyDoneCB.apply(ctx, supplier)
then:
flow == NoopFlow.INSTANCE
0 * eventDispatcher.getDataSubscribers(KnownAddresses.REQUEST_BODY_RAW)
}
void 'forward request body processed'() {
DataBundle bundle
GatewayContext gatewayContext
Object obj = 'hello'
setup:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_BODY_OBJECT in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext)
>> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
when:
requestBodyProcessedCB.apply(ctx, obj)
then:
bundle.get(KnownAddresses.REQUEST_BODY_OBJECT) == 'hello'
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'processed body does not published twice'() {
Flow flow
when:
ctx.data.setConvertedReqBodyPublished(true)
flow = requestBodyProcessedCB.apply(ctx, new Object())
then:
flow == NoopFlow.INSTANCE
0 * eventDispatcher.getDataSubscribers(KnownAddresses.REQUEST_BODY_OBJECT)
0 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, false)
}
void 'request body transforms object and publishes'() {
setup:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_BODY_OBJECT in it
}) >> nonEmptyDsInfo
DataBundle bundle
GatewayContext gatewayContext
when:
Flow<?> flow = requestBodyProcessedCB.apply(ctx, new Object() {
@SuppressWarnings('UnusedPrivateField')
private String foo = 'bar'
})
then:
1 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
a, b, db, gw -> bundle = db; gatewayContext = gw; NoopFlow.INSTANCE
}
bundle.get(KnownAddresses.REQUEST_BODY_OBJECT) == [foo: 'bar']
flow.result == null
flow.action == Flow.Action.Noop.INSTANCE
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'forwards request method'() {
DataBundle bundle
GatewayContext gatewayContext
def adapter = TestURIDataAdapter.create('http://example.com/')
setup:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_METHOD in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
when:
requestMethodURICB.apply(ctx, 'POST', adapter)
reqHeadersDoneCB.apply(ctx)
requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
then:
bundle.get(KnownAddresses.REQUEST_METHOD) == 'POST'
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'scheme is extracted from the uri adapter'() {
DataBundle bundle
GatewayContext gatewayContext
def adapter = TestURIDataAdapter.create('https://example.com/')
when:
eventDispatcher.getDataSubscribers({
KnownAddresses.REQUEST_SCHEME in it
}) >> nonEmptyDsInfo
eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
bundle = it[2]; gatewayContext = it[3]; NoopFlow.INSTANCE
}
and:
requestMethodURICB.apply(ctx, 'GET', adapter)
reqHeadersDoneCB.apply(ctx)
requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
then:
bundle.get(KnownAddresses.REQUEST_SCHEME) == 'https'
gatewayContext.isTransient == false
gatewayContext.isRasp == false
}
void 'request data does not published twice'() {
AppSecRequestContext reqCtx = Stub()
Flow flow1, flow2, flow3
when:
ctx.data.setReqDataPublished(true)
flow1 = requestSocketAddressCB.apply(ctx, '0.0.0.0', 5555)
flow2 = reqHeadersDoneCB.apply(ctx)
flow3 = requestMethodURICB.apply(ctx, "GET", TestURIDataAdapter.create('/a'))
then:
flow1 == NoopFlow.INSTANCE
flow2 == NoopFlow.INSTANCE
flow3 == NoopFlow.INSTANCE
0 * eventDispatcher.getDataSubscribers(KnownAddresses.REQUEST_SCHEME)
0 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, reqCtx, _ as DataBundle, false)
}
void 'request method URI callback called twice with different URIs does not throw'() {
// Reproduces: https://github.com/DataDog/dd-trace-java/issues/10700
when:
requestMethodURICB.apply(ctx, 'GET', TestURIDataAdapter.create('/a'))
requestMethodURICB.apply(ctx, 'GET', TestURIDataAdapter.create('/b'))
then:
noExceptionThrown()
ctx.data.savedRawURI == '/a'
}
void 'response_start produces appsec context and publishes event'() {
eventDispatcher.getDataSubscribers({
KnownAddresses.RESPONSE_STATUS in it
}) >> nonEmptyDsInfo
when:
Flow<AppSecRequestContext> flow1 = responseStartedCB.apply(ctx, 404)
Flow<AppSecRequestContext> flow2 = respHeadersDoneCB.apply(ctx)
then:
1 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
NoopFlow.INSTANCE
}
flow1.result == null
flow1.action == Flow.Action.Noop.INSTANCE
flow2.result == null
flow2.action == Flow.Action.Noop.INSTANCE
}
void 'grpc server message recv transforms object and publishes'() {
setup:
eventDispatcher.getDataSubscribers({
KnownAddresses.GRPC_SERVER_REQUEST_MESSAGE in it
}) >> nonEmptyDsInfo
DataBundle bundle
GatewayContext gatewayContext
when:
Flow<?> flow = grpcServerRequestMessageCB.apply(ctx, new Object() {
@SuppressWarnings('UnusedPrivateField')
private String foo = 'bar'
})
then:
1 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
a, b, db, gw -> bundle = db; gatewayContext = gw; NoopFlow.INSTANCE
}
bundle.get(KnownAddresses.GRPC_SERVER_REQUEST_MESSAGE) == [foo: 'bar']
flow.result == null
flow.action == Flow.Action.Noop.INSTANCE
gatewayContext.isTransient == true
gatewayContext.isRasp == false
}
void 'grpc server method publishes'() {
setup:
eventDispatcher.getDataSubscribers(KnownAddresses.GRPC_SERVER_METHOD) >> nonEmptyDsInfo
DataBundle bundle
GatewayContext gatewayContext
when:
Flow<?> flow = grpcServerMethodCB.apply(ctx, '/my.package.Greeter/SayHello')
then:
1 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
args -> bundle = args[2]; gatewayContext = args[3]; NoopFlow.INSTANCE
}
bundle.get(KnownAddresses.GRPC_SERVER_METHOD) == '/my.package.Greeter/SayHello'
gatewayContext != null
gatewayContext.isTransient == true
gatewayContext.isRasp == false
flow.result == null
flow.action == Flow.Action.Noop.INSTANCE
}
void 'process database type'() {
setup:
eventDispatcher.getDataSubscribers({
KnownAddresses.DB_TYPE in it
}) >> nonEmptyDsInfo
when:
databaseConnectionCB.accept(ctx, 'postgresql')
then:
arCtx.dbType == 'postgresql'
}
void 'process jdbc statement query object'() {
setup:
eventDispatcher.getDataSubscribers({
KnownAddresses.DB_SQL_QUERY in it
}) >> nonEmptyDsInfo
DataBundle bundle
GatewayContext gatewayContext
when:
Flow<?> flow = databaseSqlQueryCB.apply(ctx, 'SELECT * FROM foo')
then:
1 * eventDispatcher.publishDataEvent(nonEmptyDsInfo, ctx.data, _ as DataBundle, _ as GatewayContext) >> {
a, b, db, gw -> bundle = db; gatewayContext = gw; NoopFlow.INSTANCE
}
bundle.get(KnownAddresses.DB_SQL_QUERY) == 'SELECT * FROM foo'
flow.result == null
flow.action == Flow.Action.Noop.INSTANCE
gatewayContext.isTransient == true
gatewayContext.isRasp == true
}
void 'process http client request sampling'() {