From 9df5cad4d820aaa7b31222884a7163037be4f8ba Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 05:36:34 +0900 Subject: [PATCH 1/3] =?UTF-8?q?refactor(ratelimit):=20policyId=20=EB=AC=B8?= =?UTF-8?q?=EB=B2=95=EA=B3=BC=20=EA=B8=B0=EA=B0=84=20=EA=B2=80=EC=82=AC?= =?UTF-8?q?=EB=A5=BC=20shared-contract=20=ED=95=9C=20=EA=B3=B3=EC=97=90=20?= =?UTF-8?q?=EB=91=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit policyId 정규식([a-z][a-z0-9-]{0,62})이 rate-limit main에 네 벌 있었다. shared-contract RateLimitBounds, cache-redis RateLimitPolicyBounds, web EdgeRateLimitTransportBridge· EdgeRateLimitTransportSettings다. redis 사본은 policyRevision과 duration 검사(null·음수·0·상한·toMillis·whole-ms 순서와 메시지)도 줄 단위로 베꼈다. 정본 RateLimitBounds가 package-private이라 다른 패키지에서 부를 수 없어서다. 한 곳만 문법을 바꾸면 web 설정이 받아들인 id를 RateLimitRequest가 실행 중에 거절하는 엇갈림이 생긴다. - RateLimitBounds를 public으로 열고 policyId·policyRevision· positiveDuration·nonNegativeDuration을 public으로 둔다. 자기 말로 거절을 알리는 쪽을 위해 isPolicyId(null이면 false)를 더한다. subjectDigest·optionalEvaluationId와 상수는 그대로 package-private이다. - redis RateLimitPolicy·RateLimitEvaluationDedupPolicy는 정본을 부르고, RateLimitPolicyBounds에는 redis만의 상한 상수 둘만 남긴다. - web 둘은 isPolicyId를 부르고 자기 오류 메시지("policyId|defaultPolicyId must be a bounded policy identifier")와 null 처리(IAE)를 그대로 둔다. - 시험: shared-contract RateLimitBoundsTest(isPolicyId 표), redis RateLimitPolicyTest·web EdgeRateLimitTransportSettingsTest에 문법 밖 id 네 행(대문자, 밑줄, 숫자로 시작, 64자) 거절. redis에는 policyId 거절 시험이 없었다. 정규식 문법과 오류 메시지는 바꾸지 않았다. 버린 안: 사본 사이에 같은 값을 보는 대조 시험(사본을 두는 비용이 그대로다), RateLimitPolicyId 값 타입(공개 타입과 호출부가 더 바뀐다). 위험·한계: shared-contract 공개 API가 public 클래스 하나·메서드 다섯 늘어난다. application-core LeaseValidation의 같은 정규식은 lease 식별자라 이 변경 밖이다. 검증: desktop RED·GREEN은 PR 본문에 둔다. Refs: REV-BE-0040 --- .../EdgeRateLimitTransportBridge.java | 5 +- .../EdgeRateLimitTransportSettings.java | 6 +- .../EdgeRateLimitTransportSettingsTest.java | 25 ++++++++ .../RateLimitEvaluationDedupPolicy.java | 3 +- .../redis/ratelimit/RateLimitPolicy.java | 9 +-- .../ratelimit/RateLimitPolicyBounds.java | 61 ++----------------- .../redis/ratelimit/RateLimitPolicyTest.java | 33 ++++++++++ .../shared/ratelimit/RateLimitBounds.java | 51 ++++++++++++++-- .../shared/ratelimit/RateLimitBoundsTest.java | 30 +++++++++ 9 files changed, 150 insertions(+), 73 deletions(-) create mode 100644 src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridge.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridge.java index 00303de4..645ad4c6 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridge.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridge.java @@ -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; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettings.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettings.java index 7a3e8507..9a97f0d1 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettings.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettings.java @@ -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( diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettingsTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettingsTest.java index ce6a42dd..8384b1ef 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettingsTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportSettingsTest.java @@ -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 idsOutsideThePolicyIdGrammar() { + return Stream.of("Uppercase", "under_score", "9-digit-first", "a" + "b".repeat(63)); + } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java index cad1be53..323d7a05 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java @@ -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); } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java index fbcd0cc3..ab1c2d25 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java @@ -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); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java index 82eb9e90..2310fff1 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java @@ -1,70 +1,19 @@ 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. * - *

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. + *

The policy is this adapter's configuration, not a shared contract, so these maximums live with + * it. The identifier grammars and the duration checks are the contract's own ({@link + * dev.caskeleton.shared.ratelimit.RateLimitBounds}), because a request names the policy by the same + * identifier. */ 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; - } } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java index bec3982c..bec224d1 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java @@ -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 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( diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java index 680e5fae..8fc9a3e2 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java @@ -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. + * + *

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 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); } diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java new file mode 100644 index 00000000..2cd60fac --- /dev/null +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java @@ -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 exactly what policyId accepts. */ + @ParameterizedTest(name = "{0} -> {1}") + @MethodSource("policyIds") + void isPolicyIdAnswersThePolicyIdGrammar(String value, boolean expected) { + assertThat(RateLimitBounds.isPolicyId(value)).isEqualTo(expected); + } + + private static Stream 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)); + } +} -- 2.54.0 From b64518f97aa45ae3d2711e35b697c031f468162e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 07:41:05 +0900 Subject: [PATCH 2/3] =?UTF-8?q?test(ratelimit):=20web=20bridge=EA=B0=80=20?= =?UTF-8?q?=EA=B3=B5=EC=9A=A9=20=EB=AC=B8=EB=B2=95=20=EB=B0=96=20policyId?= =?UTF-8?q?=EB=A5=BC=20=EA=B1=B0=EC=A0=88=ED=95=98=EB=8A=94=EC=A7=80=20?= =?UTF-8?q?=EC=8B=9C=ED=97=98=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 앞 커밋이 EdgeRateLimitTransportBridge의 policyId 검사를 RateLimitBounds.isPolicyId로 바꾸면서 null·문법 밖 id를 자기 메시지의 IllegalArgumentException으로 거절한다고 약속했다. 그런데 Bridge 시험은 정상 id 하나만 보고 있어서 이 검사를 지워도 모두 통과한다. 잘못된 id는 나중에 evaluate에서 RateLimitRequest가 다른 메시지로 거절할 뿐이다. Bridge 시험에 null과 문법 밖 네 행(대문자, 밑줄, 숫자 첫 글자, 64자)을 ParameterizedTest로 넣고 예외 타입과 메시지를 함께 단언한다. 행은 settings ·redis 시험과 같아서, 정본 정규식을 느슨하게 바꾸면 이 시험도 함께 실패한다. RateLimitBoundsTest의 설명은 시험이 실제로 보는 것 (isPolicyId가 문법에 답한다)만 말하게 줄인다. 위험·한계: 시험만 바뀐다. 운영 코드와 메시지는 그대로다. 검증: 커밋 전에는 돌리지 않았다. 최종 트리의 desktop leaf·pr 결과와 RED는 PR 본문에 있다. Refs: REV-BE-0040 --- .../EdgeRateLimitTransportBridgeTest.java | 37 +++++++++++++++++++ .../shared/ratelimit/RateLimitBoundsTest.java | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridgeTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridgeTest.java index 32a8861b..b9c41db9 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridgeTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/EdgeRateLimitTransportBridgeTest.java @@ -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 idsOutsideThePolicyIdGrammar() { + return Stream.of("Uppercase", "under_score", "9-digit-first", "a" + "b".repeat(63)); + } + private static final class Capture { private EdgeRateLimitSubject rawSubject; diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java index 2cd60fac..707c0ff9 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitBoundsTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.params.provider.MethodSource; class RateLimitBoundsTest { - /** The predicate a transport reports in its own words answers exactly what policyId accepts. */ + /** 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) { -- 2.54.0 From bb1f32d7deffc17bf0d9a6610dca3f91496ee284 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 07:41:05 +0900 Subject: [PATCH 3/3] =?UTF-8?q?docs(ratelimit):=20=EC=A0=95=EB=B3=B8?= =?UTF-8?q?=EA=B3=BC=20redis=20=EC=83=81=ED=95=9C=20=ED=81=B4=EB=9E=98?= =?UTF-8?q?=EC=8A=A4=EC=9D=98=20Javadoc=EC=9D=84=20=EC=8B=A4=EC=A0=9C=20?= =?UTF-8?q?=EC=B1=85=EC=9E=84=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RateLimitBounds.isPolicyId의 @return은 null일 때 false라는 것만 적고 true가 되는 조건을 적지 않는다. redis RateLimitPolicyBounds의 설명은 식별자 문법과 기간 검사를 정본에서 받는 이유를 하나(요청이 같은 id로 policy를 부른다)로 묶는데, 그 이유는 문법에만 맞는다. @return에 「문법과 맞으면 true, null이면 false」를 적는다. RateLimitPolicyBounds는 이유를 둘로 나누고(문법은 같은 id라서, 기간 검사는 양수·상한·whole-ms 규칙을 한 벌만 두려고), 같은 패키지의 dedup 상한은 RateLimitEvaluationDedupPolicy에 있다고 적는다. 상수 둘을 RateLimitPolicy로 옮기고 클래스를 지우는 안은 diff를 넓히는 데 비해 얻는 동작이 없어 버렸다. 위험·한계: 주석만 바뀐다. 검증: 커밋 전에는 돌리지 않았다. 최종 트리의 desktop leaf·pr 결과는 PR 본문에 있다. Refs: REV-BE-0040 --- .../cache/redis/ratelimit/RateLimitPolicyBounds.java | 8 +++++--- .../dev/caskeleton/shared/ratelimit/RateLimitBounds.java | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java index 2310fff1..b5563d90 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java @@ -6,9 +6,11 @@ import java.time.Duration; * The bounds only a Redis rate-limit policy has. * *

The policy is this adapter's configuration, not a shared contract, so these maximums live with - * it. The identifier grammars and the duration checks are the contract's own ({@link - * dev.caskeleton.shared.ratelimit.RateLimitBounds}), because a request names the policy by the same - * identifier. + * 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 { diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java index 8fc9a3e2..9892d2bd 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java @@ -30,7 +30,7 @@ public final class RateLimitBounds { /** * Whether a value is a policy identifier, for a caller that reports the failure in its own words. * - * @return false for null + * @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(); -- 2.54.0