|
| 1 | +package com.datadog.appsec.api.security; |
| 2 | + |
| 3 | +import com.datadog.appsec.gateway.AppSecRequestContext; |
| 4 | +import datadog.trace.api.Config; |
| 5 | +import datadog.trace.api.time.SystemTimeSource; |
| 6 | +import datadog.trace.api.time.TimeSource; |
| 7 | +import java.util.Deque; |
| 8 | +import java.util.concurrent.ConcurrentHashMap; |
| 9 | +import java.util.concurrent.ConcurrentLinkedDeque; |
| 10 | +import java.util.concurrent.Semaphore; |
| 11 | +import javax.annotation.Nonnull; |
| 12 | +import org.slf4j.Logger; |
| 13 | +import org.slf4j.LoggerFactory; |
| 14 | + |
| 15 | +public class ApiSecuritySamplerImpl implements ApiSecuritySampler { |
| 16 | + |
| 17 | + private static final Logger log = LoggerFactory.getLogger(ApiSecuritySamplerImpl.class); |
| 18 | + |
| 19 | + /** |
| 20 | + * A maximum number of request contexts we'll keep open past the end of request at any given time. |
| 21 | + * This will avoid excessive memory usage in case of a high number of concurrent requests, and |
| 22 | + * should also prevent memory leaks. |
| 23 | + */ |
| 24 | + private static final int MAX_POST_PROCESSING_TASKS = 4; |
| 25 | + /** Maximum number of entries in the access map. */ |
| 26 | + private static final int MAX_SIZE = 4096; |
| 27 | + /** Mapping from endpoint hash to last access timestamp in millis. */ |
| 28 | + private final ConcurrentHashMap<Long, Long> accessMap; |
| 29 | + /** Deque of endpoint hashes ordered by access time. Oldest is always first. */ |
| 30 | + private final Deque<Long> accessDeque; |
| 31 | + |
| 32 | + private final long expirationTimeInMs; |
| 33 | + private final int capacity; |
| 34 | + private final TimeSource timeSource; |
| 35 | + private final Semaphore counter = new Semaphore(MAX_POST_PROCESSING_TASKS); |
| 36 | + |
| 37 | + public ApiSecuritySamplerImpl() { |
| 38 | + this( |
| 39 | + MAX_SIZE, |
| 40 | + (long) (Config.get().getApiSecuritySampleDelay() * 1_000), |
| 41 | + SystemTimeSource.INSTANCE); |
| 42 | + } |
| 43 | + |
| 44 | + public ApiSecuritySamplerImpl( |
| 45 | + int capacity, long expirationTimeInMs, @Nonnull TimeSource timeSource) { |
| 46 | + this.capacity = capacity; |
| 47 | + this.expirationTimeInMs = expirationTimeInMs; |
| 48 | + this.accessMap = new ConcurrentHashMap<>(); |
| 49 | + this.accessDeque = new ConcurrentLinkedDeque<>(); |
| 50 | + this.timeSource = timeSource; |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public boolean preSampleRequest(final @Nonnull AppSecRequestContext ctx) { |
| 55 | + final String route = ctx.getRoute(); |
| 56 | + if (route == null) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + final String method = ctx.getMethod(); |
| 60 | + if (method == null) { |
| 61 | + return false; |
| 62 | + } |
| 63 | + final int statusCode = ctx.getResponseStatus(); |
| 64 | + if (statusCode <= 0) { |
| 65 | + return false; |
| 66 | + } |
| 67 | + long hash = computeApiHash(route, method, statusCode); |
| 68 | + ctx.setApiSecurityEndpointHash(hash); |
| 69 | + if (!isApiAccessExpired(hash)) { |
| 70 | + return false; |
| 71 | + } |
| 72 | + if (counter.tryAcquire()) { |
| 73 | + log.debug("API security sampling is required for this request (presampled)"); |
| 74 | + ctx.setKeepOpenForApiSecurityPostProcessing(true); |
| 75 | + return true; |
| 76 | + } |
| 77 | + return false; |
| 78 | + } |
| 79 | + |
| 80 | + /** Get the final sampling decision. This method is NOT thread-safe. */ |
| 81 | + @Override |
| 82 | + public boolean sampleRequest(AppSecRequestContext ctx) { |
| 83 | + if (ctx == null) { |
| 84 | + return false; |
| 85 | + } |
| 86 | + final Long hash = ctx.getApiSecurityEndpointHash(); |
| 87 | + if (hash == null) { |
| 88 | + // This should never happen, it should have been short-circuited before. |
| 89 | + return false; |
| 90 | + } |
| 91 | + return updateApiAccessIfExpired(hash); |
| 92 | + } |
| 93 | + |
| 94 | + @Override |
| 95 | + public void releaseOne() { |
| 96 | + counter.release(); |
| 97 | + } |
| 98 | + |
| 99 | + private boolean updateApiAccessIfExpired(final long hash) { |
| 100 | + final long currentTime = timeSource.getCurrentTimeMillis(); |
| 101 | + |
| 102 | + Long lastAccess = accessMap.get(hash); |
| 103 | + if (lastAccess != null && currentTime - lastAccess < expirationTimeInMs) { |
| 104 | + return false; |
| 105 | + } |
| 106 | + |
| 107 | + if (accessMap.put(hash, currentTime) == null) { |
| 108 | + accessDeque.addLast(hash); |
| 109 | + // If we added a new entry, we perform purging. |
| 110 | + cleanupExpiredEntries(currentTime); |
| 111 | + } else { |
| 112 | + // This is now the most recently accessed entry. |
| 113 | + accessDeque.remove(hash); |
| 114 | + accessDeque.addLast(hash); |
| 115 | + } |
| 116 | + |
| 117 | + return true; |
| 118 | + } |
| 119 | + |
| 120 | + private boolean isApiAccessExpired(final long hash) { |
| 121 | + final long currentTime = timeSource.getCurrentTimeMillis(); |
| 122 | + final Long lastAccess = accessMap.get(hash); |
| 123 | + return lastAccess == null || currentTime - lastAccess >= expirationTimeInMs; |
| 124 | + } |
| 125 | + |
| 126 | + private void cleanupExpiredEntries(final long currentTime) { |
| 127 | + // Purge all expired entries. |
| 128 | + while (!accessDeque.isEmpty()) { |
| 129 | + final Long oldestHash = accessDeque.peekFirst(); |
| 130 | + if (oldestHash == null) { |
| 131 | + // Should never happen |
| 132 | + continue; |
| 133 | + } |
| 134 | + |
| 135 | + final Long lastAccessTime = accessMap.get(oldestHash); |
| 136 | + if (lastAccessTime == null) { |
| 137 | + // Should never happen |
| 138 | + continue; |
| 139 | + } |
| 140 | + |
| 141 | + if (currentTime - lastAccessTime < expirationTimeInMs) { |
| 142 | + // The oldest hash is up-to-date, so stop here. |
| 143 | + break; |
| 144 | + } |
| 145 | + |
| 146 | + accessDeque.pollFirst(); |
| 147 | + accessMap.remove(oldestHash); |
| 148 | + } |
| 149 | + |
| 150 | + // If we went over capacity, remove the oldest entries until we are within the limit. |
| 151 | + // This should never be more than 1. |
| 152 | + final int toRemove = accessMap.size() - this.capacity; |
| 153 | + for (int i = 0; i < toRemove; i++) { |
| 154 | + Long oldestHash = accessDeque.pollFirst(); |
| 155 | + if (oldestHash != null) { |
| 156 | + accessMap.remove(oldestHash); |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + private long computeApiHash(final String route, final String method, final int statusCode) { |
| 162 | + long result = 17; |
| 163 | + result = 31 * result + route.hashCode(); |
| 164 | + result = 31 * result + method.hashCode(); |
| 165 | + result = 31 * result + statusCode; |
| 166 | + return result; |
| 167 | + } |
| 168 | +} |
0 commit comments