refactor(ratelimit): policyId 문법과 기간 검사를 shared-contract 한 곳에 둔다 #93

Merged
donghyeon.kang merged 4 commits from refactor/ratelimit-shared-bounds into main 2026-11-22 00:51:34 +00:00
10 changed files with 189 additions and 73 deletions
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.ratelimit;
import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort;
import dev.caskeleton.shared.ratelimit.EdgeRateLimitSubject;
import dev.caskeleton.shared.ratelimit.EdgeSubjectPseudonymizer;
import dev.caskeleton.shared.ratelimit.RateLimitBounds;
import dev.caskeleton.shared.ratelimit.RateLimitOutcome;
import dev.caskeleton.shared.ratelimit.RateLimitRequest;
import dev.caskeleton.shared.ratelimit.RateLimitSubjectDigest;
@@ -11,7 +12,6 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Provider-neutral bridge from an HTTP request to {@link EdgeRateLimitPort}.
@@ -21,7 +21,6 @@ import java.util.regex.Pattern;
*/
public final class EdgeRateLimitTransportBridge {
private static final Pattern POLICY_ID = Pattern.compile("[a-z][a-z0-9-]{0,62}");
private static final Duration MAXIMUM_CALLER_DEADLINE_BUDGET = Duration.ofSeconds(30);
private final EdgeRateLimitPort port;
@@ -45,7 +44,7 @@ public final class EdgeRateLimitTransportBridge {
this.subjectResolver =
Objects.requireNonNull(subjectResolver, "subjectResolver must not be null");
this.clock = Objects.requireNonNull(clock, "clock must not be null");
if (policyId == null || !POLICY_ID.matcher(policyId).matches()) {
if (!RateLimitBounds.isPolicyId(policyId)) {
throw new IllegalArgumentException("policyId must be a bounded policy identifier");
}
this.policyId = policyId;
@@ -1,7 +1,7 @@
package dev.caskeleton.adapter.inbound.web.ratelimit;
import dev.caskeleton.shared.ratelimit.RateLimitBounds;
import java.time.Duration;
import java.util.regex.Pattern;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
@@ -15,15 +15,13 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
public record EdgeRateLimitTransportSettings(
boolean enabled, String defaultPolicyId, Duration callerDeadlineBudget, int hashKeyVersion) {
private static final Pattern POLICY_ID = Pattern.compile("[a-z][a-z0-9-]{0,62}");
public EdgeRateLimitTransportSettings {
defaultPolicyId =
defaultPolicyId == null || defaultPolicyId.isBlank() ? "api-default" : defaultPolicyId;
callerDeadlineBudget =
callerDeadlineBudget == null ? Duration.ofSeconds(2) : callerDeadlineBudget;
hashKeyVersion = hashKeyVersion == 0 ? 1 : hashKeyVersion;
if (!POLICY_ID.matcher(defaultPolicyId).matches()) {
if (!RateLimitBounds.isPolicyId(defaultPolicyId)) {
throw new IllegalArgumentException("defaultPolicyId must be a bounded policy identifier");
}
EdgeRateLimitTransportBridge.positiveBoundedBudget(
@@ -1,6 +1,7 @@
package dev.caskeleton.adapter.inbound.web.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
import dev.caskeleton.shared.ratelimit.EdgeRateLimitSubject;
@@ -13,8 +14,12 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -92,6 +97,38 @@ class EdgeRateLimitTransportBridgeTest {
.isEqualTo(Instant.parse("2026-07-29T01:00:00.750Z"));
}
/**
* The bridge checks its policy id against the shared contract's grammar when it is built and
* refuses it in its own words. The rows are null and the edges a loosened grammar would let
* through.
*/
@ParameterizedTest
@NullSource
@MethodSource("idsOutsideThePolicyIdGrammar")
void refusesAPolicyIdOutsideTheSharedGrammar(String policyId) {
Throwable failure =
catchThrowable(
() ->
new EdgeRateLimitTransportBridge(
request -> {
throw new AssertionError("the port must not be called");
},
subject -> new RateLimitSubjectDigest(DIGEST),
new RateLimitKeyResolver(),
CLOCK,
policyId,
Duration.ofMillis(750),
() -> EVALUATION_ID));
assertThat(failure)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("policyId must be a bounded policy identifier");
}
private static Stream<String> idsOutsideThePolicyIdGrammar() {
return Stream.of("Uppercase", "under_score", "9-digit-first", "a" + "b".repeat(63));
}
private static final class Capture {
private EdgeRateLimitSubject rawSubject;
@@ -2,9 +2,13 @@ package dev.caskeleton.adapter.inbound.web.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.time.Duration;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class EdgeRateLimitTransportSettingsTest {
@@ -39,4 +43,25 @@ class EdgeRateLimitTransportSettingsTest {
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("hashKeyVersion");
}
/**
* The default policy id is checked against the shared contract's grammar, the one a request
* carrying it must pass, so the two cannot drift. The rows are the edges a loosened grammar would
* let through.
*/
@ParameterizedTest
@MethodSource("idsOutsideThePolicyIdGrammar")
void rejectsADefaultPolicyIdOutsideTheSharedGrammar(String policyId) {
Throwable failure =
catchThrowable(
() -> new EdgeRateLimitTransportSettings(true, policyId, Duration.ofSeconds(1), 1));
assertThat(failure)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("defaultPolicyId must be a bounded policy identifier");
}
private static Stream<String> idsOutsideThePolicyIdGrammar() {
return Stream.of("Uppercase", "under_score", "9-digit-first", "a" + "b".repeat(63));
}
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.cache.redis.ratelimit;
import dev.caskeleton.shared.ratelimit.RateLimitBounds;
import java.time.Duration;
import java.util.Objects;
@@ -31,7 +32,7 @@ public record RateLimitEvaluationDedupPolicy(
"disabled evaluation dedup must not allocate TTL, entries, or stored bytes");
}
} else {
RateLimitPolicyBounds.positiveDuration(timeToLive, "timeToLive", MAXIMUM_TIME_TO_LIVE);
RateLimitBounds.positiveDuration(timeToLive, "timeToLive", MAXIMUM_TIME_TO_LIVE);
if (maximumEntries < 1 || maximumEntries > MAXIMUM_ENTRIES) {
throw new IllegalArgumentException("maximumEntries must be in 1.." + MAXIMUM_ENTRIES);
}
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.cache.redis.ratelimit;
import dev.caskeleton.shared.ratelimit.RateLimitBounds;
import dev.caskeleton.shared.ratelimit.RateParameters;
import java.time.Duration;
import java.util.Objects;
@@ -39,17 +40,17 @@ public record RateLimitPolicy(
}
public RateLimitPolicy {
RateLimitPolicyBounds.policyId(policyId);
RateLimitPolicyBounds.policyRevision(policyRevision);
RateLimitBounds.policyId(policyId);
RateLimitBounds.policyRevision(policyRevision);
Objects.requireNonNull(algorithm, "algorithm must not be null");
Objects.requireNonNull(parameters, "parameters must not be null");
if (maximumCost <= 0 || maximumCost > RateParameters.MAXIMUM_EXACT_INTEGER) {
throw new IllegalArgumentException(
"maximumCost must be positive and within Lua's exact integer range");
}
RateLimitPolicyBounds.positiveDuration(
RateLimitBounds.positiveDuration(
cleanupGrace, "cleanupGrace", RateLimitPolicyBounds.MAXIMUM_CLEANUP_GRACE);
RateLimitPolicyBounds.nonNegativeDuration(
RateLimitBounds.nonNegativeDuration(
maximumClockRegression,
"maximumClockRegression",
RateLimitPolicyBounds.MAXIMUM_CLOCK_REGRESSION);
@@ -1,70 +1,21 @@
package dev.caskeleton.adapter.outbound.cache.redis.ratelimit;
import java.time.Duration;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* The bounds a Redis rate-limit policy is validated against.
* The bounds only a Redis rate-limit policy has.
*
* <p>The policy is this adapter's configuration, not a shared contract, so its bounds live with it.
* The identifier grammars match the ones {@code shared-contract} applies to a request, because a
* request names the policy by the same identifier.
* <p>The policy is this adapter's configuration, not a shared contract, so these maximums live with
* it. The checks themselves are the contract's own ({@link
* dev.caskeleton.shared.ratelimit.RateLimitBounds}): the identifier grammars because a request
* names the policy by the same identifier, and the duration checks so the positive, bounded,
* whole-millisecond rule has one copy. The evaluation dedup maximums live on {@link
* RateLimitEvaluationDedupPolicy} itself.
*/
final class RateLimitPolicyBounds {
static final Duration MAXIMUM_CLEANUP_GRACE = Duration.ofDays(1);
static final Duration MAXIMUM_CLOCK_REGRESSION = Duration.ofHours(1);
private static final Pattern POLICY_ID = Pattern.compile("[a-z][a-z0-9-]{0,62}");
private static final Pattern POLICY_REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,63}");
private RateLimitPolicyBounds() {}
static String policyId(String value) {
return boundedIdentifier(value, "policyId", POLICY_ID);
}
static String policyRevision(String value) {
return boundedIdentifier(value, "policyRevision", POLICY_REVISION);
}
static Duration positiveDuration(Duration value, String field, Duration maximum) {
return duration(value, field, false, maximum);
}
static Duration nonNegativeDuration(Duration value, String field, Duration maximum) {
return duration(value, field, true, maximum);
}
private static String boundedIdentifier(String value, String field, Pattern pattern) {
Objects.requireNonNull(value, field + " must not be null");
if (!pattern.matcher(value).matches()) {
throw new IllegalArgumentException(field + " has an invalid bounded representation");
}
return value;
}
private static Duration duration(
Duration value, String field, boolean zeroAllowed, Duration maximum) {
Objects.requireNonNull(value, field + " must not be null");
if (value.isNegative() || (!zeroAllowed && value.isZero())) {
throw new IllegalArgumentException(
field + (zeroAllowed ? " must not be negative" : " must be positive"));
}
if (value.compareTo(maximum) > 0) {
throw new IllegalArgumentException(field + " exceeds its maximum duration of " + maximum);
}
long milliseconds;
try {
milliseconds = value.toMillis();
} catch (ArithmeticException exception) {
throw new IllegalArgumentException(
field + " exceeds the supported milliseconds range", exception);
}
if (!Duration.ofMillis(milliseconds).equals(value)) {
throw new IllegalArgumentException(field + " must use whole milliseconds");
}
return value;
}
}
@@ -2,11 +2,15 @@ package dev.caskeleton.adapter.outbound.cache.redis.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.shared.ratelimit.RateParameters;
import java.time.Duration;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class RateLimitPolicyTest {
@@ -159,6 +163,35 @@ class RateLimitPolicyTest {
assertThat(policy.evaluationDedupPolicy()).isEqualTo(RateLimitEvaluationDedupPolicy.disabled());
}
/**
* The policy id grammar is the shared contract's, so a grammar change there reaches this check
* too. The rows are the edges a loosened grammar would let through.
*/
@ParameterizedTest
@MethodSource("idsOutsideThePolicyIdGrammar")
void rejectsAPolicyIdOutsideTheSharedGrammar(String policyId) {
Throwable failure =
catchThrowable(
() ->
new RateLimitPolicy(
policyId,
"v3",
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(10, Duration.ofSeconds(1)),
1,
Duration.ofSeconds(5),
Duration.ofSeconds(1),
RateLimitFailurePolicy.FAIL_CLOSED));
assertThat(failure)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("policyId has an invalid bounded representation");
}
private static Stream<String> idsOutsideThePolicyIdGrammar() {
return Stream.of("Uppercase", "under_score", "9-digit-first", "a" + "b".repeat(63));
}
private static RateLimitPolicy policy(
RateLimitAlgorithm algorithm, RateParameters parameters, long maximumCost) {
return new RateLimitPolicy(
@@ -4,7 +4,15 @@ import java.time.Duration;
import java.util.Objects;
import java.util.regex.Pattern;
final class RateLimitBounds {
/**
* The identifier and duration bounds of the edge rate-limit contract.
*
* <p>This is the one copy of the grammars. A request names its policy by the same identifier a
* transport's settings and a provider's policy configuration name it by, so the web edge and the
* Redis adapter validate against these methods instead of keeping their own patterns. A grammar
* that diverged would let one side accept an id the other refuses at run time.
*/
public final class RateLimitBounds {
static final Duration MAXIMUM_WINDOW = Duration.ofDays(1);
static final Duration MAXIMUM_RETRY_AFTER =
@@ -19,11 +27,32 @@ final class RateLimitBounds {
private RateLimitBounds() {}
static String policyId(String value) {
/**
* Whether a value is a policy identifier, for a caller that reports the failure in its own words.
*
* @return true if the value matches the policy identifier grammar; false for null
*/
public static boolean isPolicyId(String value) {
return value != null && POLICY_ID.matcher(value).matches();
}
/**
* Checks a policy identifier.
*
* @throws NullPointerException if the value is null
* @throws IllegalArgumentException if the value does not match the policy identifier grammar
*/
public static String policyId(String value) {
return boundedIdentifier(value, "policyId", POLICY_ID);
}
static String policyRevision(String value) {
/**
* Checks a policy revision.
*
* @throws NullPointerException if the value is null
* @throws IllegalArgumentException if the value does not match the policy revision grammar
*/
public static String policyRevision(String value) {
return boundedIdentifier(value, "policyRevision", POLICY_REVISION);
}
@@ -39,11 +68,23 @@ final class RateLimitBounds {
return boundedIdentifier(value, "evaluationId", EVALUATION_ID);
}
static Duration positiveDuration(Duration value, String field, Duration maximum) {
/**
* Checks a duration that must be positive, at most {@code maximum}, and whole milliseconds.
*
* @throws NullPointerException if the value or the maximum is null
* @throws IllegalArgumentException if the value is out of bounds, naming {@code field}
*/
public static Duration positiveDuration(Duration value, String field, Duration maximum) {
return duration(value, field, false, maximum);
}
static Duration nonNegativeDuration(Duration value, String field, Duration maximum) {
/**
* Checks a duration that must not be negative, at most {@code maximum}, and whole milliseconds.
*
* @throws NullPointerException if the value or the maximum is null
* @throws IllegalArgumentException if the value is out of bounds, naming {@code field}
*/
public static Duration nonNegativeDuration(Duration value, String field, Duration maximum) {
return duration(value, field, true, maximum);
}
@@ -0,0 +1,30 @@
package dev.caskeleton.shared.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class RateLimitBoundsTest {
/** The predicate a transport reports in its own words answers the policy id grammar. */
@ParameterizedTest(name = "{0} -> {1}")
@MethodSource("policyIds")
void isPolicyIdAnswersThePolicyIdGrammar(String value, boolean expected) {
assertThat(RateLimitBounds.isPolicyId(value)).isEqualTo(expected);
}
private static Stream<Arguments> policyIds() {
return Stream.of(
Arguments.of("login", true),
Arguments.of("a" + "b".repeat(62), true),
Arguments.of("a" + "b".repeat(63), false),
Arguments.of("Uppercase", false),
Arguments.of("under_score", false),
Arguments.of("9-digit-first", false),
Arguments.of("", false),
Arguments.of(null, false));
}
}