test(auth): add SigV4 validator unit tests for RDS and ElastiCache proxies (#361)

* test(auth): add SigV4 validator unit tests for RDS proxy

Direct unit tests against RdsSigV4Validator that bypass the disabled
global floci.auth.validate-signatures flag (application.yml:36). Real
SigV4-sensitive behavior cannot be asserted from the running Floci
test harness, so validator-level tests are the only path to real-auth
coverage.

Covers three cases:
- accept: token signed with host:port
- reject: signature omits port from canonical host header
- reject: expired token (beyond X-Amz-Expires)
This commit is contained in:
TiM authored and GitHub committed 2026-04-12 02:15:49 -05:00
1 parent 093a465bde
commit c227c3cd4a
5 files changed
+592

No files matched your search

@@ -0,0 +1,173 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SigV4ValidatorTest {
@Test
void validateAcceptsTokenForMatchingReplicationGroup() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String token = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
assertTrue(validator.validate(token, "cache-cluster-01"));
assertTrue(validator.validate(token, "CACHE-CLUSTER-01"));
}
@Test
void validateRejectsTokenForDifferentReplicationGroup() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String token = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
assertFalse(validator.validate(token, "other-cluster"));
}
@Test
void validateRejectsTamperedSignature() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
String tamperedToken = validToken.replace("User=default", "User=other");
assertFalse(validator.validate(tamperedToken, "cache-cluster-01"));
}
@Test
void validateAcceptsTokenWhenExpectedGroupIsNull() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String token = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
assertTrue(validator.validate(token, null));
}
@Test
void validateRejectsExpiredToken() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String token = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(1200),
900
);
assertFalse(validator.validate(token, "cache-cluster-01"));
}
@Test
void validateRejectsTokenWithUnknownAccessKey() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String token = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDUNKNOWN",
"wrong-secret",
Instant.now().minusSeconds(60),
900
);
assertFalse(validator.validate(token, "cache-cluster-01"));
}
@Test
void validateAcceptsTokenWithUrlEncodedUser() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
// Username with characters that require URL encoding exercises the
// encoding path independently of the validator's decode logic
String token = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"user+name@domain.com",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
assertTrue(validator.validate(token, "cache-cluster-01"));
}
@Test
void validateRejectsTokenMissingActionParameter() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
String withoutAction = validToken.replaceFirst("Action=connect&", "");
assertFalse(validator.validate(withoutAction, "cache-cluster-01"));
}
@Test
void validateRejectsTokenMissingSignatureParameter() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
SigV4Validator validator = new SigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createElastiCacheToken(
"cache-cluster-01",
"default",
"AKIDCACHE",
"secret-cache",
Instant.now().minusSeconds(60),
900
);
String withoutSignature = validToken.replaceFirst("&X-Amz-Signature=[0-9a-f]+", "");
assertFalse(validator.validate(withoutSignature, "cache-cluster-01"));
}
}
@@ -0,0 +1,219 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsUtilities;
import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RdsSigV4ValidatorTest {
/**
* Uses the real AWS SDK RDS presigner as an independent SigV4 oracle.
* If this test passes, the validator is compatible with tokens generated
* by actual AWS SDK clients, not just our hand-rolled test helper.
*/
@Test
void validateAcceptsTokenFromAwsSdkPresigner() throws Exception {
String accessKeyId = "AKIAORACLETEST";
String secretAccessKey = "oracle-secret-key-value";
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey(accessKeyId, secretAccessKey);
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
RdsUtilities utilities = RdsUtilities.builder()
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKeyId, secretAccessKey)))
.region(Region.US_EAST_1)
.build();
String sdkToken = utilities.generateAuthenticationToken(
GenerateAuthenticationTokenRequest.builder()
.hostname("db.oracle-test.local")
.port(5432)
.username("testuser")
.build());
assertTrue(validator.validate(sdkToken),
"Validator must accept tokens generated by the official AWS SDK RDS presigner");
}
@Test
void validateAcceptsTokenSignedWithHostAndPort() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String token = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
assertTrue(validator.validate(token));
}
@Test
void validateRejectsTokenWhenSignedForHostWithoutPort() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
String brokenToken = validToken.replace("db.example.local:5432/?", "db.example.local/?");
assertFalse(validator.validate(brokenToken));
}
@Test
void validateRejectsExpiredToken() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String token = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(1200),
900
);
assertFalse(validator.validate(token));
}
@Test
void validateRejectsTamperedSignature() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
String tamperedToken = validToken.replace("DBUser=admin", "DBUser=attacker");
assertFalse(validator.validate(tamperedToken));
}
@Test
void validateRejectsTokenWithUnknownAccessKey() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String token = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDUNKNOWN",
"wrong-secret",
Instant.now().minusSeconds(60),
900
);
assertFalse(validator.validate(token));
}
@Test
void validateRejectsTokenMissingDbUser() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
String withoutDbUser = validToken.replaceFirst("DBUser=admin&", "");
assertFalse(validator.validate(withoutDbUser));
}
@Test
void validateAcceptsTokenWithUrlEncodedDbUser() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
// Username with characters that require URL encoding exercises the
// encoding path independently of the validator's decode logic
String token = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"db+admin@example.com",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
assertTrue(validator.validate(token));
}
@Test
void validateRejectsTokenWithWrongRegion() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String token = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
// Tampering with the region in the credential scope invalidates the signature
String tamperedToken = token.replace("us-east-1", "eu-west-1");
assertFalse(validator.validate(tamperedToken));
}
@Test
void validateRejectsTokenMissingSignatureParameter() throws Exception {
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
String validToken = SigV4TokenTestHelper.createRdsToken(
"db.example.local",
5432,
"admin",
"AKIDRDS",
"secret-rds",
Instant.now().minusSeconds(60),
900
);
String withoutSignature = validToken.replaceFirst("&X-Amz-Signature=[0-9a-f]+", "");
assertFalse(validator.validate(withoutSignature));
}
}
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import java.lang.reflect.Constructor;
public final class IamServiceTestHelper {
private IamServiceTestHelper() {
}
@SuppressWarnings("unchecked")
public static IamService iamServiceWithAccessKey(String accessKeyId, String secretAccessKey) {
try {
Constructor<IamService> constructor = IamService.class.getDeclaredConstructor(
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
StorageBackend.class,
String.class
);
constructor.setAccessible(true);
InMemoryStorage<String, AccessKey> accessKeys = new InMemoryStorage<>();
accessKeys.put(accessKeyId, new AccessKey(accessKeyId, secretAccessKey, "test-user"));
return constructor.newInstance(
null,
null,
null,
null,
accessKeys,
null,
"123456789012"
);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Failed to construct IamService test fixture", e);
}
}
}
@@ -0,0 +1,142 @@
package io.github.hectorvent.floci.testutil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class SigV4TokenTestHelper {
private static final DateTimeFormatter DATETIME_FMT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private SigV4TokenTestHelper() {
}
public static String createElastiCacheToken(
String clusterId,
String user,
String accessKeyId,
String secretKey,
Instant timestamp,
int expiresSeconds
) throws Exception {
Map<String, String> params = new LinkedHashMap<>();
params.put("Action", "connect");
params.put("User", user);
return signToken(clusterId, null, clusterId, accessKeyId, secretKey, "us-east-1",
"elasticache", timestamp, expiresSeconds, params);
}
public static String createRdsToken(
String host,
int port,
String dbUser,
String accessKeyId,
String secretKey,
Instant timestamp,
int expiresSeconds
) throws Exception {
Map<String, String> params = new LinkedHashMap<>();
params.put("Action", "connect");
params.put("DBUser", dbUser);
return signToken(host, port, host + ":" + port, accessKeyId, secretKey, "us-east-1",
"rds-db", timestamp, expiresSeconds, params);
}
private static String signToken(
String host,
Integer port,
String canonicalHostHeader,
String accessKeyId,
String secretKey,
String region,
String service,
Instant timestamp,
int expiresSeconds,
Map<String, String> params
) throws Exception {
String date = DateTimeFormatter.BASIC_ISO_DATE.withZone(ZoneOffset.UTC).format(timestamp);
String dateTime = DATETIME_FMT.format(timestamp);
String credentialScope = date + "/" + region + "/" + service + "/aws4_request";
Map<String, String> queryParams = new LinkedHashMap<>(params);
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-SignedHeaders", "host");
List<String> encodedPairs = new ArrayList<>();
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
encodedPairs.add(entry.getKey() + "=" + urlEncode(entry.getValue()));
}
String canonicalQuery = encodedPairs.stream()
.sorted(Comparator.comparing(SigV4TokenTestHelper::rawParamName))
.reduce((a, b) -> a + "&" + b)
.orElse("");
String canonicalRequest = "GET\n/\n"
+ canonicalQuery + "\n"
+ "host:" + canonicalHostHeader + "\n\n"
+ "host\n"
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
String stringToSign = "AWS4-HMAC-SHA256\n"
+ dateTime + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(secretKey, date, region, service);
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
String authority = port == null ? host : host + ":" + port;
return authority + "/?" + canonicalQuery + "&X-Amz-Signature=" + signature;
}
private static String rawParamName(String rawPair) {
int eq = rawPair.indexOf('=');
return eq >= 0 ? rawPair.substring(0, eq) : rawPair;
}
private static String urlEncode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
private static byte[] deriveSigningKey(String secretKey, String date, String region,
String service) throws Exception {
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSha256(kSecret, date);
byte[] kRegion = hmacSha256(kDate, region);
byte[] kService = hmacSha256(kRegion, service);
return hmacSha256(kService, "aws4_request");
}
private static byte[] hmacSha256(byte[] key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}