-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathAppSecRequestContext.java
More file actions
1081 lines (916 loc) · 31.3 KB
/
AppSecRequestContext.java
File metadata and controls
1081 lines (916 loc) · 31.3 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 static datadog.trace.api.telemetry.LogCollector.SEND_TELEMETRY;
import static java.util.Collections.emptySet;
import com.datadog.appsec.event.data.Address;
import com.datadog.appsec.event.data.DataBundle;
import com.datadog.appsec.report.AppSecEvent;
import com.datadog.appsec.util.StandardizedLogging;
import com.datadog.ddwaf.WafContext;
import com.datadog.ddwaf.WafHandle;
import com.datadog.ddwaf.WafMetrics;
import datadog.trace.api.Config;
import datadog.trace.api.endpoint.EndpointResolver;
import datadog.trace.api.http.StoredBodySupplier;
import datadog.trace.api.internal.TraceSegment;
import datadog.trace.util.Numbers;
import datadog.trace.util.stacktrace.StackTraceEvent;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// TODO: different methods to be called by different parts perhaps splitting it would make sense
// or at least create separate interfaces
@SuppressFBWarnings("AT_STALE_THREAD_WRITE_OF_PRIMITIVE")
public class AppSecRequestContext implements DataBundle, Closeable {
private static final Logger log = LoggerFactory.getLogger(AppSecRequestContext.class);
public static final int DEFAULT_EXTENDED_DATA_COLLECTION_MAX_HEADERS = 50;
// Values MUST be lowercase! Lookup with Ignore Case
// was removed due performance reason
// request headers that will always be set when appsec is enabled
public static final Set<String> DEFAULT_REQUEST_HEADERS_ALLOW_LIST =
new TreeSet<>(
Arrays.asList(
"content-type",
"user-agent",
"accept",
"x-amzn-trace-id",
"cloudfront-viewer-ja3-fingerprint",
"cf-ray",
"x-cloud-trace-context",
"x-appgw-trace-id",
"x-sigsci-requestid",
"x-sigsci-tags",
"akamai-user-risk"));
// request headers when there are security events
public static final Set<String> REQUEST_HEADERS_ALLOW_LIST =
new TreeSet<>(
Arrays.asList(
"x-forwarded-for",
"x-real-ip",
"true-client-ip",
"x-client-ip",
"x-forwarded",
"forwarded-for",
"x-cluster-client-ip",
"fastly-client-ip",
"cf-connecting-ip",
"cf-connecting-ipv6",
"forwarded",
"via",
"content-length",
"content-encoding",
"content-language",
"host",
"accept-encoding",
"accept-language"));
// response headers when there are security events
public static final Set<String> RESPONSE_HEADERS_ALLOW_LIST =
new TreeSet<>(
Arrays.asList("content-length", "content-type", "content-encoding", "content-language"));
// headers related with authorization
public static final Set<String> AUTHORIZATION_HEADERS =
new TreeSet<>(
Arrays.asList(
"authorization",
"proxy-authorization",
"www-authenticate",
"proxy-authenticate",
"authentication-info",
"proxy-authentication-info",
"cookie",
"set-cookie"));
static {
REQUEST_HEADERS_ALLOW_LIST.addAll(DEFAULT_REQUEST_HEADERS_ALLOW_LIST);
}
private final ConcurrentHashMap<Address<?>, Object> persistentData = new ConcurrentHashMap<>();
private volatile Queue<AppSecEvent> appSecEvents;
private volatile Queue<StackTraceEvent> stackTraceEvents;
// assume these will always be written and read by the same thread
private String scheme;
private String method;
private String savedRawURI;
private String route;
private String httpUrl;
private String endpoint;
private boolean endpointComputed = false;
private final Map<String, List<String>> requestHeaders = new LinkedHashMap<>();
private final Map<String, List<String>> responseHeaders = new LinkedHashMap<>();
private volatile Map<String, List<String>> collectedCookies;
private boolean finishedRequestHeaders;
private boolean finishedResponseHeaders;
private String peerAddress;
private int peerPort;
private String inferredClientIp;
private boolean extendedDataCollection = false;
private int extendedDataCollectionMaxHeaders = DEFAULT_EXTENDED_DATA_COLLECTION_MAX_HEADERS;
private volatile StoredBodySupplier storedRequestBodySupplier;
private String dbType;
private int responseStatus;
private boolean reqDataPublished;
private boolean rawReqBodyPublished;
private boolean convertedReqBodyPublished;
private boolean responseBodyPublished;
private boolean respDataPublished;
private boolean pathParamsPublished;
private final AtomicReference<Map<String, Object>> derivatives = new AtomicReference<>();
private final AtomicBoolean rateLimited = new AtomicBoolean(false);
private volatile boolean throttled;
// should be guarded by this
private volatile WafContext wafContext;
private volatile boolean wafContextClosed;
// set after wafContext is set
private volatile WafMetrics wafMetrics;
private volatile WafMetrics raspMetrics;
private final AtomicInteger raspMetricsCounter = new AtomicInteger(0);
private volatile boolean wafBlocked;
private volatile String blockingResponseContentType;
private volatile Integer blockingResponseContentLength;
private volatile boolean wafErrors;
private volatile boolean wafTruncated;
private volatile boolean wafRequestBlockFailure;
private volatile boolean wafRateLimited;
private volatile int wafTimeouts;
private volatile int raspTimeouts;
private volatile Object processedRequestBody;
private volatile boolean processedResponseBodySizeExceeded;
private volatile boolean raspMatched;
// keep a reference to the last published usr.id
private volatile String userId;
// keep a reference to the last published usr.login
private volatile String userLogin;
// keep a reference to the last published usr.session_id
private volatile String sessionId;
// Used to detect missing request-end event at close.
private volatile boolean requestEndCalled;
private volatile boolean keepOpenForApiSecurityPostProcessing;
private volatile Long apiSecurityEndpointHash;
private final AtomicInteger httpClientRequestCount = new AtomicInteger(0);
private final Set<Long> sampledHttpClientRequests = new HashSet<>();
private static final AtomicIntegerFieldUpdater<AppSecRequestContext> WAF_TIMEOUTS_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(AppSecRequestContext.class, "wafTimeouts");
private static final AtomicIntegerFieldUpdater<AppSecRequestContext> RASP_TIMEOUTS_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(AppSecRequestContext.class, "raspTimeouts");
private boolean manuallyKept = false;
// to be called by the Event Dispatcher
public void addAll(DataBundle newData) {
for (Map.Entry<Address<?>, Object> entry : newData) {
Address<?> address = entry.getKey();
Object value = entry.getValue();
if (value == null) {
log.debug(SEND_TELEMETRY, "Address {} ignored, because contains null value.", address);
continue;
}
Object prev = persistentData.putIfAbsent(address, value);
if (prev == value || value.equals(prev)) {
continue;
} else if (prev != null) {
log.debug(SEND_TELEMETRY, "Attempt to replace context value for {}", address);
}
if (log.isDebugEnabled()) {
StandardizedLogging.addressPushed(log, address);
}
}
}
public WafMetrics getWafMetrics() {
return wafMetrics;
}
public WafMetrics getRaspMetrics() {
return raspMetrics;
}
public AtomicInteger getRaspMetricsCounter() {
return raspMetricsCounter;
}
public void setWafBlocked() {
this.wafBlocked = true;
}
public boolean isWafBlocked() {
return wafBlocked;
}
public void setBlockingResponseContentType(String contentType) {
this.blockingResponseContentType = contentType;
}
public String getBlockingResponseContentType() {
return blockingResponseContentType;
}
public void setBlockingResponseContentLength(Integer contentLength) {
this.blockingResponseContentLength = contentLength;
}
public Integer getBlockingResponseContentLength() {
return blockingResponseContentLength;
}
public void setWafErrors() {
this.wafErrors = true;
}
public boolean hasWafErrors() {
return wafErrors;
}
public void setWafTruncated() {
this.wafTruncated = true;
}
public boolean isWafTruncated() {
return wafTruncated;
}
public void setWafRequestBlockFailure() {
this.wafRequestBlockFailure = true;
}
public boolean isWafRequestBlockFailure() {
return wafRequestBlockFailure;
}
public void setWafRateLimited() {
this.wafRateLimited = true;
}
public boolean isWafRateLimited() {
return wafRateLimited;
}
public void increaseWafTimeouts() {
WAF_TIMEOUTS_UPDATER.incrementAndGet(this);
}
public void increaseRaspTimeouts() {
RASP_TIMEOUTS_UPDATER.incrementAndGet(this);
}
public boolean sampleHttpClientRequest(final long id) {
httpClientRequestCount.incrementAndGet();
synchronized (sampledHttpClientRequests) {
if (sampledHttpClientRequests.contains(id)) {
return true;
}
if (sampledHttpClientRequests.size()
< Config.get().getApiSecurityMaxDownstreamRequestBodyAnalysis()) {
sampledHttpClientRequests.add(id);
return true;
}
}
return false;
}
public boolean isHttpClientRequestSampled(final long id) {
return sampledHttpClientRequests.contains(id);
}
public int getHttpClientRequestCount() {
return httpClientRequestCount.get();
}
public int getWafTimeouts() {
return wafTimeouts;
}
public int getRaspTimeouts() {
return raspTimeouts;
}
public boolean isExtendedDataCollection() {
return extendedDataCollection;
}
public void setExtendedDataCollection(boolean extendedDataCollection) {
this.extendedDataCollection = extendedDataCollection;
}
public int getExtendedDataCollectionMaxHeaders() {
return extendedDataCollectionMaxHeaders;
}
public void setExtendedDataCollectionMaxHeaders(int extendedDataCollectionMaxHeaders) {
this.extendedDataCollectionMaxHeaders = extendedDataCollectionMaxHeaders;
}
public WafContext getOrCreateWafContext(
WafHandle wafHandle, boolean createMetrics, boolean isRasp) {
if (createMetrics) {
if (wafMetrics == null) {
this.wafMetrics = new WafMetrics();
}
if (isRasp && raspMetrics == null) {
this.raspMetrics = new WafMetrics();
}
}
WafContext curWafContext;
synchronized (this) {
curWafContext = this.wafContext;
if (curWafContext != null) {
return curWafContext;
}
curWafContext = new WafContext(wafHandle);
this.wafContext = curWafContext;
}
return curWafContext;
}
public void closeWafContext() {
if (wafContext != null) {
synchronized (this) {
if (wafContext != null) {
try {
wafContextClosed = true;
wafContext.close();
} finally {
wafContext = null;
}
}
}
}
}
/* Implementation of DataBundle */
@Override
public boolean hasAddress(Address<?> addr) {
return persistentData.containsKey(addr);
}
@Override
public Collection<Address<?>> getAllAddresses() {
return persistentData.keySet();
}
@Override
public int size() {
return persistentData.size();
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(Address<T> addr) {
return (T) persistentData.get(addr);
}
@Override
public Iterator<Map.Entry<Address<?>, Object>> iterator() {
return persistentData.entrySet().iterator();
}
/* Interface for use of GatewayBridge */
String getScheme() {
return scheme;
}
void setScheme(String scheme) {
this.scheme = scheme;
}
public String getMethod() {
return method;
}
void setMethod(String method) {
this.method = method;
}
String getSavedRawURI() {
return savedRawURI;
}
void setRawURI(String savedRawURI) {
if (this.savedRawURI == null) {
this.savedRawURI = savedRawURI;
}
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public String getHttpUrl() {
return httpUrl;
}
public void setHttpUrl(String httpUrl) {
this.httpUrl = httpUrl;
}
/**
* Gets or computes the http.endpoint for this request. The endpoint is computed lazily on first
* access and cached to avoid recomputation.
*
* @return the http.endpoint value, or null if it cannot be computed
*/
public String getOrComputeEndpoint() {
if (!endpointComputed) {
if (httpUrl != null && !httpUrl.isEmpty()) {
try {
endpoint = EndpointResolver.computeEndpoint(httpUrl);
} catch (Exception e) {
endpoint = null;
}
}
endpointComputed = true;
}
return endpoint;
}
/**
* Sets the endpoint directly without computing it. This is useful when the endpoint has already
* been computed elsewhere.
*
* @param endpoint the endpoint value to set
*/
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
this.endpointComputed = true;
}
public void setKeepOpenForApiSecurityPostProcessing(final boolean flag) {
this.keepOpenForApiSecurityPostProcessing = flag;
}
public boolean isKeepOpenForApiSecurityPostProcessing() {
return this.keepOpenForApiSecurityPostProcessing;
}
public void setApiSecurityEndpointHash(long hash) {
this.apiSecurityEndpointHash = hash;
}
public Long getApiSecurityEndpointHash() {
return this.apiSecurityEndpointHash;
}
void addRequestHeader(String name, String value) {
if (finishedRequestHeaders) {
throw new IllegalStateException("Request headers were said to be finished before");
}
if (name == null || value == null) {
return;
}
List<String> strings =
requestHeaders.computeIfAbsent(name.toLowerCase(Locale.ROOT), h -> new ArrayList<>(1));
strings.add(value);
}
void finishRequestHeaders() {
this.finishedRequestHeaders = true;
}
boolean isFinishedRequestHeaders() {
return finishedRequestHeaders;
}
Map<String, List<String>> getRequestHeaders() {
return requestHeaders;
}
void addResponseHeader(String name, String value) {
if (finishedResponseHeaders) {
throw new IllegalStateException("Response headers were said to be finished before");
}
if (name == null || value == null) {
return;
}
List<String> strings =
responseHeaders.computeIfAbsent(name.toLowerCase(Locale.ROOT), h -> new ArrayList<>(1));
strings.add(value);
}
public void finishResponseHeaders() {
this.finishedResponseHeaders = true;
}
public boolean isFinishedResponseHeaders() {
return finishedResponseHeaders;
}
Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
void addCookies(Map<String, List<String>> cookies) {
if (finishedRequestHeaders) {
throw new IllegalStateException("Request headers were said to be finished before");
}
if (collectedCookies == null) {
collectedCookies = cookies;
} else {
collectedCookies.putAll(cookies);
}
}
Map<String, ? extends Collection<String>> getCookies() {
return collectedCookies != null ? collectedCookies : Collections.emptyMap();
}
String getPeerAddress() {
return peerAddress;
}
void setPeerAddress(String peerAddress) {
this.peerAddress = peerAddress;
}
public int getPeerPort() {
return peerPort;
}
public void setPeerPort(int peerPort) {
this.peerPort = peerPort;
}
void setInferredClientIp(String ipAddress) {
this.inferredClientIp = ipAddress;
}
String getInferredClientIp() {
return inferredClientIp;
}
void setStoredRequestBodySupplier(StoredBodySupplier storedRequestBodySupplier) {
this.storedRequestBodySupplier = storedRequestBodySupplier;
}
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
public int getResponseStatus() {
return responseStatus;
}
public void setResponseStatus(int responseStatus) {
this.responseStatus = responseStatus;
}
public boolean isReqDataPublished() {
return reqDataPublished;
}
public void setReqDataPublished(boolean reqDataPublished) {
this.reqDataPublished = reqDataPublished;
}
public boolean isPathParamsPublished() {
return pathParamsPublished;
}
public void setPathParamsPublished(boolean pathParamsPublished) {
this.pathParamsPublished = pathParamsPublished;
}
public boolean isRawReqBodyPublished() {
return rawReqBodyPublished;
}
public void setRawReqBodyPublished(boolean rawReqBodyPublished) {
this.rawReqBodyPublished = rawReqBodyPublished;
}
public boolean isConvertedReqBodyPublished() {
return convertedReqBodyPublished;
}
public void setConvertedReqBodyPublished(boolean convertedReqBodyPublished) {
this.convertedReqBodyPublished = convertedReqBodyPublished;
}
public boolean isResponseBodyPublished() {
return responseBodyPublished;
}
public void setResponseBodyPublished(final boolean responseBodyPublished) {
this.responseBodyPublished = responseBodyPublished;
}
public boolean isRespDataPublished() {
return respDataPublished;
}
public void setRespDataPublished(boolean respDataPublished) {
this.respDataPublished = respDataPublished;
}
/**
* Updates the current used usr.id
*
* @return {@code false} if the user id has not been updated
*/
public boolean updateUserId(String userId) {
if (Objects.equals(this.userId, userId)) {
return false;
}
this.userId = userId;
return true;
}
/**
* Updates current used usr.login
*
* @return {@code false} if the user login has not been updated
*/
public boolean updateUserLogin(String userLogin) {
if (Objects.equals(this.userLogin, userLogin)) {
return false;
}
this.userLogin = userLogin;
return true;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getSessionId() {
return sessionId;
}
/**
* Close the context and release all resources. This method is idempotent and can be called
* multiple times. For each root span, this method is always called from
* CoreTracer#onRootSpanPublished.
*/
@Override
public void close() {
if (!requestEndCalled) {
log.debug(SEND_TELEMETRY, "Request end event was not called before close");
}
// For API Security, we sometimes keep contexts open for late processing. In that case, this
// flag needs to be
// later reset by the API Security post-processor and close must be called again.
if (!keepOpenForApiSecurityPostProcessing) {
if (wafContext != null) {
log.debug(
SEND_TELEMETRY, "WAF object had not been closed (probably missed request-end event)");
closeWafContext();
}
collectedCookies = null;
requestHeaders.clear();
responseHeaders.clear();
persistentData.clear();
final Map<String, Object> derivatives = this.derivatives.getAndSet(null);
if (derivatives != null) {
derivatives.clear();
}
}
}
/**
* @return the portion of the body read so far, if any
*/
public CharSequence getStoredRequestBody() {
StoredBodySupplier storedRequestBodySupplier = this.storedRequestBodySupplier;
if (storedRequestBodySupplier == null) {
return null;
}
return storedRequestBodySupplier.get();
}
public void reportEvents(Collection<AppSecEvent> appSecEvents) {
for (AppSecEvent event : appSecEvents) {
StandardizedLogging.attackDetected(log, event);
}
if (this.appSecEvents == null) {
synchronized (this) {
if (this.appSecEvents == null) {
this.appSecEvents = new ConcurrentLinkedQueue<>();
}
}
}
this.appSecEvents.addAll(appSecEvents);
}
public void reportStackTrace(StackTraceEvent stackTraceEvent) {
if (this.stackTraceEvents == null) {
synchronized (this) {
if (this.stackTraceEvents == null) {
this.stackTraceEvents = new ConcurrentLinkedQueue<>();
}
}
}
if (stackTraceEvents.size() <= Config.get().getAppSecMaxStackTraces()) {
this.stackTraceEvents.add(stackTraceEvent);
}
}
Collection<AppSecEvent> transferCollectedEvents() {
if (this.appSecEvents == null) {
return Collections.emptyList();
}
Collection<AppSecEvent> events = new ArrayList<>();
AppSecEvent item;
while ((item = this.appSecEvents.poll()) != null) {
events.add(item);
}
return events;
}
List<StackTraceEvent> getStackTraces() {
if (this.stackTraceEvents == null) {
return null;
}
List<StackTraceEvent> stackTraces = new ArrayList<>();
StackTraceEvent item;
while ((item = this.stackTraceEvents.poll()) != null) {
stackTraces.add(item);
}
return stackTraces;
}
public void reportDerivatives(Map<String, Object> data) {
log.debug("Reporting derivatives: {}", data);
if (data == null || data.isEmpty()) return;
// Initialize or update derivatives atomically
derivatives.updateAndGet(
current -> {
Map<String, Object> updated = current != null ? new HashMap<>(current) : new HashMap<>();
// Process each attribute according to the specification
for (Map.Entry<String, Object> entry : data.entrySet()) {
String attributeKey = entry.getKey();
Object attributeConfig = entry.getValue();
if (attributeConfig instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> config = (Map<String, Object>) attributeConfig;
// Check if it's a literal value schema
if (config.containsKey("value")) {
Object literalValue = config.get("value");
if (literalValue != null) {
// Preserve the original type - don't convert to string
updated.put(attributeKey, literalValue);
log.debug(
"Added literal attribute: {} = {} (type: {})",
attributeKey,
literalValue,
literalValue.getClass().getSimpleName());
}
}
// Check if it's a request data schema
else if (config.containsKey("address")) {
String address = (String) config.get("address");
@SuppressWarnings("unchecked")
List<String> keyPath = (List<String>) config.get("key_path");
@SuppressWarnings("unchecked")
List<String> transformers = (List<String>) config.get("transformers");
Object extractedValue = extractValueFromRequestData(address, keyPath, transformers);
if (extractedValue != null) {
// For extracted values, convert to string as they come from request data
updated.put(attributeKey, extractedValue.toString());
log.debug("Added extracted attribute: {} = {}", attributeKey, extractedValue);
}
}
} else {
// Handle plain string/numeric values
updated.put(attributeKey, attributeConfig);
log.debug("Added direct attribute: {} = {}", attributeKey, attributeConfig);
}
}
return updated;
});
}
/**
* Extracts a value from request data based on address, key path, and transformers.
*
* @param address The address to extract from (e.g., "server.request.headers")
* @param keyPath Optional key path to navigate the data structure
* @param transformers Optional list of transformers to apply
* @return The extracted value, or null if not found
*/
private Object extractValueFromRequestData(
String address, List<String> keyPath, List<String> transformers) {
// Get the data from the address
Object data = getDataForAddress(address);
if (data == null) {
log.debug("No data found for address: {}", address);
return null;
}
// Navigate through the key path
Object currentValue = data;
if (keyPath != null && !keyPath.isEmpty()) {
currentValue = navigateKeyPath(currentValue, keyPath);
if (currentValue == null) {
log.debug("Could not navigate key path {} for address {}", keyPath, address);
return null;
}
}
// Apply transformers if specified
if (transformers != null && !transformers.isEmpty()) {
currentValue = applyTransformers(currentValue, transformers);
}
return currentValue;
}
/** Gets data for a specific address from the request context. */
private Object getDataForAddress(String address) {
// Map common addresses to our data structures
switch (address) {
case "server.request.headers":
return requestHeaders;
case "server.response.headers":
return responseHeaders;
case "server.request.cookies":
return collectedCookies;
case "server.request.uri.raw":
return savedRawURI;
case "server.request.method":
return method;
case "server.request.scheme":
return scheme;
case "server.request.route":
return route;
case "server.response.status":
return responseStatus;
case "server.request.body":
return getStoredRequestBody();
case "usr.id":
return userId;
case "usr.login":
return userLogin;
case "usr.session_id":
return sessionId;
default:
log.debug("Unknown address: {}", address);
return null;
}
}
/** Navigates through a data structure using a key path. */
private Object navigateKeyPath(Object data, List<String> keyPath) {
Object current = data;
for (String key : keyPath) {
if (current instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) current;
current = map.get(key);
} else if (current instanceof List) {
try {
int index = Integer.parseInt(key);
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) current;
if (index >= 0 && index < list.size()) {
current = list.get(index);
} else {
return null;
}
} catch (NumberFormatException e) {
log.debug("Invalid list index: {}", key);
return null;
}
} else {
log.debug("Cannot navigate key {} in data type: {}", key, current.getClass());
return null;
}
if (current == null) {
return null;
}
}
return current;
}
/** Applies transformers to a value. */
private Object applyTransformers(Object value, List<String> transformers) {
Object current = value;
for (String transformer : transformers) {
switch (transformer) {
case "lowercase":
if (current instanceof String) {
current = ((String) current).toLowerCase(Locale.ROOT);
}
break;
case "uppercase":
if (current instanceof String) {
current = ((String) current).toUpperCase(Locale.ROOT);
}
break;
case "trim":
if (current instanceof String) {
current = ((String) current).trim();
}
break;
case "length":
if (current instanceof String) {
current = ((String) current).length();
} else if (current instanceof Collection) {
current = ((Collection<?>) current).size();
} else if (current instanceof Map) {
current = ((Map<?, ?>) current).size();
}
break;
default:
log.debug("Unknown transformer: {}", transformer);
break;
}
}
return current;
}
public boolean commitDerivatives(TraceSegment traceSegment) {
if (traceSegment == null) {
return false;
}
// Get and clear derivatives atomically
Map<String, Object> derivativesToCommit = derivatives.getAndSet(null);
log.debug("Committing derivatives: {} for {}", derivativesToCommit, traceSegment);
// Process and commit derivatives directly
if (derivativesToCommit != null && !derivativesToCommit.isEmpty()) {