-
Notifications
You must be signed in to change notification settings - Fork 312
New API Security sampling algorithm #8178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
fef2c64
Added AppSec post-processing
ValentinZakharov 21a2975
Api Security schema computation moved to post-processing stage in ser…
ValentinZakharov 0c2cec6
Implemented time-based sampling per endpoint
ValentinZakharov 30a1592
Added preSampler for short-circuit Api Security
ValentinZakharov 6a71986
Added post-processing limit
ValentinZakharov 64539ed
wip
smola d4b08e3
ST commit
smola 5e32bf8
wip
smola e9d1e75
wip
smola 3551464
wip
smola 21e1114
wip
smola 7ecd889
Remove excessive logs and tweak condition
smola c429be8
typo
smola 5488b19
fix test
smola 98d957d
fix merge conflict
smola File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
56 changes: 0 additions & 56 deletions
56
...agent/appsec/src/main/java/com/datadog/appsec/api/security/ApiSecurityRequestSampler.java
This file was deleted.
Oops, something went wrong.
35 changes: 35 additions & 0 deletions
35
dd-java-agent/appsec/src/main/java/com/datadog/appsec/api/security/ApiSecuritySampler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.datadog.appsec.api.security; | ||
|
||
import com.datadog.appsec.gateway.AppSecRequestContext; | ||
import javax.annotation.Nonnull; | ||
|
||
public interface ApiSecuritySampler { | ||
/** | ||
* Prepare a request context for later sampling decision. This method should be called at request | ||
* end, and is thread-safe. If a request can potentially be sampled, this method will return true. | ||
* If this method returns true, the caller MUST call {@link #releaseOne()} once the context is not | ||
* needed anymore. | ||
*/ | ||
boolean preSampleRequest(final @Nonnull AppSecRequestContext ctx); | ||
|
||
/** Get the final sampling decision. This method is NOT required to be thread-safe. */ | ||
boolean sampleRequest(AppSecRequestContext ctx); | ||
|
||
/** Release one permit for the sampler. This must be called after processing a span. */ | ||
void releaseOne(); | ||
|
||
final class NoOp implements ApiSecuritySampler { | ||
@Override | ||
public boolean preSampleRequest(@Nonnull AppSecRequestContext ctx) { | ||
return false; | ||
} | ||
|
||
@Override | ||
public boolean sampleRequest(AppSecRequestContext ctx) { | ||
return false; | ||
} | ||
|
||
@Override | ||
public void releaseOne() {} | ||
} | ||
} |
168 changes: 168 additions & 0 deletions
168
...va-agent/appsec/src/main/java/com/datadog/appsec/api/security/ApiSecuritySamplerImpl.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
package com.datadog.appsec.api.security; | ||
|
||
import com.datadog.appsec.gateway.AppSecRequestContext; | ||
import datadog.trace.api.Config; | ||
import datadog.trace.api.time.SystemTimeSource; | ||
import datadog.trace.api.time.TimeSource; | ||
import java.util.Deque; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.ConcurrentLinkedDeque; | ||
import java.util.concurrent.Semaphore; | ||
import javax.annotation.Nonnull; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
public class ApiSecuritySamplerImpl implements ApiSecuritySampler { | ||
|
||
private static final Logger log = LoggerFactory.getLogger(ApiSecuritySamplerImpl.class); | ||
|
||
/** | ||
* A maximum number of request contexts we'll keep open past the end of request at any given time. | ||
* This will avoid excessive memory usage in case of a high number of concurrent requests, and | ||
* should also prevent memory leaks. | ||
*/ | ||
private static final int MAX_POST_PROCESSING_TASKS = 4; | ||
/** Maximum number of entries in the access map. */ | ||
private static final int MAX_SIZE = 4096; | ||
/** Mapping from endpoint hash to last access timestamp in millis. */ | ||
private final ConcurrentHashMap<Long, Long> accessMap; | ||
/** Deque of endpoint hashes ordered by access time. Oldest is always first. */ | ||
private final Deque<Long> accessDeque; | ||
|
||
private final long expirationTimeInMs; | ||
private final int capacity; | ||
private final TimeSource timeSource; | ||
private final Semaphore counter = new Semaphore(MAX_POST_PROCESSING_TASKS); | ||
|
||
public ApiSecuritySamplerImpl() { | ||
this( | ||
MAX_SIZE, | ||
(long) (Config.get().getApiSecuritySampleDelay() * 1_000), | ||
SystemTimeSource.INSTANCE); | ||
} | ||
|
||
public ApiSecuritySamplerImpl( | ||
int capacity, long expirationTimeInMs, @Nonnull TimeSource timeSource) { | ||
this.capacity = capacity; | ||
this.expirationTimeInMs = expirationTimeInMs; | ||
this.accessMap = new ConcurrentHashMap<>(); | ||
this.accessDeque = new ConcurrentLinkedDeque<>(); | ||
this.timeSource = timeSource; | ||
} | ||
|
||
@Override | ||
public boolean preSampleRequest(final @Nonnull AppSecRequestContext ctx) { | ||
final String route = ctx.getRoute(); | ||
if (route == null) { | ||
return false; | ||
} | ||
final String method = ctx.getMethod(); | ||
if (method == null) { | ||
return false; | ||
} | ||
final int statusCode = ctx.getResponseStatus(); | ||
if (statusCode <= 0) { | ||
return false; | ||
} | ||
long hash = computeApiHash(route, method, statusCode); | ||
ctx.setApiSecurityEndpointHash(hash); | ||
if (!isApiAccessExpired(hash)) { | ||
return false; | ||
} | ||
if (counter.tryAcquire()) { | ||
log.debug("API security sampling is required for this request (presampled)"); | ||
ctx.setKeepOpenForApiSecurityPostProcessing(true); | ||
return true; | ||
} | ||
return false; | ||
} | ||
|
||
/** Get the final sampling decision. This method is NOT thread-safe. */ | ||
@Override | ||
public boolean sampleRequest(AppSecRequestContext ctx) { | ||
if (ctx == null) { | ||
return false; | ||
} | ||
final Long hash = ctx.getApiSecurityEndpointHash(); | ||
if (hash == null) { | ||
// This should never happen, it should have been short-circuited before. | ||
return false; | ||
} | ||
return updateApiAccessIfExpired(hash); | ||
} | ||
|
||
@Override | ||
public void releaseOne() { | ||
counter.release(); | ||
} | ||
|
||
private boolean updateApiAccessIfExpired(final long hash) { | ||
final long currentTime = timeSource.getCurrentTimeMillis(); | ||
|
||
Long lastAccess = accessMap.get(hash); | ||
if (lastAccess != null && currentTime - lastAccess < expirationTimeInMs) { | ||
return false; | ||
} | ||
|
||
if (accessMap.put(hash, currentTime) == null) { | ||
accessDeque.addLast(hash); | ||
// If we added a new entry, we perform purging. | ||
cleanupExpiredEntries(currentTime); | ||
} else { | ||
// This is now the most recently accessed entry. | ||
accessDeque.remove(hash); | ||
accessDeque.addLast(hash); | ||
} | ||
|
||
return true; | ||
} | ||
|
||
private boolean isApiAccessExpired(final long hash) { | ||
final long currentTime = timeSource.getCurrentTimeMillis(); | ||
final Long lastAccess = accessMap.get(hash); | ||
return lastAccess == null || currentTime - lastAccess >= expirationTimeInMs; | ||
} | ||
|
||
private void cleanupExpiredEntries(final long currentTime) { | ||
// Purge all expired entries. | ||
while (!accessDeque.isEmpty()) { | ||
final Long oldestHash = accessDeque.peekFirst(); | ||
if (oldestHash == null) { | ||
// Should never happen | ||
continue; | ||
} | ||
|
||
final Long lastAccessTime = accessMap.get(oldestHash); | ||
if (lastAccessTime == null) { | ||
// Should never happen | ||
continue; | ||
} | ||
|
||
if (currentTime - lastAccessTime < expirationTimeInMs) { | ||
// The oldest hash is up-to-date, so stop here. | ||
break; | ||
} | ||
|
||
accessDeque.pollFirst(); | ||
accessMap.remove(oldestHash); | ||
} | ||
|
||
// If we went over capacity, remove the oldest entries until we are within the limit. | ||
// This should never be more than 1. | ||
final int toRemove = accessMap.size() - this.capacity; | ||
for (int i = 0; i < toRemove; i++) { | ||
Long oldestHash = accessDeque.pollFirst(); | ||
if (oldestHash != null) { | ||
accessMap.remove(oldestHash); | ||
} | ||
} | ||
} | ||
|
||
private long computeApiHash(final String route, final String method, final int statusCode) { | ||
long result = 17; | ||
result = 31 * result + route.hashCode(); | ||
result = 31 * result + method.hashCode(); | ||
result = 31 * result + statusCode; | ||
return result; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: Same remark about current time millis as in #8178 (comment),
currentTimeMillis
is not monotonic, and is subject to DST, NTP syncs, leap seconds.nanoTime
might be better suited.