fix(iam): use SecureRandom for secret credentials and tokens (#3960)

This commit is contained in:
danielvanza authored and GitHub committed 2026-09-20 16:17:50 -04:00
1 parent a03b00ce89
commit 94976360ac
7 files changed
+191 -7

No files matched your search

@@ -915,6 +915,18 @@ class IamServiceTest {
assertEquals(1, keys.size());
}
@Test
void accessKeySecretsAreFortyCharsAndUnique() {
iamService.createUser("alice", "/");
iamService.createUser("bob", "/");
AccessKey first = iamService.createAccessKey("alice");
AccessKey second = iamService.createAccessKey("bob");
assertEquals(40, first.getSecretAccessKey().length());
assertEquals(40, second.getSecretAccessKey().length());
assertNotEquals(first.getSecretAccessKey(), second.getSecretAccessKey());
}
@Test
void createThirdAccessKeyFails() {
iamService.createUser("alice", "/");
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.iam;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Guards the security-material generators against regressing to a non-CSPRNG source. Ordinary
* resource IDs may keep using {@code ThreadLocalRandom}; credentials, session tokens, grant tokens,
* and data keys must not.
*/
class SecurityMaterialRandomnessTest {
private static final Path IAM_SERVICE =
Path.of("src/main/java/io/github/hectorvent/floci/services/iam/IamService.java");
private static final Path STS_HANDLER =
Path.of("src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java");
private static final Path KMS_SERVICE =
Path.of("src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java");
private static final Pattern RANDOM_SECRET_DECLARATION =
Pattern.compile("private\\s+String\\s+randomSecret\\s*\\(int\\s+length\\)");
@Test
void iamAndStsSecretGeneratorsDoNotUseThreadLocalRandom() throws IOException {
assertSecretGeneratorUsesSecureRandom(IAM_SERVICE);
assertSecretGeneratorUsesSecureRandom(STS_HANDLER);
}
@Test
void kmsServiceDoesNotImportThreadLocalRandom() throws IOException {
assertFalse(Files.readString(KMS_SERVICE).contains("ThreadLocalRandom"),
"KMS security material must come from SecureRandom, not ThreadLocalRandom");
}
private static void assertSecretGeneratorUsesSecureRandom(Path file) throws IOException {
String source = Files.readString(file);
Matcher declaration = RANDOM_SECRET_DECLARATION.matcher(source);
assertTrue(declaration.find(), "no randomSecret(int length) declaration in " + file);
int bodyStart = source.indexOf('{', declaration.end());
assertTrue(bodyStart >= 0, "no body for randomSecret in " + file);
String body = source.substring(bodyStart, matchingBrace(source, bodyStart) + 1);
assertTrue(body.contains("secureRandom"),
"randomSecret in " + file + " must draw from the SecureRandom field");
assertFalse(body.contains("ThreadLocalRandom"),
"randomSecret in " + file + " must use SecureRandom, not ThreadLocalRandom");
}
private static int matchingBrace(String source, int openIndex) {
int depth = 0;
for (int i = openIndex; i < source.length(); i++) {
char c = source.charAt(i);
if (c == '{') {
depth++;
} else if (c == '}') {
depth--;
if (depth == 0) {
return i;
}
}
}
throw new IllegalArgumentException("unbalanced braces from index " + openIndex);
}
}
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class StsQueryHandlerTest {
private static final String REGION = "us-east-1";
private static final Pattern SECRET_ACCESS_KEY =
Pattern.compile("<SecretAccessKey>([^<]+)</SecretAccessKey>");
private static final Pattern SESSION_TOKEN =
Pattern.compile("<SessionToken>([^<]+)</SessionToken>");
private static StsQueryHandler newHandler() {
return new StsQueryHandler(
mock(IamService.class),
mock(AccountResolver.class),
new RegionResolver(REGION, "000000000000"),
mock(EmulatorConfig.class),
mock(AssumeRolePolicyEvaluator.class),
mock(WebIdentityTrustPolicyEvaluator.class),
mock(WebIdentityTokenVerifier.class),
mock(OidcIssuerKeyLookup.class),
mock(SAMLProviderService.class),
mock(SAMLTrustPolicyEvaluator.class));
}
@Test
void getSessionTokenIssuesFortyCharSecretAndTwoHundredCharToken() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
Response response = newHandler().handle("GetSessionToken", params);
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertEquals(40, extract(SECRET_ACCESS_KEY, body).length());
assertEquals(200, extract(SESSION_TOKEN, body).length());
}
@Test
void getSessionTokensAreUniqueAcrossCalls() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
String firstBody = (String) newHandler().handle("GetSessionToken", params).getEntity();
String secondBody = (String) newHandler().handle("GetSessionToken", params).getEntity();
assertNotEquals(extract(SECRET_ACCESS_KEY, firstBody), extract(SECRET_ACCESS_KEY, secondBody));
assertNotEquals(extract(SESSION_TOKEN, firstBody), extract(SESSION_TOKEN, secondBody));
}
private static String extract(Pattern pattern, String body) {
Matcher matcher = pattern.matcher(body);
assertTrue(matcher.find(), "expected " + pattern + " in " + body);
return matcher.group(1);
}
}
@@ -195,6 +195,30 @@ class KmsServiceTest {
assertEquals(false, result.get("Truncated"));
}
@Test
void grantTokensAreUniqueUrlSafeBase64Of32Bytes() {
KmsKey key = kmsService.createKey("csprng grant key", REGION);
KmsGrant first = kmsService.createGrant(key.getKeyId(),
"arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION);
KmsGrant second = kmsService.createGrant(key.getKeyId(),
"arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION);
assertEquals(43, first.getGrantToken().length());
assertNotEquals(first.getGrantToken(), second.getGrantToken());
}
@Test
void generatedDataKeyPlaintextsAreUniqueAndRequestedLength() {
KmsKey key = kmsService.createKey("csprng data key", REGION);
byte[] first = (byte[]) kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION).get("Plaintext");
byte[] second = (byte[]) kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION).get("Plaintext");
assertEquals(32, first.length);
assertFalse(Arrays.equals(first, second));
}
@Test
void createGrantMissingKeyIdThrowsValidation() {
AwsException ex = assertThrows(AwsException.class, () ->