Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(dsql): read a token's expiry from the validator (#6246)
Alessandro Lattaof08ce3629800
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.javaindex 2aa50c5a62..cbcd4473e6 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidator.java@@ -9,6 +9,7 @@ import javax.crypto.spec.SecretKeySpec;import java.net.URLDecoder;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;+import java.time.DateTimeException;import java.time.Duration;import java.time.Instant;import java.time.ZoneOffset;@@ -126,9 +127,12 @@ public final class SigV4RequestValidator {return false;}- Instant tokenTime = Instant.from(DATETIME_FMT.parse(dateTime));- int expirySeconds = Integer.parseInt(expires);- if (Instant.now().minus(expiryGrace).isAfter(tokenTime.plusSeconds(expirySeconds))) {+ Optional<Instant> expiry = expiry(dateTime, expires);+ if (expiry.isEmpty()) {+ LOG.debugv("{0} has a date or expiry that does not parse", logLabel);+ return false;+ }+ if (Instant.now().minus(expiryGrace).isAfter(expiry.get())) {LOG.debugv("{0} expired", logLabel);return false;}@@ -199,6 +203,30 @@ public final class SigV4RequestValidator {private record QueryParameter(String name, String value) {}+ /**+ * When a token stops being valid, before any grace its service allows: its {@code X-Amz-Date}+ * plus {@code X-Amz-Expires} seconds, or empty when either is missing or does not parse, the+ * seconds as an {@code int}. A caller that reports the expiry, as Aurora DSQL's hint does, reads+ * it here, so it reports the one {@link #validate} judged.+ */+ public static Optional<Instant> expiry(String rawQuery) {+ List<QueryParameter> parameters = decodeQuery(rawQuery);+ return expiry(findParam(parameters, "X-Amz-Date"), findParam(parameters, "X-Amz-Expires"));+ }++ private static Optional<Instant> expiry(String dateTime, String expires) {+ if (dateTime == null || expires == null) {+ return Optional.empty();+ }+ try {+ return Optional.of(Instant.from(DATETIME_FMT.parse(dateTime)).plusSeconds(Integer.parseInt(expires)));+ } catch (DateTimeException | NumberFormatException ignored) {+ // A date or an expiry that does not parse sets no expiry, so the token it came with is+ // refused: one of more seconds than an int holds included, as validate always refused it.+ return Optional.empty();+ }+ }+/*** The value of {@code name} in a token's query string, read as {@link #validate} reads it: the* first parameter whose percent-decoded name matches, its value decoded once. A caller that actsdiff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.javaindex d06e08c52a..a004ba5a9c 100644--- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java@@ -37,6 +37,7 @@ import java.time.format.DateTimeFormatter;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.Optional;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;@@ -362,26 +363,16 @@ public class DsqlEndpoint {* {@code Signature expired: <expiry> is now earlier than <now - 5 s> (<now> - 0 min.)}.*/private static String expiredHint(String rawQuery) {- String date = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Date");- String expires = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Expires");- if (date == null || expires == null) {- return null;- }- Instant expiry;- try {- expiry = Instant.from(AMZ_DATE.parse(date)).plusSeconds(Long.parseLong(expires));- } catch (RuntimeException ignored) {- // A date or expiry that does not parse gets no hint here: the signature check that- // follows refuses the token without one, as DSQL does.- return null;- }+ // A token without an expiry that parses gets no hint here: the signature check that+ // follows refuses it without one, as DSQL does.+ Optional<Instant> expiry = SigV4RequestValidator.expiry(rawQuery);Instant now = Instant.now();Instant earliest = now.minus(EXPIRY_GRACE);- if (!expiry.isBefore(earliest)) {+ if (expiry.isEmpty() || !expiry.get().isBefore(earliest)) {return null;}- return "Signature expired: " + AMZ_DATE.format(expiry) + " is now earlier than " + AMZ_DATE.format(earliest)- + " (" + AMZ_DATE.format(now) + " - 0 min.)";+ return "Signature expired: " + AMZ_DATE.format(expiry.get()) + " is now earlier than "+ + AMZ_DATE.format(earliest) + " (" + AMZ_DATE.format(now) + " - 0 min.)";}/**diff --git a/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidatorTest.java b/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidatorTest.javaindex 0d2c191344..5acaba8050 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4RequestValidatorTest.java@@ -12,6 +12,7 @@ import org.junit.jupiter.params.provider.ValueSource;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.time.Instant;+import java.util.Optional;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;@@ -170,6 +171,48 @@ class SigV4RequestValidatorTest {false, null, "DSQL IAM token", null, Duration.ofSeconds(5)));}+ @Test+ void expiryIsTheTokensDatePlusItsExpiresSeconds() throws Exception {+ Instant signedAt = Instant.parse("2026-10-22T10:15:30Z");+ String token = SigV4TokenTestHelper.createDsqlToken("abc.dsql.eu-west-1.localhost.floci.io", "eu-west-1",+ "DbConnectAdmin", "AKIDDSQL", "secret-dsql", signedAt, 900, null);++ assertEquals(Optional.of(signedAt.plusSeconds(900)),+ SigV4RequestValidator.expiry(token.substring(token.indexOf('?') + 1)));+ }++ /** A token without a date and an expiry that both parse has no expiry. */+ @ParameterizedTest+ @ValueSource(strings = {+ "X-Amz-Date=20261022T101530Z",+ "X-Amz-Expires=900",+ "X-Amz-Date=20261022T101530Z&X-Amz-Expires=soon",+ "X-Amz-Date=yesterday&X-Amz-Expires=900",+ "X-Amz-Date=20261022T101530Z&X-Amz-Expires=2147483648",+ "X-Amz-Date=20261022T101530Z&X-Amz-Expires=9223372036854775807"})+ void expiryIsEmptyWithoutADateAndAnExpiryThatParse(String rawQuery) {+ assertEquals(Optional.empty(), SigV4RequestValidator.expiry(rawQuery));+ }++ /**+ * A signed token whose expiry is more seconds than an int holds is refused, as it always was,+ * while the same token one second shorter is taken.+ */+ @Test+ void validateRefusesASignedTokenWhoseExpiryIsPastAnInt() throws Exception {+ IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDDSQL", "secret-dsql");+ SigV4RequestValidator validator = new SigV4RequestValidator(iamService);+ String host = "abc.dsql.eu-west-1.localhost.floci.io";+ for (long expires : new long[] {Integer.MAX_VALUE, Integer.MAX_VALUE + 1L}) {+ String token = SigV4TokenTestHelper.createDsqlToken(host, "eu-west-1", "DbConnectAdmin", "AKIDDSQL",+ "secret-dsql", Instant.now(), expires, null);+ String rawQuery = token.substring(token.indexOf('?') + 1);++ assertEquals(expires == Integer.MAX_VALUE, validator.validate(rawQuery, host, "DbConnectAdmin", "DBUser",+ false, null, "DSQL IAM token", null, Duration.ofSeconds(5)), "X-Amz-Expires=" + expires);+ }+ }+private static boolean validate(IamService iamService, String token) {String rawQuery = token.substring(token.indexOf('?') + 1);return new SigV4RequestValidator(iamService).validate(diff --git a/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java b/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.javaindex a0df30e7f0..87b0db4a44 100644--- a/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java+++ b/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java@@ -127,7 +127,7 @@ public final class SigV4TokenTestHelper {String accessKeyId,String secretKey,Instant timestamp,- int expiresSeconds,+ long expiresSeconds,String sessionToken) throws Exception {Map<String, String> params = new LinkedHashMap<>();@@ -231,7 +231,7 @@ public final class SigV4TokenTestHelper {String region,String service,Instant timestamp,- int expiresSeconds,+ long expiresSeconds,Map<String, String> params,Map<String, String> signedHeaders) throws Exception {@@ -243,7 +243,7 @@ public final class SigV4TokenTestHelper {queryParams.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256");queryParams.put("X-Amz-Credential", accessKeyId + "/" + credentialScope);queryParams.put("X-Amz-Date", dateTime);- queryParams.put("X-Amz-Expires", Integer.toString(expiresSeconds));+ queryParams.put("X-Amz-Expires", Long.toString(expiresSeconds));String signedHeaderNames = signedHeaders.keySet().stream().sorted().reduce((left, right) -> left + ";" + right)