From f08ce36298008f570929b3fbe1bf57e2bd2e19cc Mon Sep 17 00:00:00 2001 From: Alessandro Lattao Date: Thu, 22 Oct 2026 18:42:30 +0200 Subject: [PATCH] refactor(dsql): read a token's expiry from the validator (#6246) * refactor(dsql): read a token's expiry from the validator DSQL's endpoint worked out a token's expiry for its "Signature expired" hint, and SigV4RequestValidator worked it out again to judge the token, each with its own parsing (a long against an int, its own date formatter). The validator now exposes the expiry it judges, and the hint reports that one, so the two cannot disagree. A date or an expiry that does not parse, or one past what an Instant holds, gives no expiry, and the token is refused as before. * fix(dsql): read a token's expiry seconds as an int, as validate did The shared expiry parsed X-Amz-Expires as a long, so a signed token whose expiry no int holds, which validate used to refuse, was taken: a refactor that widened what is accepted. It reads the seconds as an int again, and the DSQL token helper signs a long so a test can sign one past an int. --- .../common/auth/SigV4RequestValidator.java | 34 +++++++++++++-- .../services/dsql/dataplane/DsqlEndpoint.java | 23 +++------- .../auth/SigV4RequestValidatorTest.java | 43 +++++++++++++++++++ .../floci/testutil/SigV4TokenTestHelper.java | 6 +-- 4 files changed, 84 insertions(+), 22 deletions(-) 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.java index 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 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 expiry(String rawQuery) { + List parameters = decodeQuery(rawQuery); + return expiry(findParam(parameters, "X-Amz-Date"), findParam(parameters, "X-Amz-Expires")); + } + + private static Optional 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 acts diff --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.java index 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: is now earlier than ( - 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 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.java index 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.java index 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 params = new LinkedHashMap<>(); @@ -231,7 +231,7 @@ public final class SigV4TokenTestHelper { String region, String service, Instant timestamp, - int expiresSeconds, + long expiresSeconds, Map params, Map 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)