Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cognito): support passkeys (WebAuthn) registration and sign-in (#5102)

outofplace5092713a6edf
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoWebAuthnTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoWebAuthnTest.java
new file mode 100644
index 0000000000..eb720cc759
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoWebAuthnTest.java
@@ -0,0 +1,265 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.GetUserPoolMfaConfigResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.InitiateAuthResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidParameterException;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.ListWebAuthnCredentialsResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.RespondToAuthChallengeResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolMfaType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UserVerificationType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.WebAuthnCredentialDescription;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.WebAuthnFactorConfigurationType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.WebAuthnNotEnabledException;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class CognitoWebAuthnTest {
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final String USERNAME = "passkey-sdk-user";
+ private static final String PASSWORD = "SdkPasskey123!";
+
+ @Test
+ @DisplayName("passkey registration and WEB_AUTHN sign-in through the SDK's document members")
+ void sdkRegistersAPasskeyAndSignsInWithIt() throws Exception {
+ try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
+ String poolId = cognito.createUserPool(b -> b.poolName("passkey-sdk-" + UUID.randomUUID())
+ .policies(p -> p.signInPolicy(s -> s.allowedFirstAuthFactorsWithStrings("PASSWORD", "WEB_AUTHN"))))
+ .userPool().id();
+ try {
+ cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId).mfaConfiguration(UserPoolMfaType.OFF)
+ .webAuthnConfiguration(w -> w.relyingPartyId("localhost")
+ .userVerification(UserVerificationType.PREFERRED)));
+ GetUserPoolMfaConfigResponse mfaConfig = cognito.getUserPoolMfaConfig(b -> b.userPoolId(poolId));
+ assertThat(mfaConfig.webAuthnConfiguration().relyingPartyId()).isEqualTo("localhost");
+ String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
+ .clientName("passkey-sdk-client")
+ .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH,
+ ExplicitAuthFlowsType.ALLOW_USER_AUTH))
+ .userPoolClient().clientId();
+ cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
+ .messageAction(MessageActionType.SUPPRESS));
+ cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
+ .password(PASSWORD).permanent(true));
+ String accessToken = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)))
+ .authenticationResult().accessToken();
+
+ Document options = cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken))
+ .credentialCreationOptions();
+ JsonNode creationOptions = toJson(options);
+ assertThat(creationOptions.path("rp").path("id").asText()).isEqualTo("localhost");
+
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
+ Document credential = toDocument(authenticator.register(creationOptions, "packed"));
+ cognito.completeWebAuthnRegistration(b -> b.accessToken(accessToken).credential(credential));
+
+ ListWebAuthnCredentialsResponse listed = cognito.listWebAuthnCredentials(b -> b.accessToken(accessToken));
+ assertThat(listed.credentials()).hasSize(1);
+ WebAuthnCredentialDescription description = listed.credentials().get(0);
+ assertThat(description.credentialId()).isEqualTo(authenticator.credentialId());
+ assertThat(description.relyingPartyId()).isEqualTo("localhost");
+ assertThat(description.createdAt()).isNotNull();
+
+ InitiateAuthResponse challenge = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", "WEB_AUTHN")));
+ assertThat(challenge.challengeName()).isEqualTo(ChallengeNameType.WEB_AUTHN);
+ String assertion = authenticator.authenticate(
+ challenge.challengeParameters().get("CREDENTIAL_REQUEST_OPTIONS"));
+ RespondToAuthChallengeResponse signedIn = cognito.respondToAuthChallenge(b -> b.clientId(clientId)
+ .challengeName(ChallengeNameType.WEB_AUTHN)
+ .session(challenge.session())
+ .challengeResponses(Map.of("USERNAME", USERNAME, "CREDENTIAL", assertion)));
+ assertThat(signedIn.authenticationResult().accessToken()).isNotBlank();
+
+ WebAuthnTestAuthenticator rsa = WebAuthnTestAuthenticator.rs256("http://localhost:5173");
+ JsonNode rsaOptions = toJson(cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken))
+ .credentialCreationOptions());
+ Document rsaCredential = toDocument(rsa.register(rsaOptions, "none"));
+ cognito.completeWebAuthnRegistration(b -> b.accessToken(accessToken).credential(rsaCredential));
+ InitiateAuthResponse rsaChallenge = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", "WEB_AUTHN")));
+ String rsaAssertion = rsa.authenticate(
+ rsaChallenge.challengeParameters().get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertThat(cognito.respondToAuthChallenge(b -> b.clientId(clientId)
+ .challengeName(ChallengeNameType.WEB_AUTHN)
+ .session(rsaChallenge.session())
+ .challengeResponses(Map.of("USERNAME", USERNAME, "CREDENTIAL", rsaAssertion)))
+ .authenticationResult().accessToken()).isNotBlank();
+
+ cognito.deleteWebAuthnCredential(b -> b.accessToken(accessToken)
+ .credentialId(authenticator.credentialId()));
+ cognito.deleteWebAuthnCredential(b -> b.accessToken(accessToken)
+ .credentialId(rsa.credentialId()));
+ assertThat(cognito.listWebAuthnCredentials(b -> b.accessToken(accessToken)).credentials()).isEmpty();
+ } finally {
+ cognito.deleteUserPool(b -> b.userPoolId(poolId));
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("a passkey stands in for required MFA only for a user who turned WebAuthnMfaSettings on")
+ void sdkTurnsPasskeyMfaOnPerUser() throws Exception {
+ try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
+ String poolId = cognito.createUserPool(b -> b.poolName("passkey-mfa-sdk-" + UUID.randomUUID())
+ .policies(p -> p.signInPolicy(s -> s.allowedFirstAuthFactorsWithStrings("PASSWORD", "WEB_AUTHN"))))
+ .userPool().id();
+ try {
+ cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId).mfaConfiguration(UserPoolMfaType.OFF)
+ .webAuthnConfiguration(w -> w.relyingPartyId("localhost")));
+ String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
+ .clientName("passkey-mfa-sdk-client")
+ .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH,
+ ExplicitAuthFlowsType.ALLOW_USER_AUTH))
+ .userPoolClient().clientId();
+ cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
+ .messageAction(MessageActionType.SUPPRESS));
+ cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
+ .password(PASSWORD).permanent(true));
+ String accessToken = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)))
+ .authenticationResult().accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
+ JsonNode creationOptions = toJson(cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken))
+ .credentialCreationOptions());
+ Document credential = toDocument(authenticator.register(creationOptions, "none"));
+ cognito.completeWebAuthnRegistration(b -> b.accessToken(accessToken).credential(credential));
+
+ assertThatThrownBy(() -> cognito.setUserMFAPreference(b -> b.accessToken(accessToken)
+ .webAuthnMfaSettings(w -> w.enabled(true))))
+ .isInstanceOf(InvalidParameterException.class);
+
+ cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId).mfaConfiguration(UserPoolMfaType.ON)
+ .softwareTokenMfaConfiguration(t -> t.enabled(true))
+ .webAuthnConfiguration(w -> w.relyingPartyId("localhost")
+ .factorConfiguration(WebAuthnFactorConfigurationType.MULTI_FACTOR_WITH_USER_VERIFICATION)));
+ InitiateAuthResponse withoutOptIn = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME)));
+ assertThat(withoutOptIn.challengeName()).isEqualTo(ChallengeNameType.SELECT_CHALLENGE);
+ assertThat(withoutOptIn.availableChallengesAsStrings()).containsExactly("PASSWORD", "PASSWORD_SRP");
+
+ cognito.setUserMFAPreference(b -> b.accessToken(accessToken)
+ .webAuthnMfaSettings(w -> w.enabled(true)));
+ InitiateAuthResponse challenge = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", "WEB_AUTHN")));
+ assertThat(challenge.challengeName()).isEqualTo(ChallengeNameType.WEB_AUTHN);
+ String requestOptions = challenge.challengeParameters().get("CREDENTIAL_REQUEST_OPTIONS");
+ assertThat(JSON.readTree(requestOptions).path("userVerification").asText()).isEqualTo("required");
+ String assertion = authenticator.authenticate(requestOptions);
+ RespondToAuthChallengeResponse signedIn = cognito.respondToAuthChallenge(b -> b.clientId(clientId)
+ .challengeName(ChallengeNameType.WEB_AUTHN)
+ .session(challenge.session())
+ .challengeResponses(Map.of("USERNAME", USERNAME, "CREDENTIAL", assertion)));
+ assertThat(signedIn.authenticationResult().accessToken()).isNotBlank();
+
+ cognito.adminSetUserMFAPreference(b -> b.userPoolId(poolId).username(USERNAME)
+ .webAuthnMfaSettings(w -> w.enabled(false)));
+ assertThat(cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME))).availableChallengesAsStrings())
+ .containsExactly("PASSWORD", "PASSWORD_SRP");
+ } finally {
+ cognito.deleteUserPool(b -> b.userPoolId(poolId));
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("StartWebAuthnRegistration is refused when the pool does not allow WEB_AUTHN")
+ void sdkSeesWebAuthnNotEnabled() {
+ try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
+ String poolId = cognito.createUserPool(b -> b.poolName("no-passkey-sdk-" + UUID.randomUUID()))
+ .userPool().id();
+ try {
+ String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
+ .clientName("no-passkey-sdk-client")
+ .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH))
+ .userPoolClient().clientId();
+ cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
+ .messageAction(MessageActionType.SUPPRESS));
+ cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
+ .password(PASSWORD).permanent(true));
+ String accessToken = cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)))
+ .authenticationResult().accessToken();
+
+ assertThatThrownBy(() -> cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken)))
+ .isInstanceOf(WebAuthnNotEnabledException.class);
+ } finally {
+ cognito.deleteUserPool(b -> b.userPoolId(poolId));
+ }
+ }
+ }
+
+ private static JsonNode toJson(Document document) {
+ if (document.isMap()) {
+ ObjectNode node = JSON.createObjectNode();
+ document.asMap().forEach((key, value) -> node.set(key, toJson(value)));
+ return node;
+ }
+ if (document.isList()) {
+ ArrayNode node = JSON.createArrayNode();
+ document.asList().forEach(value -> node.add(toJson(value)));
+ return node;
+ }
+ if (document.isString()) {
+ return JSON.getNodeFactory().textNode(document.asString());
+ }
+ if (document.isNumber()) {
+ return JSON.getNodeFactory().numberNode(document.asNumber().bigDecimalValue());
+ }
+ if (document.isBoolean()) {
+ return JSON.getNodeFactory().booleanNode(document.asBoolean());
+ }
+ return JSON.getNodeFactory().nullNode();
+ }
+
+ private static Document toDocument(JsonNode node) {
+ if (node.isObject()) {
+ Map<String, Document> members = new LinkedHashMap<>();
+ node.fields().forEachRemaining(entry -> members.put(entry.getKey(), toDocument(entry.getValue())));
+ return Document.fromMap(members);
+ }
+ if (node.isArray()) {
+ List<Document> items = new ArrayList<>();
+ node.forEach(item -> items.add(toDocument(item)));
+ return Document.fromList(items);
+ }
+ if (node.isBoolean()) {
+ return Document.fromBoolean(node.asBoolean());
+ }
+ if (node.isNumber()) {
+ return Document.fromNumber(node.decimalValue());
+ }
+ if (node.isNull()) {
+ return Document.fromNull();
+ }
+ return Document.fromString(node.asText());
+ }
+}
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/WebAuthnTestAuthenticator.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/WebAuthnTestAuthenticator.java
new file mode 100644
index 0000000000..1cf63745c3
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/WebAuthnTestAuthenticator.java
@@ -0,0 +1,274 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
+import java.security.Signature;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.ECGenParameterSpec;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.UUID;
+
+/**
+ * A software passkey authenticator for tests, standing in for a browser and its authenticator:
+ * it answers creation options with a {@code RegistrationResponseJSON} ({@code none} or
+ * {@code packed} self attestation) and request options with an {@code AuthenticationResponseJSON}.
+ */
+final class WebAuthnTestAuthenticator {
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final byte FLAG_UP = 0x01;
+ private static final byte FLAG_UV = 0x04;
+ private static final byte FLAG_AT = 0x40;
+
+ private final String origin;
+ private final KeyPair keyPair;
+ private final long algorithm;
+ private final String signatureAlgorithm;
+ private final byte[] credentialId = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
+ private String relyingPartyIdOverride;
+ private boolean userVerified = true;
+ private boolean corruptAttestation;
+ private long signCount;
+
+ private WebAuthnTestAuthenticator(String origin, KeyPair keyPair, long algorithm, String signatureAlgorithm) {
+ this.origin = origin;
+ this.keyPair = keyPair;
+ this.algorithm = algorithm;
+ this.signatureAlgorithm = signatureAlgorithm;
+ }
+
+ static WebAuthnTestAuthenticator es256(String origin) throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp256r1"));
+ return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -7, "SHA256withECDSA");
+ }
+
+ static WebAuthnTestAuthenticator es384(String origin) throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp384r1"));
+ return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -35, "SHA384withECDSA");
+ }
+
+ static WebAuthnTestAuthenticator rs256(String origin) throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -257, "SHA256withRSA");
+ }
+
+ /** Claims {@code relyingPartyId} instead of the one the options name. */
+ WebAuthnTestAuthenticator relyingPartyId(String relyingPartyId) {
+ this.relyingPartyIdOverride = relyingPartyId;
+ return this;
+ }
+
+ WebAuthnTestAuthenticator userVerified(boolean userVerified) {
+ this.userVerified = userVerified;
+ return this;
+ }
+
+ /** Signs a {@code packed} attestation statement over the wrong data. */
+ WebAuthnTestAuthenticator corruptAttestation() {
+ this.corruptAttestation = true;
+ return this;
+ }
+
+ String credentialId() {
+ return base64Url(credentialId);
+ }
+
+ ObjectNode register(JsonNode creationOptions, String format) throws Exception {
+ String relyingPartyId = relyingPartyIdOverride != null
+ ? relyingPartyIdOverride : creationOptions.path("rp").path("id").asText();
+ byte[] clientData = clientData("webauthn.create", creationOptions.path("challenge").asText());
+ ByteArrayOutputStream authData = new ByteArrayOutputStream();
+ authData.write(sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)));
+ authData.write(FLAG_UP | FLAG_AT | (userVerified ? FLAG_UV : 0));
+ authData.write(ByteBuffer.allocate(4).putInt((int) signCount).array());
+ authData.write(new byte[16]);
+ authData.write(ByteBuffer.allocate(2).putShort((short) credentialId.length).array());
+ authData.write(credentialId);
+ authData.write(coseKey());
+ byte[] authenticatorData = authData.toByteArray();
+
+ Cbor statement = new Cbor();
+ if ("packed".equals(format)) {
+ byte[] signed = concat(authenticatorData, sha256(clientData));
+ if (corruptAttestation) {
+ signed[0] ^= 0x01;
+ }
+ statement.map(2).text("alg").integer(algorithm).text("sig").bytes(sign(signed));
+ } else {
+ statement.map(0);
+ }
+ byte[] attestationObject = new Cbor().map(3)
+ .text("fmt").text(format)
+ .text("attStmt").raw(statement.toByteArray())
+ .text("authData").bytes(authenticatorData)
+ .toByteArray();
+
+ ObjectNode credential = JSON.createObjectNode();
+ credential.put("id", credentialId());
+ credential.put("rawId", credentialId());
+ credential.put("type", "public-key");
+ credential.put("authenticatorAttachment", "platform");
+ credential.putObject("clientExtensionResults");
+ ObjectNode response = credential.putObject("response");
+ response.put("clientDataJSON", base64Url(clientData));
+ response.put("attestationObject", base64Url(attestationObject));
+ response.putArray("transports").add("internal").add("hybrid");
+ return credential;
+ }
+
+ String authenticate(String requestOptionsJson) throws Exception {
+ JsonNode options = JSON.readTree(requestOptionsJson);
+ String relyingPartyId = relyingPartyIdOverride != null ? relyingPartyIdOverride : options.path("rpId").asText();
+ byte[] clientData = clientData("webauthn.get", options.path("challenge").asText());
+ signCount++;
+ byte[] authenticatorData = concat(sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)),
+ new byte[] {(byte) (FLAG_UP | (userVerified ? FLAG_UV : 0))},
+ ByteBuffer.allocate(4).putInt((int) signCount).array());
+
+ ObjectNode credential = JSON.createObjectNode();
+ credential.put("id", credentialId());
+ credential.put("rawId", credentialId());
+ credential.put("type", "public-key");
+ credential.put("authenticatorAttachment", "platform");
+ credential.putObject("clientExtensionResults");
+ ObjectNode response = credential.putObject("response");
+ response.put("authenticatorData", base64Url(authenticatorData));
+ response.put("clientDataJSON", base64Url(clientData));
+ response.put("signature", base64Url(sign(concat(authenticatorData, sha256(clientData)))));
+ return JSON.writeValueAsString(credential);
+ }
+
+ private byte[] clientData(String type, String challenge) throws Exception {
+ ObjectNode clientData = JSON.createObjectNode();
+ clientData.put("type", type);
+ clientData.put("challenge", challenge);
+ clientData.put("origin", origin);
+ clientData.put("crossOrigin", false);
+ return JSON.writeValueAsBytes(clientData);
+ }
+
+ private byte[] coseKey() {
+ if (keyPair.getPublic() instanceof RSAPublicKey rsa) {
+ return new Cbor().map(4)
+ .integer(1).integer(3)
+ .integer(3).integer(algorithm)
+ .integer(-1).bytes(unsigned(rsa.getModulus()))
+ .integer(-2).bytes(unsigned(rsa.getPublicExponent()))
+ .toByteArray();
+ }
+ ECPublicKey ec = (ECPublicKey) keyPair.getPublic();
+ int size = algorithm == -35 ? 48 : 32;
+ return new Cbor().map(5)
+ .integer(1).integer(2)
+ .integer(3).integer(algorithm)
+ .integer(-1).integer(algorithm == -35 ? 2 : 1)
+ .integer(-2).bytes(fixed(ec.getW().getAffineX(), size))
+ .integer(-3).bytes(fixed(ec.getW().getAffineY(), size))
+ .toByteArray();
+ }
+
+ private byte[] sign(byte[] data) throws Exception {
+ Signature signature = Signature.getInstance(signatureAlgorithm);
+ signature.initSign(keyPair.getPrivate());
+ signature.update(data);
+ return signature.sign();
+ }
+
+ private static byte[] sha256(byte[] data) throws Exception {
+ return MessageDigest.getInstance("SHA-256").digest(data);
+ }
+
+ private static byte[] concat(byte[]... parts) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ for (byte[] part : parts) {
+ out.writeBytes(part);
+ }
+ return out.toByteArray();
+ }
+
+ private static byte[] unsigned(BigInteger value) {
+ byte[] bytes = value.toByteArray();
+ return bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes;
+ }
+
+ private static byte[] fixed(BigInteger value, int size) {
+ byte[] bytes = unsigned(value);
+ byte[] padded = new byte[size];
+ System.arraycopy(bytes, 0, padded, size - bytes.length, bytes.length);
+ return padded;
+ }
+
+ static String base64Url(byte[] bytes) {
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+
+ /** The few CBOR items an attestation object and a COSE key need. */
+ private static final class Cbor {
+ private final ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+ Cbor map(int entries) {
+ head(5, entries);
+ return this;
+ }
+
+ Cbor text(String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ head(3, bytes.length);
+ out.writeBytes(bytes);
+ return this;
+ }
+
+ Cbor bytes(byte[] value) {
+ head(2, value.length);
+ out.writeBytes(value);
+ return this;
+ }
+
+ Cbor integer(long value) {
+ if (value >= 0) {
+ head(0, value);
+ } else {
+ head(1, -1 - value);
+ }
+ return this;
+ }
+
+ Cbor raw(byte[] encoded) {
+ out.writeBytes(encoded);
+ return this;
+ }
+
+ byte[] toByteArray() {
+ return out.toByteArray();
+ }
+
+ private void head(int majorType, long value) {
+ int major = majorType << 5;
+ if (value < 24) {
+ out.write(major | (int) value);
+ } else if (value < 0x100) {
+ out.write(major | 24);
+ out.write((int) value);
+ } else if (value < 0x10000) {
+ out.write(major | 25);
+ out.writeBytes(ByteBuffer.allocate(2).putShort((short) value).array());
+ } else {
+ out.write(major | 26);
+ out.writeBytes(ByteBuffer.allocate(4).putInt((int) value).array());
+ }
+ }
+ }
+}
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index fa5e82b37b..c0f534ae5c 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -47,9 +47,9 @@ format. Validation runs before pool or client lookup.
| ListUserPools | Lists local user pools visible in the request region. |
| UpdateUserPool | Updates mutable user pool settings and persisted user-pool tags. |
| DeleteUserPool | Deletes a local user pool and everything it owns: users, groups, app clients, resource servers, identity providers, revoked tokens and verification codes. Refused with `InvalidParameterException` while `DeletionProtection` is `ACTIVE` (switch it to `INACTIVE` with `UpdateUserPool` first, as on AWS) or while a domain is still configured. |
-| GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token setting. |
+| GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token and passkey (`WebAuthnConfiguration`) settings. |
| AddCustomAttributes | Adds 1 to 25 attributes to a user pool's schema, prefixing each name with `custom:`, or `dev:` for a `DeveloperOnlyAttribute`, and rejecting a name the schema already has. |
-| SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS. SMS, email and WebAuthn configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have. |
+| SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS, and is stored: see [Passkeys](#passkeys). A request without it keeps the stored one. SMS and email configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have. |
Email that Cognito sends to users, such as verification codes, goes through Floci's SES (readable
at `/_aws/ses`) from the sender the pool's `EmailConfiguration` names:
@@ -231,7 +231,7 @@ further divergences, both deliberate:
| AdminDisableUser | Disables a user, whose sign-in then fails with `NotAuthorizedException` (`User is disabled.`). Tokens already issued keep working, where AWS revokes the user's access tokens. |
| AdminEnableUser | Re-enables a disabled user. |
| AdminResetUserPassword | Clears a user's password and sets the status to `RESET_REQUIRED`, so sign-in fails with `PasswordResetRequiredException`. Floci sends no reset code: finish with `ForgotPassword` and `ConfirmForgotPassword`, or `AdminSetUserPassword`. Refused when the pool's account recovery is `admin_only`. |
-| AdminSetUserMFAPreference | Sets a user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`. SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
+| AdminSetUserMFAPreference | Sets a user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`, and passkey MFA from `WebAuthnMfaSettings` (see [Passkeys](#passkeys)). SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
| AdminUserGlobalSignOut | Revokes the access, ID and refresh tokens issued to a user. |
| AdminLinkProviderForUser | Links an external IdP identity to an existing user's `identities` attribute. |
@@ -243,22 +243,26 @@ further divergences, both deliberate:
| ConfirmSignUp | Confirms a pending self-service signup. |
| ResendConfirmationCode | Issues a new sign-up confirmation code to an unconfirmed user, replacing the previous one, and returns where it was sent. |
| GetUser | Returns attributes for the authenticated access-token user, and the MFA settings (`UserMFASettingList`, `PreferredMfaSetting`) once any is turned on. |
-| GetUserAuthFactors | Returns the authenticated access-token user's sign-in factors: `PASSWORD` when the user has a password, `EMAIL_OTP` and `SMS_OTP` when the email or phone number is verified, whatever the pool's `AllowedFirstAuthFactors` allows, as on AWS, and `SOFTWARE_TOKEN` once `VerifySoftwareToken` has confirmed an authenticator. The access token must carry the `aws.cognito.signin.user.admin` scope. `UserMFASettingList` and `PreferredMfaSetting` report the email and software-token MFA preferences set with `SetUserMFAPreference`. `WEB_AUTHN` and SMS MFA settings are not reported. |
+| GetUserAuthFactors | Returns the authenticated access-token user's sign-in factors: `PASSWORD` when the user has a password, `EMAIL_OTP` and `SMS_OTP` when the email or phone number is verified, whatever the pool's `AllowedFirstAuthFactors` allows, as on AWS, `WEB_AUTHN` once the user has registered a passkey, and `SOFTWARE_TOKEN` once `VerifySoftwareToken` has confirmed an authenticator. The access token must carry the `aws.cognito.signin.user.admin` scope. `UserMFASettingList` and `PreferredMfaSetting` report the email and software-token MFA preferences set with `SetUserMFAPreference`. SMS MFA settings are not reported. |
| GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. |
| VerifyUserAttribute | Verifies an email or phone_number attribute with its issued verification code. |
| UpdateUserAttributes | Updates attributes for the authenticated access-token user. |
| DeleteUserAttributes | Deletes the named attributes from the authenticated access-token user. |
| DeleteUser | Deletes the authenticated access-token user and removes them from their groups. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. |
| ChangePassword | Changes the authenticated user's password. |
-| SetUserMFAPreference | Sets the authenticated access-token user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`. SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
+| SetUserMFAPreference | Sets the authenticated access-token user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`, and passkey MFA from `WebAuthnMfaSettings` (see [Passkeys](#passkeys)). SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
| GlobalSignOut | Revokes the access, ID and refresh tokens issued to the authenticated access-token user. |
+| StartWebAuthnRegistration | Returns the `CredentialCreationOptions` to register a passkey for the authenticated access-token user. See [Passkeys](#passkeys). |
+| CompleteWebAuthnRegistration | Verifies the `RegistrationResponseJSON` in `Credential` and registers the passkey. |
+| ListWebAuthnCredentials | Lists the authenticated access-token user's passkeys, oldest first, up to 20 per page. `NextToken` is a cursor on the last passkey listed, so deleting a passkey between two pages skips none. |
+| DeleteWebAuthnCredential | Deletes one of the authenticated access-token user's passkeys. |
| ForgotPassword | Starts the local forgot-password flow for a user. |
| ConfirmForgotPassword | Completes the forgot-password flow by setting a replacement password. |
As on AWS, every operation authorized by the user's access token (`GetUser`,
`GetUserAuthFactors`, `UpdateUserAttributes`, `DeleteUserAttributes`, `DeleteUser`,
`ChangePassword`, `GetUserAttributeVerificationCode`, `VerifyUserAttribute`,
-`SetUserMFAPreference`, `GlobalSignOut`, and `AssociateSoftwareToken` and
+`SetUserMFAPreference`, `GlobalSignOut`, the four passkey actions, and `AssociateSoftwareToken` and
`VerifySoftwareToken` with an `AccessToken`)
requires the token's `scope` to include `aws.cognito.signin.user.admin`. Tokens from
`InitiateAuth` and the other API sign-in flows always carry it; a token from the OAuth token
@@ -316,10 +320,55 @@ software-token MFA, which is what AWS documents.
- In `USER_AUTH`, a user with software-token MFA turned on in an optional-MFA pool is offered only
`PASSWORD` and `PASSWORD_SRP`, as AWS documents for users with MFA, so the second factor still
follows. Email MFA does not restrict the choice, because Floci does not send an email MFA code
- after a password.
+ after a password. A user who also turned passkey MFA on keeps `WEB_AUTHN` (see [Passkeys](#passkeys)).
SMS and email MFA challenges, and managed-login MFA, are not emulated.
+### Passkeys
+
+Passkey (WebAuthn) registration and sign-in follow the
+[Cognito passkey flow](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html#amazon-cognito-user-pools-authentication-flow-methods-passkey).
+Passkeys are on for a pool whose `Policies.SignInPolicy.AllowedFirstAuthFactors` includes
+`WEB_AUTHN`, on any tier but Lite; otherwise the passkey actions fail with
+`WebAuthnNotEnabledException`. `SetUserPoolMfaConfig` sets `WebAuthnConfiguration`:
+
+- `RelyingPartyId`: the relying party ID passkeys are registered for. Without one, Floci uses the
+ pool's custom domain, then its prefix domain (`<prefix>.auth.<region>.amazoncognito.com` in the
+ commercial partition), as AWS does, and fails with `WebAuthnConfigurationMissingException` when the pool has neither. For a
+ local page, set it to `localhost`.
+- `UserVerification`: `preferred` (the default) or `required`.
+- `FactorConfiguration`: `MULTI_FACTOR_WITH_USER_VERIFICATION` makes passkey MFA possible, and each
+ user turns it on with `WebAuthnMfaSettings` in `SetUserMFAPreference` or
+ `AdminSetUserMFAPreference`. For a user who did, a passkey sign-in asks for user verification and,
+ verified, satisfies MFA. Turning it on in a pool with `SINGLE_FACTOR` or none, or in a Lite pool,
+ fails with `InvalidParameterException`. A pool that requires MFA offers `WEB_AUTHN` only to users
+ with passkey MFA on, and an optional-MFA pool keeps offering it to a user with software-token MFA
+ only when passkey MFA is on too, as the AWS MFA table describes; elsewhere, a passkey sign-in by a
+ user without it goes through the pool's MFA rules, as after a password.
+
+Registration: `StartWebAuthnRegistration` returns `CredentialCreationOptions` (ES256 and RS256
+keys, a discoverable credential, the user's `sub` as the user handle, the user's existing passkeys
+excluded), and `CompleteWebAuthnRegistration` verifies the browser's `RegistrationResponseJSON`:
+the challenge, the origin, the relying party ID, user presence, user verification when required,
+and an ES256 or RS256 public key. As in Cognito, attestation is not enforced, so the attestation
+statement is not verified, whatever its format. The origin must be the relying party ID or one of
+its subdomains, over HTTPS, or over HTTP for `localhost`, the one insecure origin browsers allow.
+Errors follow the API reference:
+`WebAuthnChallengeNotFoundException` (no pending registration, or one older than five minutes),
+`WebAuthnClientMismatchException` (an access token from another app client),
+`WebAuthnOriginNotAllowedException`, `WebAuthnRelyingPartyMismatchException`, and
+`WebAuthnCredentialNotSupportedException` (another algorithm, or no user verification when it is
+required). A user can register 20 passkeys. `FriendlyCredentialName` is `Roaming passkey` for a
+cross-platform authenticator and `Passkey` otherwise: Floci has no catalog of authenticator models
+to name a passkey after.
+
+Sign-in: `USER_AUTH` offers `WEB_AUTHN` to a user with a registered passkey. The `WEB_AUTHN`
+challenge carries `CREDENTIAL_REQUEST_OPTIONS`, the `PublicKeyCredentialRequestOptionsJSON` for
+`navigator.credentials.get()`, and is answered with `RespondToAuthChallenge` (`CREDENTIAL`: the
+`AuthenticationResponseJSON`). Floci checks the signature, the challenge, the origin, the relying
+party ID, user presence, user verification when required, and the signature counter. A failed
+check is `NotAuthorizedException`.
+
### User Listing
| Action | Description |
@@ -335,7 +384,7 @@ SMS and email MFA challenges, and managed-login MFA, are not emulated.
`USER_AUTH` is the choice-based flow: with no `PREFERRED_CHALLENGE` it returns
`ChallengeName=SELECT_CHALLENGE` and an `AvailableChallenges` list drawn from what the user has
-configured (`PASSWORD`, `PASSWORD_SRP`, `EMAIL_OTP`, `SMS_OTP`); with one, it goes straight to that
+configured (`PASSWORD`, `PASSWORD_SRP`, `EMAIL_OTP`, `SMS_OTP`, `WEB_AUTHN`); with one, it goes straight to that
challenge. The list keeps only the first factors the pool's
`Policies.SignInPolicy.AllowedFirstAuthFactors` allows: its `PASSWORD` covers both `PASSWORD` and
`PASSWORD_SRP`, so a pool that allows only `EMAIL_OTP` offers `["EMAIL_OTP"]`, and a user with no
@@ -346,8 +395,8 @@ and puts the default back when its `Policies` has no `SignInPolicy`. A `PREFERRE
the list, because the policy leaves it out or the user has not set it up, gets `SELECT_CHALLENGE` and
the list, as on AWS; one that names no challenge Cognito supports fails with
`InvalidParameterException`. A `SELECT_CHALLENGE` answer outside the list fails with
-`InvalidParameterException`. It requires the user pool's tier to be Essentials or higher. `WEB_AUTHN` and the `ConfirmSignUp` session as a first-factor
-shortcut are not implemented yet.
+`InvalidParameterException`. It requires the user pool's tier to be Essentials or higher. The `ConfirmSignUp` session as a first-factor
+shortcut is not implemented yet.
Any other `AuthFlow` value is rejected with `InvalidParameterException` and no tokens are issued.
diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java
index 1296293e99..fe062668dc 100644
--- a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java
+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.config;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
@@ -26,7 +27,6 @@ import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.KeyPair;
-import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
@@ -152,7 +152,7 @@ public final class FlociCertificateAuthority {
public String fingerprint() {
try {
return HexFormat.ofDelimiter(":").withUpperCase()
- .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded()));
+ .formatHex(Digests.sha256(certificate.getEncoded()));
} catch (Exception e) {
throw new IllegalStateException("Cannot fingerprint the CA certificate", e);
}
diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.java b/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.java
index 8b4633323b..43aebec9d5 100644
--- a/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.java
+++ b/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
@@ -252,7 +253,7 @@ public class TlsCertificateManager implements Resettable {
config.dns().extraSuffixes().ifPresent(list -> list.forEach(s -> suffixes.add(s.toLowerCase(Locale.ROOT))));
String bare = name.startsWith("*.") ? name.substring(2) : name;
for (String suffix : suffixes) {
- if (bare.equals(suffix) || bare.endsWith("." + suffix)) {
+ if (DomainNames.isWithin(bare, suffix)) {
return true;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Base64Url.java b/src/main/java/io/github/hectorvent/floci/core/common/Base64Url.java
new file mode 100644
index 0000000000..baee01423b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/Base64Url.java
@@ -0,0 +1,20 @@
+package io.github.hectorvent.floci.core.common;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+/** Base64url without padding, the encoding of JWT segments and WebAuthn fields. */
+public final class Base64Url {
+
+ private Base64Url() {
+ }
+
+ public static String encode(byte[] data) {
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(data);
+ }
+
+ /** Encodes the UTF-8 bytes of {@code text}. */
+ public static String encode(String text) {
+ return encode(text.getBytes(StandardCharsets.UTF_8));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Digests.java b/src/main/java/io/github/hectorvent/floci/core/common/Digests.java
new file mode 100644
index 0000000000..905774f1f6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/Digests.java
@@ -0,0 +1,31 @@
+package io.github.hectorvent.floci.core.common;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+
+/** Message digests every Java runtime is required to provide, without the checked exception. */
+public final class Digests {
+
+ private Digests() {
+ }
+
+ public static byte[] sha256(byte[] data) {
+ try {
+ return MessageDigest.getInstance("SHA-256").digest(data);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 is not available", e);
+ }
+ }
+
+ /** The SHA-256 digest of {@code data} as lowercase hex. */
+ public static String sha256Hex(byte[] data) {
+ return HexFormat.of().formatHex(sha256(data));
+ }
+
+ /** The SHA-256 digest of the UTF-8 bytes of {@code text} as lowercase hex. */
+ public static String sha256Hex(String text) {
+ return sha256Hex(text.getBytes(StandardCharsets.UTF_8));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/DomainNames.java b/src/main/java/io/github/hectorvent/floci/core/common/DomainNames.java
new file mode 100644
index 0000000000..2bc4884111
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/DomainNames.java
@@ -0,0 +1,16 @@
+package io.github.hectorvent.floci.core.common;
+
+/** Relations between domain names. */
+public final class DomainNames {
+
+ private DomainNames() {
+ }
+
+ /**
+ * Whether {@code name} is {@code domain} itself or one of its subdomains. The names are compared
+ * as given, so a caller that wants a case-insensitive match passes both in one case.
+ */
+ public static boolean isWithin(String name, String domain) {
+ return name.equals(domain) || name.endsWith("." + domain);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java
index 9545c07a92..e80955f02d 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java
@@ -100,7 +100,7 @@ public final class Pagination {
}
private static String encodeToken(String cursor) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(cursor);
}
private static String decodeCursor(String token, String prefix,
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PublicKeys.java b/src/main/java/io/github/hectorvent/floci/core/common/PublicKeys.java
new file mode 100644
index 0000000000..42ff7b7dea
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/PublicKeys.java
@@ -0,0 +1,41 @@
+package io.github.hectorvent.floci.core.common;
+
+import java.math.BigInteger;
+import java.security.AlgorithmParameters;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.ECParameterSpec;
+import java.security.spec.ECPoint;
+import java.security.spec.ECPublicKeySpec;
+import java.security.spec.RSAPublicKeySpec;
+
+/**
+ * Public keys built from their raw components, the form JWKs, COSE keys and SSH blobs carry them in,
+ * and the parameters of a named EC curve.
+ */
+public final class PublicKeys {
+
+ private PublicKeys() {
+ }
+
+ /** The RSA public key with this modulus and public exponent. */
+ public static RSAPublicKey rsa(BigInteger modulus, BigInteger exponent) throws GeneralSecurityException {
+ return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
+ }
+
+ /** The EC public key at the point ({@code x}, {@code y}) of the named curve, such as {@code secp256r1}. */
+ public static ECPublicKey ec(String curve, BigInteger x, BigInteger y) throws GeneralSecurityException {
+ return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(
+ new ECPublicKeySpec(new ECPoint(x, y), namedCurve(curve)));
+ }
+
+ /** The domain parameters of a named EC curve, such as {@code secp256r1}. */
+ public static ECParameterSpec namedCurve(String name) throws GeneralSecurityException {
+ AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
+ parameters.init(new ECGenParameterSpec(name));
+ return parameters.getParameterSpec(ECParameterSpec.class);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java b/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java
index 5f9d2be158..e33e6f6d33 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java
@@ -8,8 +8,6 @@ import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HexFormat;
@@ -122,9 +120,8 @@ public final class SshPublicKeys {
BigInteger exponent = new BigInteger(reader.readField());
BigInteger modulus = new BigInteger(reader.readField());
try {
- return (RSAPublicKey) KeyFactory.getInstance("RSA")
- .generatePublic(new RSAPublicKeySpec(modulus, exponent));
- } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
+ return PublicKeys.rsa(modulus, exponent);
+ } catch (GeneralSecurityException e) {
throw new SshPublicKeyException("not a usable RSA public key: " + e.getMessage(), e);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java
index a32f0f5dfd..fd9ac218d4 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.core.common.auth;
+import io.github.hectorvent.floci.core.common.Digests;
+
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -42,7 +44,7 @@ public final class SigV4Canonicalization {
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ scope.credentialScope() + "\n"
- + SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String expected = SigV4RequestValidator.hexEncode(
SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
if (MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
@@ -147,7 +149,7 @@ public final class SigV4Canonicalization {
if (presigned) {
return "UNSIGNED-PAYLOAD";
}
- return SigV4RequestValidator.sha256Hex(body == null ? new byte[0] : body);
+ return Digests.sha256Hex(body == null ? new byte[0] : body);
}
/** RFC 3986 percent-encoding as SigV4 defines it: {@code /} is escaped, {@code -._~} are not. */
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 35b50b779e..b533cccf53 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
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.core.common.auth;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.iam.IamService;
import org.jboss.logging.Logger;
@@ -133,7 +134,7 @@ public final class SigV4RequestValidator {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ dateTime + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(secretKey, date, region, service);
String expectedSignature = hexEncode(hmacSha256(signingKey, stringToSign));
@@ -294,16 +295,6 @@ public final class SigV4RequestValidator {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
- public static String sha256Hex(String input) throws Exception {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
- }
-
- public static String sha256Hex(byte[] input) throws Exception {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- return hexEncode(digest.digest(input));
- }
-
public static String hexEncode(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsForwardingRule.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsForwardingRule.java
index 91cf98514d..553ac66141 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsForwardingRule.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsForwardingRule.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.core.common.dns;
+import io.github.hectorvent.floci.core.common.DomainNames;
+
import java.util.List;
import java.util.Locale;
@@ -54,7 +56,7 @@ public record DnsForwardingRule(String domainName, List<Target> targets) {
return true;
}
String query = normalize(queryName);
- return query.equals(domainName) || query.endsWith("." + domainName);
+ return DomainNames.isWithin(query, domainName);
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
index 508823dba7..289a395812 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common.dns;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsConfigSource;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.quarkus.runtime.Startup;
@@ -242,7 +243,7 @@ public class EmbeddedDnsServer {
String lower = name.toLowerCase();
for (String suffix : suffixes) {
String s = suffix.toLowerCase();
- if (lower.equals(s) || lower.endsWith("." + s)) {
+ if (DomainNames.isWithin(lower, s)) {
return true;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
index 640ba4b044..2563fbaafe 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
@@ -10,6 +10,7 @@ import com.github.dockerjava.core.SSLConfig;
import com.github.dockerjava.core.util.CertificateUtils;
import com.github.dockerjava.transport.DockerHttpClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Digests;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
@@ -21,12 +22,9 @@ import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.Serializable;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Optional;
@@ -284,7 +282,7 @@ public class DockerClientProducer {
private static String readContextDockerHost(Path dockerConfigDir, String contextName) {
Path metaFile = dockerConfigDir.resolve("contexts").resolve("meta")
- .resolve(sha256Hex(contextName)).resolve("meta.json");
+ .resolve(Digests.sha256Hex(contextName)).resolve("meta.json");
if (!Files.isRegularFile(metaFile)) {
return null;
}
@@ -309,7 +307,7 @@ public class DockerClientProducer {
*/
private static boolean readContextSkipTlsVerify(Path dockerConfigDir, String contextName) {
Path metaFile = dockerConfigDir.resolve("contexts").resolve("meta")
- .resolve(sha256Hex(contextName)).resolve("meta.json");
+ .resolve(Digests.sha256Hex(contextName)).resolve("meta.json");
if (!Files.isRegularFile(metaFile)) {
return false;
}
@@ -342,7 +340,7 @@ public class DockerClientProducer {
*/
private static Optional<Path> resolveActiveDockerContextTlsMaterial(Path dockerConfigDir, String contextName) {
Path tlsDir = dockerConfigDir.resolve("contexts").resolve("tls")
- .resolve(sha256Hex(contextName)).resolve(CONTEXT_TLS_ENDPOINT_DIR);
+ .resolve(Digests.sha256Hex(contextName)).resolve(CONTEXT_TLS_ENDPOINT_DIR);
if (!Files.isDirectory(tlsDir)) {
return Optional.empty();
}
@@ -363,20 +361,6 @@ public class DockerClientProducer {
return Optional.empty();
}
- private static String sha256Hex(String value) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- byte[] hash = digest.digest(value.getBytes(StandardCharsets.UTF_8));
- StringBuilder hex = new StringBuilder(hash.length * 2);
- for (byte b : hash) {
- hex.append(String.format("%02x", b));
- }
- return hex.toString();
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 algorithm not available", e);
- }
- }
-
private static DefaultDockerClientConfig.Builder createDockerConfigBuilder() {
try {
return DefaultDockerClientConfig.createDefaultConfigBuilder();
diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java
index 972cb1433b..0aa71496ca 100644
--- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java
@@ -5,6 +5,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
@@ -28,8 +30,6 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.ArrayList;
@@ -39,7 +39,6 @@ import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
@@ -796,7 +795,7 @@ public class AcmService implements ResourceProvider {
static boolean isValidationDomainOf(String domain, String validationDomain) {
String lowerDomain = domain.toLowerCase(Locale.ROOT);
String lowerValidationDomain = validationDomain.toLowerCase(Locale.ROOT);
- return lowerDomain.equals(lowerValidationDomain) || lowerDomain.endsWith("." + lowerValidationDomain);
+ return DomainNames.isWithin(lowerDomain, lowerValidationDomain);
}
/**
@@ -848,13 +847,7 @@ public class AcmService implements ResourceProvider {
private String generateValidationToken(String domain) {
String tokenInput = regionResolver.getAccountId() + ":" + baseDomain(domain);
- try {
- return HexFormat.of().formatHex(
- MessageDigest.getInstance("SHA-256").digest(tokenInput.getBytes(StandardCharsets.UTF_8))
- );
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is unavailable", e);
- }
+ return Digests.sha256Hex(tokenInput);
}
private static String baseDomain(String domain) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java
index a959e5a834..9c88e8944a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.PublicKeys;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -27,10 +28,8 @@ import java.net.URI;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
-import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
-import java.security.spec.RSAPublicKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
@@ -316,10 +315,8 @@ public class JwtSignatureVerifier implements AutoCloseable {
}
private RSAPublicKey toRsaPublicKey(String n, String e) throws GeneralSecurityException {
- BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(n)));
- BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(e)));
- RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
- return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
+ return PublicKeys.rsa(new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(n))),
+ new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(e))));
}
private boolean signatureValid(String signingInput, String encodedSignature, RSAPublicKey publicKey) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java
index 0c51e80a19..e8d5ac039f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteApiHostFilter;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
@@ -25,6 +26,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
/**
* Vert.x-based WebSocket handler for API Gateway v2 WebSocket APIs.
@@ -707,8 +709,8 @@ public class WebSocketHandler {
*/
private static String generateConnectionId() {
byte[] bytes = new byte[9];
- java.util.concurrent.ThreadLocalRandom.current().nextBytes(bytes);
- return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ ThreadLocalRandom.current().nextBytes(bytes);
+ return Base64Url.encode(bytes);
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java
index 7ef32c59ee..2cbbb38e5d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.CloudFrontEdgeDomain;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
@@ -1370,8 +1371,7 @@ public class AppSyncService {
}
static String encodeToken(int offset) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(Integer.toString(offset).getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ return Base64Url.encode(Integer.toString(offset));
}
static int decodeToken(String token) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java
index 8ebe45bc84..4e5c4974d8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/IamAuthValidator.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
import io.github.hectorvent.floci.core.common.auth.SigV4AuthorizationHeader;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
@@ -128,12 +129,12 @@ public class IamAuthValidator {
checkSessionToken(accessKeyId, info.requestHeaders());
try {
String canonicalUri = "/v1/apis/" + apiId + "/graphql";
- String payloadHash = SigV4RequestValidator.sha256Hex(info.rawBody().getBytes(StandardCharsets.UTF_8));
+ String payloadHash = Digests.sha256Hex(info.rawBody().getBytes(StandardCharsets.UTF_8));
String canonicalHeaders = canonicalHeaders(signed.signedHeaders(), info.requestHeaders());
String canonicalRequest = "POST\n" + canonicalUri + "\n\n"
+ canonicalHeaders + "\n" + signed.signedHeaders() + "\n" + payloadHash;
String stringToSign = ALGORITHM + "\n" + signed.amzDate() + "\n" + scope.credentialScope() + "\n"
- + SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(
secretKey, scope.date(), scope.region(), scope.service());
String expected = SigV4RequestValidator.hexEncode(
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java
index 832e8a0ecb..b22789fff3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/auth/JwtClaimsDecoder.java
@@ -2,10 +2,10 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
-import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
@@ -70,10 +70,8 @@ public class JwtClaimsDecoder {
static String encode(Map<String, Object> claims, ObjectMapper objectMapper) {
try {
- String header = Base64.getUrlEncoder().withoutPadding()
- .encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
- String payload = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(objectMapper.writeValueAsBytes(claims));
+ String header = Base64Url.encode("{\"alg\":\"none\",\"typ\":\"JWT\"}");
+ String payload = Base64Url.encode(objectMapper.writeValueAsBytes(claims));
return header + "." + payload + ".sig";
} catch (Exception e) {
throw new IllegalArgumentException(e);
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java
index 870ea39ed3..6c7f0940a4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/DynamoDbDataSourceInvoker.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.appsync.model.DataSource;
import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
@@ -343,8 +344,7 @@ public class DynamoDbDataSourceInvoker implements AppSyncDataSourceInvoker {
if (lastEvaluatedKey == null || lastEvaluatedKey.isNull() || lastEvaluatedKey.isEmpty()) {
return null;
}
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(lastEvaluatedKey.toString().getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(lastEvaluatedKey.toString());
}
private JsonNode decodeNextToken(String nextToken) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
index 16a756f1d7..643267aa80 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
@@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.Container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
@@ -28,8 +29,6 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
@@ -244,17 +243,7 @@ public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown
/** Digest of the server script this build would start the sidecar with. */
private String scriptDigest() {
- try {
- byte[] hash = MessageDigest.getInstance("SHA-256")
- .digest(serverScript().getBytes(StandardCharsets.UTF_8));
- StringBuilder hex = new StringBuilder(16);
- for (int i = 0; i < 8; i++) {
- hex.append(String.format("%02x", hash[i]));
- }
- return hex.toString();
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is unavailable", e);
- }
+ return Digests.sha256Hex(serverScript()).substring(0, 16);
}
private String serverScript() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java
index f6693033de..ca46f80aa1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/ResolverCallbackSessions.java
@@ -1,9 +1,9 @@
package io.github.hectorvent.floci.services.appsync.graphql.resolver;
+import io.github.hectorvent.floci.core.common.Base64Url;
import jakarta.enterprise.context.ApplicationScoped;
import java.security.SecureRandom;
-import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -84,7 +84,7 @@ public class ResolverCallbackSessions {
public Session open(String apiId, Object identity, String authType) {
byte[] bytes = new byte[TOKEN_BYTES];
random.nextBytes(bytes);
- String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ String token = Base64Url.encode(bytes);
Session session = new Session(sessions, token, apiId, identity, authType);
sessions.put(token, session);
return session;
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java
index 4831581da1..a64641dd62 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.InlineZipPackager;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -22,8 +23,6 @@ import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
@@ -638,12 +637,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
private static String sha256Base64(String zipFileBase64) {
byte[] zipBytes = Base64.getDecoder().decode(zipFileBase64);
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(zipBytes);
- return Base64.getEncoder().encodeToString(digest);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException(e);
- }
+ return Base64.getEncoder().encodeToString(Digests.sha256(zipBytes));
}
private static Map<String, String> environmentVariables(Object value) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java
index aebc5f80d8..c0b3e355ad 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java
@@ -2,18 +2,17 @@ package io.github.hectorvent.floci.services.cloudfront;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.PublicKeys;
import java.net.InetAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
-import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
-import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
@@ -250,10 +249,7 @@ public final class CloudFrontSignatureVerifier {
return rsa.getModulus().bitLength() == 2048;
}
if (publicKey instanceof ECPublicKey ec) {
- AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
- parameters.init(new ECGenParameterSpec("secp256r1"));
- ECParameterSpec p256 =
- parameters.getParameterSpec(ECParameterSpec.class);
+ ECParameterSpec p256 = PublicKeys.namedCurve("secp256r1");
ECParameterSpec actual = ec.getParams();
return actual.getCurve().equals(p256.getCurve())
&& actual.getGenerator().equals(p256.getGenerator())
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
index c847df0619..6c1d33f5d9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -598,7 +599,7 @@ public class CloudWatchLogsService implements ResourceProvider {
private static String encodeStreamPageToken(String snapshotId, int position) {
String raw = "v2:" + snapshotId + ":" + position;
- return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(raw);
}
private static AwsException invalidNextToken() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java
index 07f2d0761c..8b9342a3cc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -36,7 +38,6 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
-import java.util.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -572,7 +573,7 @@ public class CodeArtifactService implements Resettable {
"The maximum asset file size is 5 Gigabytes.", 402,
resourceFields(assetName, "asset"));
}
- String actualSha256 = sha256Hex(assetContent);
+ String actualSha256 = Digests.sha256Hex(assetContent);
if (!assetSha256.equalsIgnoreCase(actualSha256)) {
throw validation("assetSHA256 does not match the SHA-256 hash of the uploaded content.");
}
@@ -1004,7 +1005,7 @@ public class CodeArtifactService implements Resettable {
}
String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
String revisionKey = repoId + "/" + (namespace == null ? "" : namespace) + "/" + packageName + "/" + version;
- String revision = sha256Hex(revisionKey.getBytes(StandardCharsets.UTF_8));
+ String revision = Digests.sha256Hex(revisionKey.getBytes(StandardCharsets.UTF_8));
if (packageVersionRevision != null && !packageVersionRevision.equals(revision)) {
throw notFound("Package version '" + version + "' was not found at revision '"
+ packageVersionRevision + "'.", version, "package-version");
@@ -1076,7 +1077,7 @@ public class CodeArtifactService implements Resettable {
private static String generateAuthorizationToken() {
byte[] bytes = new byte[TOKEN_RANDOM_BYTES];
new SecureRandom().nextBytes(bytes);
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
// -------------------------------------------------------------------- tags
@@ -1349,7 +1350,7 @@ public class CodeArtifactService implements Resettable {
String expectedSha256) {
if (inMemory) {
byte[] existing = memoryAssetStore.get(assetStoreKey(owner, packageVersionKey, assetName));
- return existing != null && expectedSha256.equalsIgnoreCase(sha256Hex(existing));
+ return existing != null && expectedSha256.equalsIgnoreCase(Digests.sha256Hex(existing));
}
Path filePath = resolveAssetPath(owner, packageVersionKey, assetName);
try (InputStream in = Files.newInputStream(filePath)) {
@@ -1428,8 +1429,8 @@ public class CodeArtifactService implements Resettable {
*/
private Path resolveAssetPath(String owner, String packageVersionKey, String assetName) {
return assetRoot.resolve(owner)
- .resolve(sha256Hex(packageVersionKey.getBytes(StandardCharsets.UTF_8)))
- .resolve(sha256Hex(assetName.getBytes(StandardCharsets.UTF_8)));
+ .resolve(Digests.sha256Hex(packageVersionKey.getBytes(StandardCharsets.UTF_8)))
+ .resolve(Digests.sha256Hex(assetName.getBytes(StandardCharsets.UTF_8)));
}
private void deleteAssetRoot() {
@@ -1492,14 +1493,6 @@ public class CodeArtifactService implements Resettable {
return hashes;
}
- private static String sha256Hex(byte[] content) {
- try {
- return SigV4RequestValidator.sha256Hex(content);
- } catch (Exception e) {
- throw new IllegalStateException("JVM does not support SHA-256", e);
- }
- }
-
private static byte[] digest(String algorithm, byte[] content) {
try {
return MessageDigest.getInstance(algorithm).digest(content);
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
index 0d0f1a8ccc..530df037d1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
@@ -99,7 +99,7 @@ final class CognitoAuthFlowHandler {
* caller trigger an OTP send without ever starting a flow.
*/
private record UserAuthSession(String userPoolId, String username, String clientId, String challengeName,
- Instant expiresAt, boolean userExists) {}
+ Instant expiresAt, boolean userExists, byte[] webAuthnChallenge) {}
static final class CustomAuthSession {
final String userPoolId;
@@ -464,6 +464,9 @@ final class CognitoAuthFlowHandler {
rejectSimulatedUser(consumeUserAuthSession(pool, client, session, challengeName));
return handleOtpChallengeResponse(pool, client, challengeName, responses, clientMetadata);
}
+ if ("WEB_AUTHN".equals(challengeName)) {
+ return handleWebAuthnChallengeResponse(pool, client, session, responses, clientMetadata);
+ }
if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) {
String username = responses.get("USERNAME");
String newPassword = responses.get("NEW_PASSWORD");
@@ -873,8 +876,8 @@ final class CognitoAuthFlowHandler {
* {@code PASSWORD_SRP} reuse {@link #authenticateWithPassword} and {@link #handleUserSrpAuth}
* unchanged rather than reverifying the same credential a second way.
*
- * <p>Not implemented: {@code WEB_AUTHN} and the {@code ConfirmSignUp} session as a
- * first-factor shortcut (tracked as follow-ups on the issue this was added for).
+ * <p>Not implemented: the {@code ConfirmSignUp} session as a first-factor shortcut (tracked as a
+ * follow-up on the issue this was added for).
*/
private Map<String, Object> handleUserAuth(UserPool pool, UserPoolClient client,
Map<String, String> params, Map<String, String> clientMetadata) {
@@ -969,6 +972,7 @@ final class CognitoAuthFlowHandler {
advertised, clientMetadata);
case "SMS_OTP" -> issueOtpChallenge(pool, client, user, "SMS_OTP", "phone_number", "SMS",
advertised, clientMetadata);
+ case "WEB_AUTHN" -> issueWebAuthnChallenge(pool, client, user, advertised, clientMetadata);
default -> throw new AwsException("InvalidParameterException",
challenge + " is not a supported challenge", 400);
};
@@ -987,6 +991,80 @@ final class CognitoAuthFlowHandler {
return userAuthChallengeResponse(pool, client, user, challengeName, available, challengeParams);
}
+ /**
+ * Issues a {@code WEB_AUTHN} challenge: {@code CREDENTIAL_REQUEST_OPTIONS} is the
+ * {@code PublicKeyCredentialRequestOptionsJSON} to pass to the browser or platform, allowing the
+ * user's registered passkeys, and its challenge stays with the session.
+ */
+ private Map<String, Object> issueWebAuthnChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
+ List<String> available, Map<String, String> clientMetadata) {
+ firePreAuthentication(pool, client, user, null, clientMetadata, false);
+ byte[] challenge = service.newWebAuthnChallenge();
+ String options;
+ try {
+ options = service.webAuthnRequestOptions(pool, user, challenge,
+ Duration.ofMinutes(client.getAuthSessionValidity()).toMillis());
+ } catch (AwsException e) {
+ if (!"WebAuthnConfigurationMissingException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ throw new AwsException("InvalidUserPoolConfigurationException", e.getMessage(), 400);
+ }
+ Map<String, String> challengeParams = new HashMap<>();
+ challengeParams.put("CREDENTIAL_REQUEST_OPTIONS", options);
+ challengeParams.put("USERNAME", user.getUsername());
+ return userAuthChallengeResponse(pool, client, user.getUsername(), "WEB_AUTHN", available, challengeParams,
+ true, challenge);
+ }
+
+ /**
+ * Answers a {@code WEB_AUTHN} challenge: {@code CREDENTIAL} is the {@code AuthenticationResponseJSON}
+ * signed over the session's challenge by one of the user's passkeys. A passkey that verified the user
+ * satisfies MFA for a user who turned passkey MFA on, in a pool whose
+ * {@code WebAuthnConfiguration.FactorConfiguration} is {@code MULTI_FACTOR_WITH_USER_VERIFICATION};
+ * otherwise the pool's MFA rules apply as after a password.
+ */
+ private Map<String, Object> handleWebAuthnChallengeResponse(UserPool pool, UserPoolClient client, String session,
+ Map<String, String> responses,
+ Map<String, String> clientMetadata) {
+ UserAuthSession state = consumeUserAuthSession(pool, client, session, "WEB_AUTHN");
+ rejectSimulatedUser(state);
+ String username = responses.get("USERNAME");
+ String credential = responses.get("CREDENTIAL");
+ if (username == null || credential == null) {
+ throw new AwsException("InvalidParameterException", "USERNAME and CREDENTIAL are required", 400);
+ }
+ validateSecretHash(client, responses, username);
+ CognitoUser user = service.adminGetUser(pool.getId(), username);
+ if (!user.getUsername().equals(state.username())) {
+ throw new AwsException("NotAuthorizedException", "Session does not match user", 400);
+ }
+ requireSignInEligible(user);
+ // For a user whose passkey stands in for MFA, the assertion must verify the user.
+ boolean userVerified = service.verifyWebAuthnSignIn(pool, user.getUsername(), state.webAuthnChallenge(),
+ credential);
+ user = service.adminGetUser(pool.getId(), user.getUsername());
+ if (userVerified && passkeySatisfiesMfa(pool, user)) {
+ return authenticationResult(pool, client, user, "TokenGeneration_Authentication", clientMetadata);
+ }
+ return completePrimaryAuth(pool, client, user, "TokenGeneration_Authentication", clientMetadata);
+ }
+
+ /** Whether the pool lets a passkey that verified the user stand in for MFA. */
+ static boolean passkeyMfaAllowed(UserPool pool) {
+ return pool.getWebAuthnConfiguration() != null
+ && "MULTI_FACTOR_WITH_USER_VERIFICATION".equals(pool.getWebAuthnConfiguration().getFactorConfiguration());
+ }
+
+ /**
+ * Whether a user-verified passkey sign-in satisfies MFA for {@code user}. AWS needs both the pool's
+ * {@code FactorConfiguration} and the user's own {@code WebAuthnMfaSettings}: the pool only makes
+ * passkey MFA possible, and each user opts in.
+ */
+ static boolean passkeySatisfiesMfa(UserPool pool, CognitoUser user) {
+ return passkeyMfaAllowed(pool) && user.isWebAuthnMfaEnabled();
+ }
+
private Map<String, Object> handleOtpChallengeResponse(UserPool pool, UserPoolClient client, String challengeName,
Map<String, String> responses,
Map<String, String> clientMetadata) {
@@ -1018,13 +1096,22 @@ final class CognitoAuthFlowHandler {
String challengeName, List<String> available,
Map<String, String> challengeParameters) {
return userAuthChallengeResponse(pool, client, user.getUsername(), challengeName, available,
- challengeParameters, true);
+ challengeParameters, true, null);
}
private Map<String, Object> userAuthChallengeResponse(UserPool pool, UserPoolClient client, String username,
String challengeName, List<String> available,
Map<String, String> challengeParameters,
boolean userExists) {
+ return userAuthChallengeResponse(pool, client, username, challengeName, available, challengeParameters,
+ userExists, null);
+ }
+
+ /** {@code webAuthnChallenge} is the challenge a {@code WEB_AUTHN} answer must sign, kept with the session. */
+ private Map<String, Object> userAuthChallengeResponse(UserPool pool, UserPoolClient client, String username,
+ String challengeName, List<String> available,
+ Map<String, String> challengeParameters,
+ boolean userExists, byte[] webAuthnChallenge) {
String session = userAuthSessionToken(pool.getId(), client.getClientId());
synchronized (userAuthSessionLock) {
Instant issuedAt = clock.instant();
@@ -1039,7 +1126,7 @@ final class CognitoAuthFlowHandler {
tokens.remove();
}
store.put(session, new UserAuthSession(pool.getId(), username, client.getClientId(),
- challengeName, sessionExpiry(client, issuedAt), userExists));
+ challengeName, sessionExpiry(client, issuedAt), userExists, webAuthnChallenge));
}
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", challengeName);
@@ -1140,7 +1227,7 @@ final class CognitoAuthFlowHandler {
* when it names none: AWS's DescribeUserPool reports {@code ["PASSWORD"]} for a pool created without a
* sign-in policy. Floci now stores that default too, but a pool it persisted earlier may have none.
*/
- private static List<String> allowedFirstAuthFactors(UserPool pool) {
+ static List<String> allowedFirstAuthFactors(UserPool pool) {
Map<String, Object> policies = pool.getPolicies();
if (policies == null || !(policies.get("SignInPolicy") instanceof Map<?, ?> signInPolicy)
|| !(signInPolicy.get("AllowedFirstAuthFactors") instanceof List<?> factors) || factors.isEmpty()) {
@@ -1166,9 +1253,16 @@ final class CognitoAuthFlowHandler {
available.removeIf(challenge -> !allowed.contains("PASSWORD_SRP".equals(challenge) ? "PASSWORD" : challenge));
// Where MFA is optional, AWS lets a user who has turned on an MFA factor sign in with a password
// only, so that the second factor still follows. Floci asks for software-token codes, not for
- // email or SMS ones, so only that factor restricts the choice here.
+ // email or SMS ones, so only that factor restricts the choice here. A user who turned passkey MFA
+ // on keeps WEB_AUTHN, since a user-verified passkey satisfies MFA on its own.
if ("OPTIONAL".equals(pool.getMfaConfiguration()) && CognitoService.softwareTokenMfaEnabled(user)) {
- available.removeIf(challenge -> !"PASSWORD".equals(challenge) && !"PASSWORD_SRP".equals(challenge));
+ boolean passkeyIsMfa = passkeySatisfiesMfa(pool, user);
+ available.removeIf(challenge -> !"PASSWORD".equals(challenge) && !"PASSWORD_SRP".equals(challenge)
+ && !(passkeyIsMfa && "WEB_AUTHN".equals(challenge)));
+ }
+ // Where MFA is required, a passkey is a sign-in choice only for a user whose passkey satisfies MFA.
+ if ("ON".equals(pool.getMfaConfiguration()) && !passkeySatisfiesMfa(pool, user)) {
+ available.remove("WEB_AUTHN");
}
return available;
}
@@ -1190,6 +1284,9 @@ final class CognitoAuthFlowHandler {
available.add("SMS_OTP");
}
}
+ if (!user.getWebAuthnCredentials().isEmpty()) {
+ available.add("WEB_AUTHN");
+ }
return available;
}
@@ -1197,7 +1294,7 @@ final class CognitoAuthFlowHandler {
* The sign-in factors {@code user} has set up, as GetUserAuthFactors reports them, in the
* {@code AuthFactorType} enum's order. AWS lists what the user holds, not what the pool's
* {@code AllowedFirstAuthFactors} permits, so neither that policy nor Floci's code-delivery
- * wiring filters this list. {@code WEB_AUTHN} never appears: Floci stores no passkeys.
+ * wiring filters this list. {@code WEB_AUTHN} appears once the user has registered a passkey.
*/
List<String> configuredUserAuthFactors(CognitoUser user) {
List<String> factors = new ArrayList<>();
@@ -1210,6 +1307,9 @@ final class CognitoAuthFlowHandler {
if (hasVerifiedAttribute(user, "phone_number")) {
factors.add("SMS_OTP");
}
+ if (!user.getWebAuthnCredentials().isEmpty()) {
+ factors.add("WEB_AUTHN");
+ }
if (user.getSoftwareTokenMfaSecret() != null) {
factors.add("SOFTWARE_TOKEN");
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java
index 654466e557..24454693a5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cognito;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
import io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;
@@ -8,7 +9,6 @@ import jakarta.enterprise.context.ApplicationScoped;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
-import java.util.Base64;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
@@ -72,7 +72,7 @@ public class CognitoFederationStateStore {
String generateOpaqueKey() {
byte[] bytes = new byte[OPAQUE_KEY_BYTES];
secureRandom.nextBytes(bytes);
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
private <T> String put(ConcurrentHashMap<String, T> store, T value) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
index 61aa0e05dd..72ccdcaec0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
+import io.github.hectorvent.floci.services.cognito.model.WebAuthnConfiguration;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@@ -144,6 +145,10 @@ public class CognitoJsonHandler {
case "DeleteUserPoolClientSecret" -> handleDeleteUserPoolClientSecret(request);
case "AdminSetUserMFAPreference" -> handleAdminSetUserMFAPreference(request);
case "SetUserMFAPreference" -> handleSetUserMFAPreference(request);
+ case "StartWebAuthnRegistration" -> handleStartWebAuthnRegistration(request);
+ case "CompleteWebAuthnRegistration" -> handleCompleteWebAuthnRegistration(request);
+ case "ListWebAuthnCredentials" -> handleListWebAuthnCredentials(request);
+ case "DeleteWebAuthnCredential" -> handleDeleteWebAuthnCredential(request);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
@@ -231,14 +236,29 @@ public class CognitoJsonHandler {
request.path("UserPoolId").asText(),
request.hasNonNull("MfaConfiguration") ? request.path("MfaConfiguration").asText() : null,
softwareToken.hasNonNull("Enabled") ? softwareToken.path("Enabled").asBoolean() : null,
- otherFactorConfigured);
+ otherFactorConfigured,
+ webAuthnConfiguration(request.path("WebAuthnConfiguration")));
return Response.ok(buildMfaConfigResponse(pool)).build();
}
+ private static WebAuthnConfiguration webAuthnConfiguration(JsonNode node) {
+ if (!node.isObject()) {
+ return null;
+ }
+ WebAuthnConfiguration configuration = new WebAuthnConfiguration();
+ configuration.setRelyingPartyId(node.hasNonNull("RelyingPartyId") ? node.path("RelyingPartyId").asText() : null);
+ configuration.setUserVerification(
+ node.hasNonNull("UserVerification") ? node.path("UserVerification").asText() : null);
+ configuration.setFactorConfiguration(
+ node.hasNonNull("FactorConfiguration") ? node.path("FactorConfiguration").asText() : null);
+ return configuration;
+ }
+
/**
* Shared by Get and Set, which answer with the same members. SoftwareTokenMfaConfiguration
- * is omitted while unset, matching the live service, which returns only the factors that
- * have been configured.
+ * and WebAuthnConfiguration are omitted while unset, matching the live service, which returns
+ * only the factors that have been configured. A stored WebAuthnConfiguration reports
+ * UserVerification as {@code preferred} when it was not given, the AWS default.
*/
private ObjectNode buildMfaConfigResponse(UserPool pool) {
ObjectNode response = objectMapper.createObjectNode();
@@ -247,6 +267,17 @@ public class CognitoJsonHandler {
.put("Enabled", pool.getSoftwareTokenMfaEnabled());
}
response.put("MfaConfiguration", pool.getMfaConfiguration());
+ WebAuthnConfiguration webAuthn = pool.getWebAuthnConfiguration();
+ if (webAuthn != null) {
+ ObjectNode node = response.putObject("WebAuthnConfiguration");
+ if (webAuthn.getFactorConfiguration() != null) {
+ node.put("FactorConfiguration", webAuthn.getFactorConfiguration());
+ }
+ if (webAuthn.getRelyingPartyId() != null) {
+ node.put("RelyingPartyId", webAuthn.getRelyingPartyId());
+ }
+ node.put("UserVerification", CognitoService.webAuthnUserVerification(pool));
+ }
return response;
}
@@ -1531,7 +1562,8 @@ public class CognitoJsonHandler {
request.path("UserPoolId").asText(),
request.path("Username").asText(),
mfaSettingsUpdate(request.path("EmailMfaSettings")),
- mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")));
+ mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")),
+ webAuthnMfaEnabled(request));
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -1539,7 +1571,8 @@ public class CognitoJsonHandler {
service.setUserMFAPreference(
request.path("AccessToken").asText(),
mfaSettingsUpdate(request.path("EmailMfaSettings")),
- mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")));
+ mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")),
+ webAuthnMfaEnabled(request));
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -1549,4 +1582,44 @@ public class CognitoJsonHandler {
settings.has("PreferredMfa") ? settings.path("PreferredMfa").asBoolean() : null);
}
+ /** {@code WebAuthnMfaSettings.Enabled}, or null when the request leaves passkey MFA as it is. */
+ private static Boolean webAuthnMfaEnabled(JsonNode request) {
+ JsonNode settings = request.path("WebAuthnMfaSettings");
+ return settings.has("Enabled") ? settings.path("Enabled").asBoolean() : null;
+ }
+
+ private Response handleStartWebAuthnRegistration(JsonNode request) {
+ return Response.ok(objectMapper.valueToTree(
+ service.startWebAuthnRegistration(request.path("AccessToken").asText()))).build();
+ }
+
+ /**
+ * {@code Credential} is a document, so the SDKs send the {@code RegistrationResponseJSON} as a
+ * JSON object; a client that sends it as a JSON string is accepted too.
+ */
+ private Response handleCompleteWebAuthnRegistration(JsonNode request) {
+ JsonNode credential = request.path("Credential");
+ if (credential.isTextual()) {
+ try {
+ credential = objectMapper.readTree(credential.asText());
+ } catch (Exception e) {
+ throw new AwsException("InvalidParameterException", "Credential is not valid JSON", 400);
+ }
+ }
+ service.completeWebAuthnRegistration(request.path("AccessToken").asText(), credential);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleListWebAuthnCredentials(JsonNode request) {
+ return Response.ok(objectMapper.valueToTree(service.listWebAuthnCredentials(
+ request.path("AccessToken").asText(),
+ request.hasNonNull("MaxResults") ? request.path("MaxResults").asInt() : null,
+ request.hasNonNull("NextToken") ? request.path("NextToken").asText() : null))).build();
+ }
+
+ private Response handleDeleteWebAuthnCredential(JsonNode request) {
+ service.deleteWebAuthnCredential(request.path("AccessToken").asText(), request.path("CredentialId").asText());
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java
index b1feb0cc4f..1169a867c9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
@@ -31,7 +33,6 @@ import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
@@ -779,22 +780,14 @@ public class CognitoOAuthController {
if (!CODE_VERIFIER_PATTERN.matcher(codeVerifier).matches()) {
return "code_verifier must be 43 to 128 unreserved characters";
}
- byte[] computed = Base64.getUrlEncoder().withoutPadding()
- .encode(sha256(codeVerifier.getBytes(StandardCharsets.US_ASCII)));
+ byte[] computed = Base64Url.encode(Digests.sha256(codeVerifier.getBytes(StandardCharsets.US_ASCII)))
+ .getBytes(StandardCharsets.US_ASCII);
if (!MessageDigest.isEqual(computed, codeChallenge.getBytes(StandardCharsets.US_ASCII))) {
return "code_verifier does not match the code_challenge";
}
return null;
}
- private static byte[] sha256(byte[] value) {
- try {
- return MessageDigest.getInstance("SHA-256").digest(value);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is required for PKCE", e);
- }
- }
-
/** AWS puts the authorization request's nonce in the ID token. */
private static CognitoService.ClaimsOverride nonceClaim(String nonce) {
if (nonce == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
index 649b714fe9..e9da88e9e3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
@@ -9,6 +9,11 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
@@ -34,6 +39,8 @@ import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
+import io.github.hectorvent.floci.services.cognito.model.WebAuthnConfiguration;
+import io.github.hectorvent.floci.services.cognito.model.WebAuthnCredential;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
@@ -157,6 +164,7 @@ public class CognitoService implements ResourceProvider {
// Keyed by session token; contains SRP ephemeral state (bPrivate, B, A, secretBlock)
private final CognitoAuthFlowHandler authFlowHandler;
+ private final CognitoWebAuthn webAuthn;
private static Object[] newUserLockStripes() {
Object[] stripes = new Object[USER_LOCK_STRIPES];
@@ -310,6 +318,7 @@ public class CognitoService implements ResourceProvider {
this.messageDispatcher = messageDispatcher;
this.certificateManager = certificateManager;
this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver, clock);
+ this.webAuthn = new CognitoWebAuthn(clock);
}
// ──────────────────────────── User Pools ────────────────────────────
@@ -691,26 +700,36 @@ public class CognitoService implements ResourceProvider {
return pool;
}
+ public UserPool setUserPoolMfaConfig(String id, String mfaConfiguration,
+ Boolean softwareTokenMfaEnabled,
+ boolean otherFactorConfigured) {
+ return setUserPoolMfaConfig(id, mfaConfiguration, softwareTokenMfaEnabled, otherFactorConfigured, null);
+ }
+
/**
- * SetUserPoolMfaConfig. Stores the MFA mode and the software-token setting, which is
- * what GetUserPoolMfaConfig reports back and what the Terraform provider reads to
- * detect drift on mfa_configuration / software_token_mfa_configuration.
+ * SetUserPoolMfaConfig. Stores the MFA mode, the software-token setting and the passkey
+ * ({@code WebAuthnConfiguration}) settings, which is what GetUserPoolMfaConfig reports back
+ * and what the Terraform provider reads to detect drift on mfa_configuration /
+ * software_token_mfa_configuration / web_authn_configuration.
+ *
+ * <p>SMS and email MFA are accepted and not stored: Floci has no path to deliver an SMS or
+ * email factor, so retaining the config would claim a capability that does not exist.
*
- * <p>SMS, email and WebAuthn MFA are accepted and not stored: Floci has no path to
- * deliver an SMS or email factor, so retaining the config would claim a capability
- * that does not exist.
- */
- /**
* @param otherFactorConfigured whether EmailMfaConfiguration or SmsMfaConfiguration was
* present in the request. Both count towards the factor rules below even though
* Floci does not deliver either challenge; WebAuthnConfiguration does not, measured
* against the live service, which accepts it alongside OFF and does not accept it
* as the sole factor for ON or OPTIONAL.
+ * @param webAuthnConfiguration the request's WebAuthnConfiguration, or null to keep the stored one
*/
public UserPool setUserPoolMfaConfig(String id, String mfaConfiguration,
Boolean softwareTokenMfaEnabled,
- boolean otherFactorConfigured) {
+ boolean otherFactorConfigured,
+ WebAuthnConfiguration webAuthnConfiguration) {
UserPool pool = describeUserPool(id);
+ if (webAuthnConfiguration != null) {
+ validateWebAuthnConfiguration(webAuthnConfiguration);
+ }
// An absent MfaConfiguration means OFF, not "leave the current mode alone":
// measured against the live service, which resets a pool that was OPTIONAL back
// to OFF when the member is omitted.
@@ -744,10 +763,38 @@ public class CognitoService implements ResourceProvider {
} else if (softwareTokenMfaEnabled != null) {
pool.setSoftwareTokenMfaEnabled(softwareTokenMfaEnabled);
}
+ if (webAuthnConfiguration != null) {
+ pool.setWebAuthnConfiguration(webAuthnConfiguration);
+ }
poolStore.put(id, pool);
return pool;
}
+ private static void validateWebAuthnConfiguration(WebAuthnConfiguration configuration) {
+ String relyingPartyId = configuration.getRelyingPartyId();
+ if (relyingPartyId != null && (relyingPartyId.isEmpty() || relyingPartyId.length() > 127)) {
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value at 'webAuthnConfiguration.relyingPartyId' failed to "
+ + "satisfy constraint: Member must have length between 1 and 127", 400);
+ }
+ String userVerification = configuration.getUserVerification();
+ if (userVerification != null && !List.of("required", "preferred").contains(userVerification)) {
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value '" + userVerification + "' at "
+ + "'webAuthnConfiguration.userVerification' failed to satisfy constraint: Member must "
+ + "satisfy enum value set: [required, preferred]", 400);
+ }
+ String factorConfiguration = configuration.getFactorConfiguration();
+ if (factorConfiguration != null
+ && !List.of("SINGLE_FACTOR", "MULTI_FACTOR_WITH_USER_VERIFICATION").contains(factorConfiguration)) {
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value '" + factorConfiguration + "' at "
+ + "'webAuthnConfiguration.factorConfiguration' failed to satisfy constraint: Member "
+ + "must satisfy enum value set: [SINGLE_FACTOR, MULTI_FACTOR_WITH_USER_VERIFICATION]",
+ 400);
+ }
+ }
+
public List<UserPool> listUserPools() {
String region = regionResolver.getRegion();
return poolStore.scan(k -> true).stream()
@@ -3346,6 +3393,209 @@ public class CognitoService implements ResourceProvider {
}
}
+ // ──────────────────────────── Passkeys (WebAuthn) ────────────────────────────
+
+ /** StartWebAuthnRegistration: creation options for the access token's user, whose challenge the app client must answer. */
+ public Map<String, Object> startWebAuthnRegistration(String accessToken) {
+ VerifiedAccessToken token = verifyAccessToken(accessToken);
+ requireScope(accessToken, USER_ADMIN_SCOPE);
+ UserPool pool = describeUserPool(token.poolId());
+ requireWebAuthnEnabled(pool);
+ String relyingPartyId = webAuthnRelyingPartyId(pool);
+ CognitoUser user = adminGetUser(token.poolId(), token.username());
+ if (user.getWebAuthnCredentials().size() >= CognitoWebAuthn.MAX_CREDENTIALS_PER_USER) {
+ throw new AwsException("LimitExceededException",
+ "A user can register at most " + CognitoWebAuthn.MAX_CREDENTIALS_PER_USER + " passkeys.", 400);
+ }
+ String userHandle = user.getAttributes().getOrDefault("sub", user.getUsername());
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("CredentialCreationOptions", webAuthn.startRegistration(pool.getId(), user.getUsername(),
+ userHandle, token.clientId(), relyingPartyId, webAuthnUserVerification(pool),
+ user.getWebAuthnCredentials()));
+ return response;
+ }
+
+ /** CompleteWebAuthnRegistration: verifies the {@code RegistrationResponseJSON} and stores the passkey. */
+ public void completeWebAuthnRegistration(String accessToken, JsonNode credential) {
+ VerifiedAccessToken token = verifyAccessToken(accessToken);
+ requireScope(accessToken, USER_ADMIN_SCOPE);
+ if (credential == null || !credential.isObject()) {
+ throw new AwsException("InvalidParameterException", "Credential is required", 400);
+ }
+ UserPool pool = describeUserPool(token.poolId());
+ requireWebAuthnEnabled(pool);
+ WebAuthnCredential registered = webAuthn.completeRegistration(pool.getId(), token.username(),
+ token.clientId(), credential);
+ synchronized (userLock(token.poolId(), token.username())) {
+ CognitoUser user = adminGetUser(token.poolId(), token.username());
+ List<WebAuthnCredential> credentials = user.getWebAuthnCredentials();
+ if (credentials.size() >= CognitoWebAuthn.MAX_CREDENTIALS_PER_USER) {
+ throw new AwsException("LimitExceededException",
+ "A user can register at most " + CognitoWebAuthn.MAX_CREDENTIALS_PER_USER + " passkeys.",
+ 400);
+ }
+ if (credentials.stream().anyMatch(c -> c.getCredentialId().equals(registered.getCredentialId()))) {
+ throw new AwsException("InvalidParameterException", "This passkey is already registered.", 400);
+ }
+ credentials.add(registered);
+ user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
+ userStore.put(userKey(token.poolId(), user.getUsername()), user);
+ }
+ }
+
+ /**
+ * ListWebAuthnCredentials: the access token's user's passkeys, oldest first, a page of at most 20 at
+ * a time. {@code NextToken} is a cursor on the last passkey listed, so deleting a passkey between two
+ * pages does not shift the next page past one.
+ */
+ public Map<String, Object> listWebAuthnCredentials(String accessToken, Integer maxResults, String nextToken) {
+ VerifiedAccessToken token = verifyAccessToken(accessToken);
+ requireScope(accessToken, USER_ADMIN_SCOPE);
+ if (maxResults != null && (maxResults < 0 || maxResults > CognitoWebAuthn.MAX_CREDENTIALS_PER_USER)) {
+ String constraint = maxResults < 0
+ ? "greater than or equal to 0"
+ : "less than or equal to " + CognitoWebAuthn.MAX_CREDENTIALS_PER_USER;
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value '" + maxResults + "' at 'maxResults' failed to satisfy "
+ + "constraint: Member must have value " + constraint, 400);
+ }
+ int pageSize = maxResults == null || maxResults == 0 ? CognitoWebAuthn.MAX_CREDENTIALS_PER_USER : maxResults;
+ List<WebAuthnCredential> credentials = adminGetUser(token.poolId(), token.username()).getWebAuthnCredentials();
+ PaginatedResult<WebAuthnCredential> listed = Pagination.paginate(credentials,
+ CognitoService::webAuthnCredentialCursor, pageSize, nextToken, "ListWebAuthnCredentials",
+ invalid -> new AwsException("InvalidParameterException", "Invalid NextToken", 400));
+ List<Map<String, Object>> page = new ArrayList<>();
+ for (WebAuthnCredential credential : listed.items()) {
+ Map<String, Object> description = new LinkedHashMap<>();
+ if (credential.getAuthenticatorAttachment() != null) {
+ description.put("AuthenticatorAttachment", credential.getAuthenticatorAttachment());
+ }
+ description.put("AuthenticatorTransports", credential.getTransports());
+ description.put("CreatedAt", credential.getCreatedAtMillis() / 1000.0);
+ description.put("CredentialId", credential.getCredentialId());
+ description.put("FriendlyCredentialName", credential.getFriendlyCredentialName());
+ description.put("RelyingPartyId", credential.getRelyingPartyId());
+ page.add(description);
+ }
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("Credentials", page);
+ if (listed.nextToken() != null) {
+ response.put("NextToken", listed.nextToken());
+ }
+ return response;
+ }
+
+ /** Orders passkeys by registration time, the credential ID telling apart two registered in one millisecond. */
+ private static String webAuthnCredentialCursor(WebAuthnCredential credential) {
+ return String.format(Locale.ROOT, "%019d/%s", credential.getCreatedAtMillis(), credential.getCredentialId());
+ }
+
+ /** DeleteWebAuthnCredential: removes one of the access token's user's passkeys. */
+ public void deleteWebAuthnCredential(String accessToken, String credentialId) {
+ VerifiedAccessToken token = verifyAccessToken(accessToken);
+ requireScope(accessToken, USER_ADMIN_SCOPE);
+ synchronized (userLock(token.poolId(), token.username())) {
+ CognitoUser user = adminGetUser(token.poolId(), token.username());
+ List<WebAuthnCredential> credentials = user.getWebAuthnCredentials();
+ if (!credentials.removeIf(c -> c.getCredentialId().equals(credentialId))) {
+ throw new AwsException("ResourceNotFoundException", "Passkey credential not found", 400);
+ }
+ user.setWebAuthnCredentials(credentials);
+ user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
+ userStore.put(userKey(token.poolId(), user.getUsername()), user);
+ }
+ }
+
+ /** Passkeys are on for a pool whose sign-in policy allows {@code WEB_AUTHN} as a first factor. */
+ private static void requireWebAuthnEnabled(UserPool pool) {
+ if (!passkeysInFeaturePlan(pool)
+ || !CognitoAuthFlowHandler.allowedFirstAuthFactors(pool).contains("WEB_AUTHN")) {
+ throw new AwsException("WebAuthnNotEnabledException",
+ "Passkey sign-in is not enabled for this user pool. Add WEB_AUTHN to the pool's "
+ + "SignInPolicy AllowedFirstAuthFactors.", 400);
+ }
+ }
+
+ /** AWS offers passkeys, and passkey MFA with them, in every feature plan but Lite. */
+ private static boolean passkeysInFeaturePlan(UserPool pool) {
+ return !"LITE".equals(pool.getUserPoolTier());
+ }
+
+ /**
+ * The relying party ID passkeys are registered for: the configured one, or as AWS defaults it,
+ * the pool's custom domain, then its prefix domain.
+ */
+ String webAuthnRelyingPartyId(UserPool pool) {
+ WebAuthnConfiguration configuration = pool.getWebAuthnConfiguration();
+ if (configuration != null && configuration.getRelyingPartyId() != null) {
+ return configuration.getRelyingPartyId();
+ }
+ List<UserPoolDomain> domains = domainStore.scan(key -> true).stream()
+ .filter(domain -> pool.getId().equals(domain.getUserPoolId()))
+ .toList();
+ for (UserPoolDomain domain : domains) {
+ if (domain.isCustomDomain()) {
+ return domain.getDomain();
+ }
+ }
+ if (!domains.isEmpty()) {
+ // A prefix domain is <prefix>.auth.<region>.amazoncognito.<partition suffix>.
+ String region = AwsArnUtils.regionOrDefault(pool.getArn(), regionResolver.getDefaultRegion());
+ return domains.get(0).getDomain() + ".auth." + region + "."
+ + AwsRegions.dnsSuffixFor(region).replaceFirst("^amazonaws", "amazoncognito");
+ }
+ throw new AwsException("WebAuthnConfigurationMissingException",
+ "The user pool has no relying party ID and no domain to default it to. Set "
+ + "WebAuthnConfiguration.RelyingPartyId with SetUserPoolMfaConfig.", 400);
+ }
+
+ /** {@code required} or {@code preferred}, the AWS default. */
+ static String webAuthnUserVerification(UserPool pool) {
+ WebAuthnConfiguration configuration = pool.getWebAuthnConfiguration();
+ return configuration != null && configuration.getUserVerification() != null
+ ? configuration.getUserVerification() : "preferred";
+ }
+
+ /**
+ * The user verification a passkey sign-in by {@code user} needs: the pool's setting, and always for
+ * a user whose passkey stands in for MFA, since AWS asks a user who turned passkey MFA on to verify
+ * themselves and only a user-verified passkey satisfies MFA.
+ */
+ private static String webAuthnSignInUserVerification(UserPool pool, CognitoUser user) {
+ return CognitoAuthFlowHandler.passkeySatisfiesMfa(pool, user) ? "required" : webAuthnUserVerification(pool);
+ }
+
+ /** The {@code CREDENTIAL_REQUEST_OPTIONS} of a {@code WEB_AUTHN} challenge for {@code user}. */
+ String webAuthnRequestOptions(UserPool pool, CognitoUser user, byte[] challenge, long timeoutMillis) {
+ return webAuthn.requestOptions(webAuthnRelyingPartyId(pool), webAuthnSignInUserVerification(pool, user),
+ user.getWebAuthnCredentials(), challenge, timeoutMillis);
+ }
+
+ byte[] newWebAuthnChallenge() {
+ return webAuthn.newChallenge();
+ }
+
+ /**
+ * Verifies a {@code WEB_AUTHN} challenge answer for {@code username} and records the
+ * authenticator's new signature counter, both under the user's lock, so two sign-ins with one
+ * passkey cannot both pass the counter check. Returns whether the authenticator verified the user.
+ */
+ boolean verifyWebAuthnSignIn(UserPool pool, String username, byte[] challenge, String credentialJson) {
+ String relyingPartyId = webAuthnRelyingPartyId(pool);
+ CognitoUser resolved = adminGetUser(pool.getId(), username);
+ synchronized (userLock(pool.getId(), resolved.getUsername())) {
+ CognitoUser user = adminGetUser(pool.getId(), resolved.getUsername());
+ boolean userVerificationRequired = "required".equals(webAuthnSignInUserVerification(pool, user));
+ CognitoWebAuthn.Assertion assertion = webAuthn.verifyAssertion(relyingPartyId, userVerificationRequired,
+ challenge, user.getWebAuthnCredentials(), credentialJson);
+ WebAuthnCredential credential = assertion.credential();
+ credential.setSignCount(assertion.signCount());
+ credential.setUserVerified(credential.isUserVerified() || assertion.userVerified());
+ userStore.put(userKey(pool.getId(), user.getUsername()), user);
+ return assertion.userVerified();
+ }
+ }
+
public void changePassword(String accessToken, String previousPassword, String proposedPassword) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
@@ -4134,14 +4384,12 @@ public class CognitoService implements ResourceProvider {
String headerJson = String.format(
"{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}",
escapeJson(getSigningKeyId(pool)));
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(headerJson);
}
private static String encodeJsonBase64Url(Map<String, Object> claims) {
try {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(MAPPER.writeValueAsBytes(claims));
+ return Base64Url.encode(MAPPER.writeValueAsBytes(claims));
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to serialize JWT claims", e);
}
@@ -4153,8 +4401,7 @@ public class CognitoService implements ResourceProvider {
String headerJson = String.format(
"{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}",
escapeJson(getSigningKeyId(pool)));
- String header = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
+ String header = Base64Url.encode(headerJson);
String clientId = client != null ? client.getClientId() : null;
String audFragment = (clientId != null && !clientId.isBlank() && "id".equals(type))
? ",\"aud\":\"" + escapeJson(clientId) + "\""
@@ -4164,8 +4411,7 @@ public class CognitoService implements ResourceProvider {
"\"exp\":%d,\"iat\":%d,\"username\":\"%s\"%s}",
UUID.randomUUID(), type, escapeJson(getIssuer(pool.getId())), now + lifetimeSeconds, now, username, audFragment
);
- String payload = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
+ String payload = Base64Url.encode(payloadJson);
return signJwt(header, payload, getSigningPrivateKey(pool));
}
@@ -4173,8 +4419,7 @@ public class CognitoService implements ResourceProvider {
String headerJson = String.format(
"{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}",
escapeJson(getSigningKeyId(pool)));
- String header = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
+ String header = Base64Url.encode(headerJson);
long now = System.currentTimeMillis() / 1000L;
long lifetimeSeconds = resolveAccessTokenLifetimeSeconds(client);
@@ -4193,8 +4438,7 @@ public class CognitoService implements ResourceProvider {
}
payloadJson.append("}");
- String payload = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(payloadJson.toString().getBytes(StandardCharsets.UTF_8));
+ String payload = Base64Url.encode(payloadJson.toString());
return signJwt(header, payload, getSigningPrivateKey(pool));
}
@@ -4444,7 +4688,7 @@ public class CognitoService implements ResourceProvider {
signature.initSign(signingKey);
signature.update(data.getBytes(StandardCharsets.UTF_8));
byte[] sig = signature.sign();
- return Base64.getUrlEncoder().withoutPadding().encodeToString(sig);
+ return Base64Url.encode(sig);
} catch (Exception e) {
throw new RuntimeException("JWT signing failed", e);
}
@@ -4541,17 +4785,7 @@ public class CognitoService implements ResourceProvider {
}
String hashPassword(String password) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
- StringBuilder hex = new StringBuilder();
- for (byte b : hash) {
- hex.append(String.format("%02x", b));
- }
- return hex.toString();
- } catch (Exception e) {
- throw new RuntimeException("Password hashing failed", e);
- }
+ return Digests.sha256Hex(password);
}
private void updateUserPassword(CognitoUser user, String password) {
@@ -4824,7 +5058,7 @@ public class CognitoService implements ResourceProvider {
return null;
}
- record VerifiedAccessToken(String username, String poolId, String subject) {}
+ record VerifiedAccessToken(String username, String poolId, String subject, String clientId) {}
/** Verified JWT details for services that enforce Cognito user-pool authorizers. */
public record VerifiedApiGatewayToken(String poolId, String tokenUse, Map<String, Object> claims) {}
@@ -4923,7 +5157,7 @@ public class CognitoService implements ResourceProvider {
validateTokenNotRevoked(originJti, poolId, "access");
}
validateUserNotGloballySignedOut(username, poolId, "access", issuedAt);
- return new VerifiedAccessToken(username, poolId, subject);
+ return new VerifiedAccessToken(username, poolId, subject, clientId);
} catch (AwsException e) {
throw e;
} catch (Exception e) {
@@ -5542,23 +5776,38 @@ public class CognitoService implements ResourceProvider {
public void adminSetUserMFAPreference(String userPoolId, String username,
MfaSettingsUpdate email, MfaSettingsUpdate softwareToken) {
+ adminSetUserMFAPreference(userPoolId, username, email, softwareToken, null);
+ }
+
+ /** @param webAuthnMfaEnabled {@code WebAuthnMfaSettings.Enabled}, or null to leave passkey MFA as it is */
+ public void adminSetUserMFAPreference(String userPoolId, String username, MfaSettingsUpdate email,
+ MfaSettingsUpdate softwareToken, Boolean webAuthnMfaEnabled) {
CognitoUser resolvedUser = adminGetUser(userPoolId, username);
synchronized (userLock(userPoolId, resolvedUser.getUsername())) {
- updateMfaPreferenceUnderUserLock(userPoolId, resolvedUser.getUsername(), email, softwareToken);
+ updateMfaPreferenceUnderUserLock(userPoolId, resolvedUser.getUsername(), email, softwareToken,
+ webAuthnMfaEnabled);
}
}
public void setUserMFAPreference(String accessToken, MfaSettingsUpdate email, MfaSettingsUpdate softwareToken) {
+ setUserMFAPreference(accessToken, email, softwareToken, null);
+ }
+
+ /** @param webAuthnMfaEnabled {@code WebAuthnMfaSettings.Enabled}, or null to leave passkey MFA as it is */
+ public void setUserMFAPreference(String accessToken, MfaSettingsUpdate email, MfaSettingsUpdate softwareToken,
+ Boolean webAuthnMfaEnabled) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
synchronized (userLock(token.poolId(), token.username())) {
- updateMfaPreferenceUnderUserLock(token.poolId(), token.username(), email, softwareToken);
+ updateMfaPreferenceUnderUserLock(token.poolId(), token.username(), email, softwareToken,
+ webAuthnMfaEnabled);
}
}
- private void updateMfaPreferenceUnderUserLock(String poolId, String username,
- MfaSettingsUpdate email, MfaSettingsUpdate softwareToken) {
+ private void updateMfaPreferenceUnderUserLock(String poolId, String username, MfaSettingsUpdate email,
+ MfaSettingsUpdate softwareToken, Boolean webAuthnMfaEnabled) {
CognitoUser user = adminGetUser(poolId, username);
+ requirePasskeyMfaAvailable(describeUserPool(poolId), webAuthnMfaEnabled);
if (Boolean.TRUE.equals(email.preferredMfa()) && Boolean.TRUE.equals(softwareToken.preferredMfa())) {
throw new AwsException("InvalidParameterException",
"Only one MFA method can be set as preferred.", 400);
@@ -5592,6 +5841,9 @@ public class CognitoService implements ResourceProvider {
settings.setPreferredMfa(tokenState.preferred());
user.setSoftwareTokenMfaSettings(settings);
}
+ if (webAuthnMfaEnabled != null) {
+ user.setWebAuthnMfaEnabled(webAuthnMfaEnabled);
+ }
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(poolId, user.getUsername()), user);
}
@@ -5600,6 +5852,28 @@ public class CognitoService implements ResourceProvider {
static final FactorState OFF = new FactorState(false, false);
}
+ /**
+ * A user can turn passkey MFA on only where the pool's {@code WebAuthnConfiguration} lets a passkey
+ * stand in for MFA ({@code FactorConfiguration} {@code MULTI_FACTOR_WITH_USER_VERIFICATION}) and the
+ * pool is in the Essentials tier or higher, as the SetUserMFAPreference reference requires. Turning
+ * it off is always accepted.
+ */
+ private static void requirePasskeyMfaAvailable(UserPool pool, Boolean webAuthnMfaEnabled) {
+ if (!Boolean.TRUE.equals(webAuthnMfaEnabled)) {
+ return;
+ }
+ if (!CognitoAuthFlowHandler.passkeyMfaAllowed(pool)) {
+ throw new AwsException("InvalidParameterException",
+ "Passkey MFA cannot be enabled because the user pool's WebAuthnConfiguration "
+ + "FactorConfiguration is not MULTI_FACTOR_WITH_USER_VERIFICATION.", 400);
+ }
+ if (!passkeysInFeaturePlan(pool)) {
+ throw new AwsException("InvalidParameterException",
+ "Passkey MFA cannot be enabled because the user pool is not in the Essentials tier or higher.",
+ 400);
+ }
+ }
+
/**
* The state a factor ends up in after {@code update}. Disabling a factor drops its preference,
* and preferring a disabled one is refused.
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthn.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthn.java
new file mode 100644
index 0000000000..8b9a31756d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthn.java
@@ -0,0 +1,531 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
+import io.github.hectorvent.floci.core.common.DomainNames;
+import io.github.hectorvent.floci.core.common.PublicKeys;
+import io.github.hectorvent.floci.services.cognito.model.WebAuthnCredential;
+import org.jboss.logging.Logger;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.MessageDigest;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.Signature;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Passkey registration and sign-in checks for Cognito user pools.
+ *
+ * <p>Cognito accepts ES256 and RS256 passkeys and does not enforce attestation, so a registration's
+ * attestation statement is never verified, whatever its format: the passkey comes from the
+ * authenticator data alone. The origin of a ceremony must be the relying party ID or one of its
+ * subdomains, over HTTPS, or HTTP for a local page.
+ */
+final class CognitoWebAuthn {
+
+ private static final Logger LOG = Logger.getLogger(CognitoWebAuthn.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
+ /** The most passkeys a user can register, as AWS documents. */
+ static final int MAX_CREDENTIALS_PER_USER = 20;
+ /** The {@code timeout} of AWS's creation options. */
+ static final long REGISTRATION_TIMEOUT_MILLIS = 60_000L;
+ private static final Duration REGISTRATION_CHALLENGE_LIFETIME = Duration.ofMinutes(5);
+ /** The COSE algorithms Cognito recognizes: ES256 and RS256. */
+ private static final int ES256 = -7;
+ private static final int RS256 = -257;
+ private static final List<Integer> SUPPORTED_ALGORITHMS = List.of(ES256, RS256);
+ // COSE key labels: the key type and algorithm, then the EC2 or RSA key members.
+ private static final String COSE_KEY_TYPE = "1";
+ private static final String COSE_ALGORITHM = "3";
+ private static final String COSE_EC2_CURVE = "-1";
+ private static final String COSE_EC2_X = "-2";
+ private static final String COSE_EC2_Y = "-3";
+ private static final String COSE_RSA_MODULUS = "-1";
+ private static final String COSE_RSA_EXPONENT = "-2";
+ private static final int COSE_KEY_TYPE_EC2 = 2;
+ private static final int COSE_KEY_TYPE_RSA = 3;
+ private static final int COSE_CURVE_P256 = 1;
+ // Authenticator data flags.
+ private static final int FLAG_USER_PRESENT = 0x01;
+ private static final int FLAG_USER_VERIFIED = 0x04;
+ private static final int FLAG_BACKUP_ELIGIBLE = 0x08;
+ private static final int FLAG_BACKUP_STATE = 0x10;
+ private static final int FLAG_ATTESTED_CREDENTIAL_DATA = 0x40;
+ /** The relying party ID hash, the flags and the signature counter. */
+ private static final int AUTHENTICATOR_DATA_HEADER_LENGTH = 37;
+
+ private final SecureRandom random = new SecureRandom();
+ private final Clock clock;
+ private final ConcurrentHashMap<String, PendingRegistration> pendingRegistrations = new ConcurrentHashMap<>();
+
+ private record PendingRegistration(byte[] challenge, String clientId, String relyingPartyId,
+ boolean userVerificationRequired, Instant expiresAt) {}
+
+ /** A verified sign-in: the new signature counter and whether the authenticator verified the user. */
+ record Assertion(WebAuthnCredential credential, long signCount, boolean userVerified) {}
+
+ /** The authenticator data of a ceremony; {@code attested} is set when it carries a new passkey. */
+ private record AuthenticatorData(byte[] relyingPartyIdHash, int flags, long signCount,
+ AttestedCredential attested) {
+ boolean flag(int mask) {
+ return (flags & mask) != 0;
+ }
+ }
+
+ /**
+ * A passkey's attested credential data: its ID and COSE public key, and {@code encoded}, the
+ * WebAuthn binary form of the three (AAGUID, ID and key) that a passkey is stored as.
+ */
+ private record AttestedCredential(byte[] credentialId, JsonNode publicKey, byte[] encoded) {}
+
+ /** Why a ceremony failed. A registration answers each with its own error, a sign-in with NotAuthorized. */
+ private enum Failure { MALFORMED, ORIGIN, RELYING_PARTY, CHALLENGE, NOT_SUPPORTED, INVALID }
+
+ private static final class CeremonyException extends Exception {
+ private final Failure failure;
+
+ CeremonyException(Failure failure, String message) {
+ super(message);
+ this.failure = failure;
+ }
+ }
+
+ CognitoWebAuthn(Clock clock) {
+ this.clock = clock;
+ }
+
+ /**
+ * Issues the {@code CredentialCreationOptions} of StartWebAuthnRegistration and remembers its
+ * challenge for this user and app client. A later call replaces an earlier, unfinished one.
+ */
+ Map<String, Object> startRegistration(String poolId, String username, String userHandle, String clientId,
+ String relyingPartyId, String userVerification,
+ List<WebAuthnCredential> registered) {
+ byte[] challenge = newChallenge();
+ pendingRegistrations.put(registrationKey(poolId, username), new PendingRegistration(challenge, clientId,
+ relyingPartyId, "required".equals(userVerification),
+ clock.instant().plus(REGISTRATION_CHALLENGE_LIFETIME)));
+
+ Map<String, Object> selection = new LinkedHashMap<>();
+ selection.put("requireResidentKey", true);
+ selection.put("residentKey", "required");
+ selection.put("userVerification", userVerification);
+ List<Map<String, Object>> exclude = new ArrayList<>();
+ for (WebAuthnCredential credential : registered) {
+ exclude.add(Map.of("id", credential.getCredentialId(), "type", "public-key"));
+ }
+ List<Map<String, Object>> algorithms = new ArrayList<>();
+ for (int algorithm : SUPPORTED_ALGORITHMS) {
+ algorithms.add(Map.of("alg", algorithm, "type", "public-key"));
+ }
+ Map<String, Object> options = new LinkedHashMap<>();
+ options.put("authenticatorSelection", selection);
+ options.put("challenge", Base64Url.encode(challenge));
+ options.put("excludeCredentials", exclude);
+ options.put("pubKeyCredParams", algorithms);
+ options.put("rp", Map.of("id", relyingPartyId, "name", relyingPartyId));
+ options.put("timeout", REGISTRATION_TIMEOUT_MILLIS);
+ options.put("user", Map.of(
+ "displayName", username,
+ "id", Base64Url.encode(userHandle),
+ "name", username));
+ return options;
+ }
+
+ /**
+ * Verifies a {@code RegistrationResponseJSON} against the user's pending registration, which it
+ * consumes, and returns the passkey to store.
+ */
+ WebAuthnCredential completeRegistration(String poolId, String username, String clientId, JsonNode credential) {
+ String key = registrationKey(poolId, username);
+ PendingRegistration pending = pendingRegistrations.get(key);
+ if (pending == null || clock.instant().isAfter(pending.expiresAt())) {
+ throw new AwsException("WebAuthnChallengeNotFoundException",
+ "The passkey registration challenge was not found or has expired.", 400);
+ }
+ // Another client's attempt leaves the registration for the client that started it.
+ if (!pending.clientId().equals(clientId)) {
+ throw new AwsException("WebAuthnClientMismatchException",
+ "The access token is for a different app client than the one that started the registration.",
+ 400);
+ }
+ if (!pendingRegistrations.remove(key, pending)) {
+ throw new AwsException("WebAuthnChallengeNotFoundException",
+ "The passkey registration challenge was not found or has expired.", 400);
+ }
+ JsonNode response = credential.path("response");
+ byte[] clientDataJson = requiredBytes(response, "clientDataJSON");
+ byte[] attestationObject = requiredBytes(response, "attestationObject");
+
+ AuthenticatorData authenticatorData;
+ try {
+ authenticatorData = verifyRegistration(pending, clientDataJson, attestationObject);
+ } catch (CeremonyException e) {
+ LOG.debugv(e, "Passkey registration failed verification for {0} in pool {1}", username, poolId);
+ throw registrationError(e, pending.relyingPartyId());
+ }
+
+ AttestedCredential attested = authenticatorData.attested();
+ WebAuthnCredential stored = new WebAuthnCredential();
+ stored.setCredentialId(Base64Url.encode(attested.credentialId()));
+ stored.setAttestedCredentialData(Base64Url.encode(attested.encoded()));
+ stored.setSignCount(authenticatorData.signCount());
+ stored.setUserVerified(authenticatorData.flag(FLAG_USER_VERIFIED));
+ stored.setBackupEligible(authenticatorData.flag(FLAG_BACKUP_ELIGIBLE));
+ stored.setBackupState(authenticatorData.flag(FLAG_BACKUP_STATE));
+ Set<String> transports = new LinkedHashSet<>();
+ response.path("transports").forEach(transport -> transports.add(transport.asText()));
+ stored.setTransports(new ArrayList<>(transports));
+ String attachment = credential.path("authenticatorAttachment").asText(null);
+ stored.setAuthenticatorAttachment(attachment);
+ // AWS generates the name; Floci has no catalog of authenticator models to name a passkey after.
+ stored.setFriendlyCredentialName("cross-platform".equals(attachment) ? "Roaming passkey" : "Passkey");
+ stored.setRelyingPartyId(pending.relyingPartyId());
+ stored.setCreatedAtMillis(clock.millis());
+ return stored;
+ }
+
+ private static AuthenticatorData verifyRegistration(PendingRegistration pending, byte[] clientDataJson,
+ byte[] attestationObject) throws CeremonyException {
+ verifyClientData(clientDataJson, "webauthn.create", pending.challenge(), pending.relyingPartyId());
+ JsonNode attestation = decodeCbor(attestationObject, "attestationObject");
+ if (!attestation.path("fmt").isTextual()) {
+ throw new CeremonyException(Failure.MALFORMED, "attestationObject has no fmt");
+ }
+ AuthenticatorData authenticatorData = parseAuthenticatorData(cborBytes(attestation, "authData"));
+ verifyAuthenticatorData(authenticatorData, pending.relyingPartyId(), pending.userVerificationRequired());
+ if (authenticatorData.attested() == null) {
+ throw new CeremonyException(Failure.INVALID, "the authenticator data has no attested credential data");
+ }
+ // Refuses a key of an algorithm Cognito does not recognize before it is stored.
+ publicKey(authenticatorData.attested().publicKey());
+ return authenticatorData;
+ }
+
+ private static AwsException registrationError(CeremonyException e, String relyingPartyId) {
+ return switch (e.failure) {
+ case MALFORMED -> new AwsException("InvalidParameterException",
+ "The passkey credential is malformed.", 400);
+ case ORIGIN -> new AwsException("WebAuthnOriginNotAllowedException",
+ "The passkey credential's origin does not match the relying party ID " + relyingPartyId + ".",
+ 400);
+ case RELYING_PARTY -> new AwsException("WebAuthnRelyingPartyMismatchException",
+ "The passkey credential is for a different relying party than " + relyingPartyId + ".", 400);
+ case CHALLENGE -> new AwsException("WebAuthnChallengeNotFoundException",
+ "The passkey credential does not answer the registration challenge.", 400);
+ case NOT_SUPPORTED -> new AwsException("WebAuthnCredentialNotSupportedException",
+ "The passkey credential is not supported: " + e.getMessage(), 400);
+ case INVALID -> new AwsException("InvalidParameterException",
+ "The passkey credential failed verification: " + e.getMessage(), 400);
+ };
+ }
+
+ /** A fresh sign-in challenge for a {@code WEB_AUTHN} USER_AUTH challenge. */
+ byte[] newChallenge() {
+ byte[] challenge = new byte[32];
+ random.nextBytes(challenge);
+ return challenge;
+ }
+
+ /**
+ * The {@code CREDENTIAL_REQUEST_OPTIONS} challenge parameter: a {@code PublicKeyCredentialRequestOptionsJSON}
+ * that allows the user's registered passkeys.
+ */
+ String requestOptions(String relyingPartyId, String userVerification, List<WebAuthnCredential> registered,
+ byte[] challenge, long timeoutMillis) {
+ List<Map<String, Object>> allow = new ArrayList<>();
+ for (WebAuthnCredential credential : registered) {
+ Map<String, Object> descriptor = new LinkedHashMap<>();
+ descriptor.put("id", credential.getCredentialId());
+ descriptor.put("type", "public-key");
+ if (!credential.getTransports().isEmpty()) {
+ descriptor.put("transports", credential.getTransports());
+ }
+ allow.add(descriptor);
+ }
+ Map<String, Object> options = new LinkedHashMap<>();
+ options.put("challenge", Base64Url.encode(challenge));
+ options.put("timeout", timeoutMillis);
+ options.put("rpId", relyingPartyId);
+ options.put("allowCredentials", allow);
+ options.put("userVerification", userVerification);
+ try {
+ return MAPPER.writeValueAsString(options);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InternalErrorException", "Failed to build the passkey request options", 500);
+ }
+ }
+
+ /**
+ * Verifies an {@code AuthenticationResponseJSON} against the challenge of a {@code WEB_AUTHN}
+ * USER_AUTH challenge and the user's registered passkeys. Any failure is a failed sign-in.
+ */
+ Assertion verifyAssertion(String relyingPartyId, boolean userVerificationRequired, byte[] challenge,
+ List<WebAuthnCredential> registered, String credentialJson) {
+ JsonNode credential;
+ try {
+ credential = MAPPER.readTree(credentialJson);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidParameterException", "CREDENTIAL is not valid JSON", 400);
+ }
+ if (credential == null || !credential.isObject()) {
+ throw new AwsException("InvalidParameterException", "CREDENTIAL is not valid JSON", 400);
+ }
+ String credentialId = credential.path("rawId").asText(credential.path("id").asText(""));
+ WebAuthnCredential stored = null;
+ for (WebAuthnCredential candidate : registered) {
+ if (candidate.getCredentialId().equals(credentialId)) {
+ stored = candidate;
+ break;
+ }
+ }
+ if (stored == null) {
+ throw new AwsException("NotAuthorizedException", "The passkey is not registered for this user.", 400);
+ }
+ JsonNode response = credential.path("response");
+ byte[] authenticatorData = requiredBytes(response, "authenticatorData");
+ byte[] clientDataJson = requiredBytes(response, "clientDataJSON");
+ byte[] signature = requiredBytes(response, "signature");
+ AuthenticatorData verified;
+ try {
+ verified = verifySignIn(relyingPartyId, userVerificationRequired, challenge, stored, authenticatorData,
+ clientDataJson, signature);
+ } catch (CeremonyException e) {
+ if (e.failure == Failure.MALFORMED) {
+ throw new AwsException("InvalidParameterException", "CREDENTIAL is malformed", 400);
+ }
+ LOG.debugv(e, "Passkey sign-in failed verification for credential {0}", credentialId);
+ throw new AwsException("NotAuthorizedException", "Failed to verify the passkey: " + e.getMessage(), 400);
+ }
+ return new Assertion(stored, verified.signCount(), verified.flag(FLAG_USER_VERIFIED));
+ }
+
+ private static AuthenticatorData verifySignIn(String relyingPartyId, boolean userVerificationRequired,
+ byte[] challenge, WebAuthnCredential stored,
+ byte[] authenticatorData, byte[] clientDataJson,
+ byte[] signature) throws CeremonyException {
+ verifyClientData(clientDataJson, "webauthn.get", challenge, relyingPartyId);
+ AuthenticatorData parsed = parseAuthenticatorData(authenticatorData);
+ verifyAuthenticatorData(parsed, relyingPartyId, userVerificationRequired);
+ JsonNode publicKey = readAttestedCredential(decode(stored.getAttestedCredentialData()), 0).publicKey();
+ if (!signatureMatches(publicKey, authenticatorData, Digests.sha256(clientDataJson), signature)) {
+ throw new CeremonyException(Failure.INVALID, "the signature does not match the passkey");
+ }
+ // A counter that does not move past the stored one suggests a cloned authenticator; one that
+ // stays at zero on both sides is an authenticator that keeps no counter.
+ if ((parsed.signCount() != 0 || stored.getSignCount() != 0) && parsed.signCount() <= stored.getSignCount()) {
+ throw new CeremonyException(Failure.INVALID, "the signature counter did not increase");
+ }
+ return parsed;
+ }
+
+ /** Checks a ceremony's {@code clientDataJSON}: its type, the challenge it answers and its origin. */
+ private static void verifyClientData(byte[] clientDataJson, String type, byte[] challenge, String relyingPartyId)
+ throws CeremonyException {
+ JsonNode clientData;
+ try {
+ clientData = MAPPER.readTree(clientDataJson);
+ } catch (IOException e) {
+ throw new CeremonyException(Failure.MALFORMED, "clientDataJSON is not valid JSON");
+ }
+ if (clientData == null || !clientData.isObject()) {
+ throw new CeremonyException(Failure.MALFORMED, "clientDataJSON is not a JSON object");
+ }
+ if (!type.equals(clientData.path("type").asText())) {
+ throw new CeremonyException(Failure.INVALID, "clientDataJSON is not of type " + type);
+ }
+ if (!Base64Url.encode(challenge).equals(clientData.path("challenge").asText())) {
+ throw new CeremonyException(Failure.CHALLENGE, "the credential does not answer the challenge");
+ }
+ if (!originMatches(clientData.path("origin").asText(""), relyingPartyId)) {
+ throw new CeremonyException(Failure.ORIGIN, "the origin is not allowed for " + relyingPartyId);
+ }
+ }
+
+ private static void verifyAuthenticatorData(AuthenticatorData authenticatorData, String relyingPartyId,
+ boolean userVerificationRequired) throws CeremonyException {
+ if (!MessageDigest.isEqual(authenticatorData.relyingPartyIdHash(),
+ Digests.sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)))) {
+ throw new CeremonyException(Failure.RELYING_PARTY, "the authenticator data is for another relying party");
+ }
+ if (!authenticatorData.flag(FLAG_USER_PRESENT)) {
+ throw new CeremonyException(Failure.INVALID, "the authenticator did not check for user presence");
+ }
+ if (userVerificationRequired && !authenticatorData.flag(FLAG_USER_VERIFIED)) {
+ throw new CeremonyException(Failure.NOT_SUPPORTED, "the authenticator did not verify the user");
+ }
+ }
+
+ /**
+ * Splits authenticator data: the relying party ID hash, the flags, the signature counter, and the
+ * attested credential data when its flag is set. Extensions after them are not read.
+ */
+ private static AuthenticatorData parseAuthenticatorData(byte[] data) throws CeremonyException {
+ if (data.length < AUTHENTICATOR_DATA_HEADER_LENGTH) {
+ throw new CeremonyException(Failure.MALFORMED, "the authenticator data is too short");
+ }
+ int flags = data[32] & 0xFF;
+ long signCount = ByteBuffer.wrap(data, 33, 4).getInt() & 0xFFFFFFFFL;
+ AttestedCredential attested = (flags & FLAG_ATTESTED_CREDENTIAL_DATA) != 0
+ ? readAttestedCredential(data, AUTHENTICATOR_DATA_HEADER_LENGTH)
+ : null;
+ return new AuthenticatorData(Arrays.copyOfRange(data, 0, 32), flags, signCount, attested);
+ }
+
+ /**
+ * Reads attested credential data starting at {@code offset}: a 16-byte AAGUID, the credential ID
+ * behind its 2-byte length, then the COSE public key, after which extensions may follow.
+ */
+ private static AttestedCredential readAttestedCredential(byte[] data, int offset) throws CeremonyException {
+ int idOffset = offset + 18;
+ if (data.length < idOffset) {
+ throw new CeremonyException(Failure.MALFORMED, "the attested credential data is too short");
+ }
+ int idLength = ((data[offset + 16] & 0xFF) << 8) | (data[offset + 17] & 0xFF);
+ int keyOffset = idOffset + idLength;
+ if (data.length <= keyOffset) {
+ throw new CeremonyException(Failure.MALFORMED, "the attested credential data has no public key");
+ }
+ JsonNode publicKey;
+ int keyLength;
+ try (JsonParser parser = CBOR_MAPPER.createParser(Arrays.copyOfRange(data, keyOffset, data.length))) {
+ publicKey = CBOR_MAPPER.readTree(parser);
+ keyLength = (int) parser.currentLocation().getByteOffset();
+ } catch (IOException e) {
+ throw new CeremonyException(Failure.MALFORMED, "the passkey's public key is not valid CBOR");
+ }
+ if (publicKey == null || !publicKey.isObject()) {
+ throw new CeremonyException(Failure.MALFORMED, "the passkey's public key is not a COSE key");
+ }
+ return new AttestedCredential(Arrays.copyOfRange(data, idOffset, keyOffset), publicKey,
+ Arrays.copyOfRange(data, offset, keyOffset + keyLength));
+ }
+
+ /** The ES256 or RS256 public key a COSE key holds; a key of any other algorithm is not supported. */
+ private static PublicKey publicKey(JsonNode coseKey) throws CeremonyException {
+ int keyType = coseKey.path(COSE_KEY_TYPE).asInt();
+ int algorithm = coseKey.path(COSE_ALGORITHM).asInt();
+ try {
+ if (algorithm == ES256 && keyType == COSE_KEY_TYPE_EC2
+ && coseKey.path(COSE_EC2_CURVE).asInt() == COSE_CURVE_P256) {
+ return PublicKeys.ec("secp256r1", new BigInteger(1, cborBytes(coseKey, COSE_EC2_X)),
+ new BigInteger(1, cborBytes(coseKey, COSE_EC2_Y)));
+ }
+ if (algorithm == RS256 && keyType == COSE_KEY_TYPE_RSA) {
+ return PublicKeys.rsa(new BigInteger(1, cborBytes(coseKey, COSE_RSA_MODULUS)),
+ new BigInteger(1, cborBytes(coseKey, COSE_RSA_EXPONENT)));
+ }
+ } catch (GeneralSecurityException e) {
+ throw new CeremonyException(Failure.MALFORMED, "the passkey's public key is not valid");
+ }
+ throw new CeremonyException(Failure.NOT_SUPPORTED,
+ "COSE algorithm " + algorithm + " is not ES256 (-7) or RS256 (-257)");
+ }
+
+ /** Whether {@code signature} signs the authenticator data followed by the client data hash. */
+ private static boolean signatureMatches(JsonNode coseKey, byte[] authenticatorData, byte[] clientDataHash,
+ byte[] signature) throws CeremonyException {
+ PublicKey key = publicKey(coseKey);
+ String algorithm = coseKey.path(COSE_ALGORITHM).asInt() == ES256 ? "SHA256withECDSA" : "SHA256withRSA";
+ try {
+ Signature verifier = Signature.getInstance(algorithm);
+ verifier.initVerify(key);
+ verifier.update(authenticatorData);
+ verifier.update(clientDataHash);
+ return verifier.verify(signature);
+ } catch (GeneralSecurityException e) {
+ throw new CeremonyException(Failure.INVALID, "the signature is not a valid " + algorithm + " signature");
+ }
+ }
+
+ /**
+ * The relying party ID or a subdomain of it, over HTTPS, or over HTTP for a {@code localhost} page,
+ * the one insecure origin browsers let run WebAuthn ceremonies.
+ */
+ static boolean originMatches(String origin, String relyingPartyId) {
+ URI uri;
+ try {
+ uri = new URI(origin);
+ } catch (URISyntaxException e) {
+ return false;
+ }
+ String host = uri.getHost();
+ if (host == null || !DomainNames.isWithin(host, relyingPartyId)) {
+ return false;
+ }
+ String scheme = uri.getScheme();
+ return "https".equals(scheme)
+ || ("http".equals(scheme) && (host.equals("localhost") || host.endsWith(".localhost")));
+ }
+
+ private static JsonNode decodeCbor(byte[] data, String name) throws CeremonyException {
+ JsonNode node;
+ try {
+ node = CBOR_MAPPER.readTree(data);
+ } catch (IOException e) {
+ throw new CeremonyException(Failure.MALFORMED, name + " is not valid CBOR");
+ }
+ if (node == null || !node.isObject()) {
+ throw new CeremonyException(Failure.MALFORMED, name + " is not a CBOR map");
+ }
+ return node;
+ }
+
+ private static byte[] cborBytes(JsonNode map, String key) throws CeremonyException {
+ JsonNode value = map.path(key);
+ if (!value.isBinary()) {
+ throw new CeremonyException(Failure.MALFORMED, key + " is not a byte string");
+ }
+ try {
+ return value.binaryValue();
+ } catch (IOException e) {
+ throw new CeremonyException(Failure.MALFORMED, key + " is not a byte string");
+ }
+ }
+
+ private static String registrationKey(String poolId, String username) {
+ return poolId + "::" + username;
+ }
+
+ private static byte[] requiredBytes(JsonNode node, String field) {
+ String value = node.path(field).asText(null);
+ if (value == null || value.isEmpty()) {
+ throw new AwsException("InvalidParameterException", "The passkey credential has no " + field, 400);
+ }
+ return decode(value);
+ }
+
+ private static byte[] decode(String base64Url) {
+ try {
+ return Base64.getUrlDecoder().decode(base64Url);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterException", "The passkey credential is not base64url encoded",
+ 400);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java
index 1d91b8936a..4ccae7efb5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cognito;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
@@ -12,7 +13,6 @@ import jakarta.ws.rs.core.Response;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
-import java.util.Base64;
/**
* Exposes Cognito well-known endpoints.
@@ -76,6 +76,6 @@ public class CognitoWellKnownController {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
index 2620777d3c..6f06ef4ab0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
@@ -30,6 +30,8 @@ public class CognitoUser {
private String softwareTokenMfaSecret;
private String pendingSoftwareTokenMfaSecret;
private Integer pendingSoftwareTokenMfaAttemptsRemaining;
+ private List<WebAuthnCredential> webAuthnCredentials = new ArrayList<>();
+ private boolean webAuthnMfaEnabled;
private String federatedProviderName;
private String federatedSubject;
@@ -112,6 +114,15 @@ public class CognitoUser {
this.pendingSoftwareTokenMfaAttemptsRemaining = attempts;
}
+ public List<WebAuthnCredential> getWebAuthnCredentials() { return webAuthnCredentials; }
+ public void setWebAuthnCredentials(List<WebAuthnCredential> webAuthnCredentials) {
+ this.webAuthnCredentials = webAuthnCredentials == null ? new ArrayList<>() : new ArrayList<>(webAuthnCredentials);
+ }
+
+ /** {@code WebAuthnMfaSettings.Enabled}: whether a user-verified passkey sign-in stands in for MFA. */
+ public boolean isWebAuthnMfaEnabled() { return webAuthnMfaEnabled; }
+ public void setWebAuthnMfaEnabled(boolean webAuthnMfaEnabled) { this.webAuthnMfaEnabled = webAuthnMfaEnabled; }
+
public String getFederatedProviderName() {
return federatedProviderName;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
index a1abeb4f06..02c185cbd7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
@@ -38,6 +38,7 @@ public class UserPool {
private String mfaConfiguration = "OFF";
/** Null until SetUserPoolMfaConfig sets it; absent from responses while null, as AWS omits it. */
private Boolean softwareTokenMfaEnabled;
+ private WebAuthnConfiguration webAuthnConfiguration;
private Map<String, Object> deviceConfiguration = new HashMap<>();
private int estimatedNumberOfUsers = 0;
private Map<String, Object> emailConfiguration = new HashMap<>();
@@ -135,6 +136,11 @@ public class UserPool {
}
public void setMfaConfiguration(String mfaConfiguration) { this.mfaConfiguration = mfaConfiguration; }
+ public WebAuthnConfiguration getWebAuthnConfiguration() { return webAuthnConfiguration; }
+ public void setWebAuthnConfiguration(WebAuthnConfiguration webAuthnConfiguration) {
+ this.webAuthnConfiguration = webAuthnConfiguration;
+ }
+
public Map<String, Object> getDeviceConfiguration() { return deviceConfiguration; }
public void setDeviceConfiguration(Map<String, Object> deviceConfiguration) { this.deviceConfiguration = deviceConfiguration; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/WebAuthnConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/WebAuthnConfiguration.java
new file mode 100644
index 0000000000..9a8db8656c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/WebAuthnConfiguration.java
@@ -0,0 +1,23 @@
+package io.github.hectorvent.floci.services.cognito.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/** A user pool's passkey settings, from {@code SetUserPoolMfaConfig}'s {@code WebAuthnConfiguration}. */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class WebAuthnConfiguration {
+
+ private String relyingPartyId;
+ private String userVerification;
+ private String factorConfiguration;
+
+ public String getRelyingPartyId() { return relyingPartyId; }
+ public void setRelyingPartyId(String relyingPartyId) { this.relyingPartyId = relyingPartyId; }
+
+ public String getUserVerification() { return userVerification; }
+ public void setUserVerification(String userVerification) { this.userVerification = userVerification; }
+
+ public String getFactorConfiguration() { return factorConfiguration; }
+ public void setFactorConfiguration(String factorConfiguration) { this.factorConfiguration = factorConfiguration; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/WebAuthnCredential.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/WebAuthnCredential.java
new file mode 100644
index 0000000000..075a4f1c86
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/WebAuthnCredential.java
@@ -0,0 +1,70 @@
+package io.github.hectorvent.floci.services.cognito.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A passkey registered with {@code CompleteWebAuthnRegistration}. {@code attestedCredentialData}
+ * holds the authenticator's credential id and public key in their WebAuthn binary form, base64url
+ * encoded, which is what an assertion is verified against.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class WebAuthnCredential {
+
+ private String credentialId;
+ private String attestedCredentialData;
+ private long signCount;
+ private boolean userVerified;
+ private Boolean backupEligible;
+ private Boolean backupState;
+ private List<String> transports = new ArrayList<>();
+ private String authenticatorAttachment;
+ private String friendlyCredentialName;
+ private String relyingPartyId;
+ private long createdAtMillis;
+
+ public String getCredentialId() { return credentialId; }
+ public void setCredentialId(String credentialId) { this.credentialId = credentialId; }
+
+ public String getAttestedCredentialData() { return attestedCredentialData; }
+ public void setAttestedCredentialData(String attestedCredentialData) {
+ this.attestedCredentialData = attestedCredentialData;
+ }
+
+ public long getSignCount() { return signCount; }
+ public void setSignCount(long signCount) { this.signCount = signCount; }
+
+ public boolean isUserVerified() { return userVerified; }
+ public void setUserVerified(boolean userVerified) { this.userVerified = userVerified; }
+
+ public Boolean getBackupEligible() { return backupEligible; }
+ public void setBackupEligible(Boolean backupEligible) { this.backupEligible = backupEligible; }
+
+ public Boolean getBackupState() { return backupState; }
+ public void setBackupState(Boolean backupState) { this.backupState = backupState; }
+
+ public List<String> getTransports() { return transports; }
+ public void setTransports(List<String> transports) {
+ this.transports = transports == null ? new ArrayList<>() : new ArrayList<>(transports);
+ }
+
+ public String getAuthenticatorAttachment() { return authenticatorAttachment; }
+ public void setAuthenticatorAttachment(String authenticatorAttachment) {
+ this.authenticatorAttachment = authenticatorAttachment;
+ }
+
+ public String getFriendlyCredentialName() { return friendlyCredentialName; }
+ public void setFriendlyCredentialName(String friendlyCredentialName) {
+ this.friendlyCredentialName = friendlyCredentialName;
+ }
+
+ public String getRelyingPartyId() { return relyingPartyId; }
+ public void setRelyingPartyId(String relyingPartyId) { this.relyingPartyId = relyingPartyId; }
+
+ public long getCreatedAtMillis() { return createdAtMillis; }
+ public void setCreatedAtMillis(long createdAtMillis) { this.createdAtMillis = createdAtMillis; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java
index 67b4ff7d9c..01cedcc1cb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cognito.verification;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.ses.SesService;
@@ -203,7 +204,7 @@ public final class CognitoMessageDispatcher {
}
String domain = mailbox.getDomain().toLowerCase(Locale.ROOT);
String identityDomain = identity.toLowerCase(Locale.ROOT);
- return domain.equals(identityDomain) || domain.endsWith("." + identityDomain);
+ return DomainNames.isWithin(domain, identityDomain);
}
/** The identity an SES {@code identity/<name>} ARN names, or {@code null} for anything else. */
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java
index f482e9d93a..30c9d6afd4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java
@@ -1,12 +1,10 @@
package io.github.hectorvent.floci.services.cognito.verification;
import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
@@ -92,7 +90,7 @@ public final class VerificationCodeService {
String code = String.format("%06d", random.nextInt(1_000_000));
String salt = HexFormat.of().formatHex(randomBytes(SALT_BYTES));
- String hash = sha256(code + salt);
+ String hash = Digests.sha256Hex(code + salt);
Instant now = clock.instant();
VerificationCode vc = new VerificationCode(
@@ -150,7 +148,7 @@ public final class VerificationCodeService {
"Invalid verification code provided, please try again");
}
- String expectedHash = sha256(code + vc.getSalt());
+ String expectedHash = Digests.sha256Hex(code + vc.getSalt());
if (!constantTimeEquals(expectedHash, vc.getCodeHash())) {
vc.decrementAttempts();
if (vc.getAttemptsRemaining() <= 0) {
@@ -222,15 +220,6 @@ public final class VerificationCodeService {
return b;
}
- private String sha256(String s) {
- try {
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- return HexFormat.of().formatHex(md.digest(s.getBytes(StandardCharsets.UTF_8)));
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException(e);
- }
- }
-
private boolean constantTimeEquals(String a, String b) {
if (a.length() != b.length()) return false;
int r = 0;
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
index 2d49f87e0d..5d4e9e7323 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
@@ -1733,7 +1734,7 @@ public class DynamoDbService {
return new TransactWriteResult(applyTransactWrite(transactItems, region).writeCapacity(), false);
}
String cacheKey = regionResolver.getAccountId() + "::" + region + "::" + clientRequestToken;
- String requestHash = sha256(rawRequest.toString());
+ String requestHash = Digests.sha256Hex(rawRequest.toString());
for (;;) {
long nowNanos = System.nanoTime();
IdempotencyEntry fresh = new IdempotencyEntry(requestHash, nowNanos, new CompletableFuture<>());
@@ -4662,23 +4663,6 @@ public class DynamoDbService {
}
}
- /**
- * SHA-256 hex digest of a string, used by ClientRequestToken idempotency to compare
- * request bodies. SHA-256 is required (not MD5) for the dedup contract because a
- * collision would allow a request with different parameters to be silently treated
- * as a replay; SHA-256 is supported on every JVM via {@link MessageDigest}.
- */
- private static String sha256(String input) {
- try {
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(digest);
- } catch (NoSuchAlgorithmException e) {
- // SHA-256 is mandated by the JLS to be available on every JVM; this should never trigger.
- throw new IllegalStateException("SHA-256 is required but not available on this JVM", e);
- }
- }
-
private String buildManifestSummary(ExportDescription desc, String exportId,
String dataKey, long itemCount, long billedSize,
String md5, String etag, String manifestSummaryKey) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClient.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClient.java
index bdfdeb7b14..128b9d9b76 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClient.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClient.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb.backend;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
@@ -93,9 +94,9 @@ class DynamoDbLocalClient implements AutoCloseable {
+ "x-amz-date:" + amzDate + "\n"
+ "x-amz-target:" + target + "\n\n"
+ SIGNED_HEADERS + "\n"
- + SigV4RequestValidator.sha256Hex(payload);
+ + Digests.sha256Hex(payload);
String toSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
- + SigV4RequestValidator.sha256Hex(canonical);
+ + Digests.sha256Hex(canonical);
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(SECRET_KEY, date, scope.region(), SERVICE);
String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, toSign));
return "AWS4-HMAC-SHA256 Credential=floci" + scope.accountId() + "/" + credentialScope
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java
index 5558fcb8cd..4a6a94bc16 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ec2;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.SshPublicKeys;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
@@ -108,8 +109,7 @@ public final class Ec2KeyMaterial {
if (reader.readField().length != ED25519_KEY_LENGTH) {
return null;
}
- return Base64.getEncoder().encodeToString(
- MessageDigest.getInstance("SHA-256").digest(blob));
+ return Base64.getEncoder().encodeToString(Digests.sha256(blob));
}
// EC2 documents its ssh-rsa fingerprint as the MD5 of the DER, which is not the
// OpenSSH fingerprint of the same key. SshPublicKeys keeps the two apart on purpose.
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java
index 1a6fd0efee..2fd6b15e06 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
@@ -2402,8 +2403,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
int end = Math.min(offset + pageSize, arns.size());
String token = end < arns.size()
- ? Base64.getUrlEncoder().withoutPadding()
- .encodeToString(String.valueOf(end).getBytes(StandardCharsets.UTF_8))
+ ? Base64Url.encode(String.valueOf(end))
: null;
return new ListPage(List.copyOf(arns.subList(offset, end)), token);
}
@@ -3215,8 +3215,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
int end = Math.min(offset + pageSize, filtered.size());
String token = end < filtered.size()
- ? Base64.getUrlEncoder().withoutPadding()
- .encodeToString(String.valueOf(end).getBytes(StandardCharsets.UTF_8))
+ ? Base64Url.encode(String.valueOf(end))
: null;
return new AccountSettingPage(List.copyOf(filtered.subList(offset, end)), token);
}
@@ -3378,8 +3377,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
int end = Math.min(offset + pageSize, matches.size());
String token = end < matches.size()
- ? Base64.getUrlEncoder().withoutPadding()
- .encodeToString(String.valueOf(end).getBytes(StandardCharsets.UTF_8))
+ ? Base64Url.encode(String.valueOf(end))
: null;
return new ListAttributesPage(List.copyOf(matches.subList(offset, end)), token);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
index 43ee68224c..7eba3b4e75 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
@@ -14,6 +14,7 @@ import com.github.dockerjava.api.model.Statistics;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
@@ -68,14 +69,11 @@ import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashSet;
-import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -2202,13 +2200,13 @@ public class EcsContainerManager {
*/
static String efsVolumeToken(String fileSystemId, String accessPointId, String rootDirectory) {
if (accessPointId != null && !accessPointId.isBlank()) {
- return "efs-" + fileSystemId + "-" + sha256Hex("accessPoint:" + accessPointId);
+ return "efs-" + fileSystemId + "-" + Digests.sha256Hex("accessPoint:" + accessPointId);
}
String normalizedRoot = normalizeRootDirectory(rootDirectory);
if ("/".equals(normalizedRoot)) {
return "efs-" + fileSystemId;
}
- return "efs-" + fileSystemId + "-" + sha256Hex(normalizedRoot);
+ return "efs-" + fileSystemId + "-" + Digests.sha256Hex(normalizedRoot);
}
/**
@@ -2244,15 +2242,6 @@ public class EcsContainerManager {
return collapsed.startsWith("/") ? collapsed : "/" + collapsed;
}
- private static String sha256Hex(String value) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(digest);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is required but not available", e);
- }
- }
-
// Inner enum to avoid import cycle — mirrors model.TaskStatus for readability
private enum TaskStatus {RUNNING}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessage.java b/src/main/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessage.java
index de57803602..81729ab4ff 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessage.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessage.java
@@ -1,9 +1,9 @@
package io.github.hectorvent.floci.services.ecs.exec;
+import io.github.hectorvent.floci.core.common.Digests;
+
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;
@@ -79,7 +79,7 @@ public record AgentMessage(
buffer.putLong(flags);
buffer.putLong(messageId.getLeastSignificantBits());
buffer.putLong(messageId.getMostSignificantBits());
- buffer.put(sha256(body));
+ buffer.put(Digests.sha256(body));
buffer.putInt(payloadType);
buffer.putInt(body.length);
buffer.put(body);
@@ -125,12 +125,4 @@ public record AgentMessage(
System.arraycopy(raw, 0, padded, 0, Math.min(raw.length, MESSAGE_TYPE_LENGTH));
return padded;
}
-
- private static byte[] sha256(byte[] input) {
- try {
- return MessageDigest.getInstance("SHA-256").digest(input);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is required to frame a Session Manager message", e);
- }
- }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/exec/EcsExecSessionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/ecs/exec/EcsExecSessionRegistry.java
index 245fdfc7b2..a6af54f044 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/exec/EcsExecSessionRegistry.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/exec/EcsExecSessionRegistry.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ecs.exec;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Resettable;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -11,7 +12,6 @@ import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
-import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -58,7 +58,7 @@ public class EcsExecSessionRegistry implements Resettable {
byte[] token = new byte[32];
RANDOM.nextBytes(token);
ExecSession session = new ExecSession(sessionId,
- Base64.getUrlEncoder().withoutPadding().encodeToString(token),
+ Base64Url.encode(token),
taskArn, clusterArn, containerName, containerArn, runtimeId, command, interactive,
clock.instant());
sessions.put(sessionId, session);
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java
index 642e88f982..b956bc7be4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksAccessEntryService.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -181,8 +182,7 @@ public class EksAccessEntryService {
.map(stored -> stored.entry().principalArn()).filter(principal -> principal.compareTo(cursor) > 0)
.sorted(Comparator.naturalOrder()).toList();
List<String> page = remaining.stream().limit(limit).toList();
- String token = remaining.size() > limit ? Base64.getUrlEncoder().withoutPadding().encodeToString(
- (prefix + "\n" + page.getLast()).getBytes(StandardCharsets.UTF_8)) : null;
+ String token = remaining.size() > limit ? Base64Url.encode(prefix + "\n" + page.getLast()) : null;
return new Page(page, token);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java
index d87cbc196f..30477c3919 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsEndpoints;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -179,8 +180,8 @@ public class EksOidcService implements OidcIssuerKeyLookup {
long exp = now + lifetime;
String subject = "system:serviceaccount:" + namespace + ":" + serviceAccount;
- String header = base64Url(writeJson(buildHeader(key.getKeyId())));
- String payload = base64Url(writeJson(
+ String header = Base64Url.encode(writeJson(buildHeader(key.getKeyId())));
+ String payload = Base64Url.encode(writeJson(
buildClaims(issuer, aud, subject, namespace, serviceAccount, now, exp)));
String signingInput = header + "." + payload;
@@ -236,7 +237,7 @@ public class EksOidcService implements OidcIssuerKeyLookup {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- return base64Url(signature.sign());
+ return Base64Url.encode(signature.sign());
} catch (GeneralSecurityException e) {
throw new IllegalStateException("EKS OIDC token signing failed", e);
}
@@ -260,10 +261,6 @@ public class EksOidcService implements OidcIssuerKeyLookup {
}
}
- private static String base64Url(byte[] data) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(data);
- }
-
/**
* Exports the cluster's RSA signing key in PKCS#8 PEM format for the k3s API server's
* {@code --service-account-signing-key-file} argument.
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java
index 0f42b25660..39f504d37a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcWellKnownController.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;
import jakarta.enterprise.context.ApplicationScoped;
@@ -15,7 +16,7 @@ import jakarta.ws.rs.core.Response;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
-import java.util.Base64;
+import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -109,8 +110,8 @@ public class EksOidcWellKnownController {
private String base64UrlEncodeUnsigned(BigInteger value) {
byte[] bytes = value.toByteArray();
if (bytes.length > 1 && bytes[0] == 0) {
- bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
+ bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java
index 62b9a19c49..5c78db78dd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -272,8 +273,7 @@ public class EksPodIdentityAssociationService {
.toList();
String token = remaining.size() > limit
- ? Base64.getUrlEncoder().withoutPadding().encodeToString(
- (prefix + "\n" + page.getLast().associationId()).getBytes(StandardCharsets.UTF_8))
+ ? Base64Url.encode(prefix + "\n" + page.getLast().associationId())
: null;
return new Page(page, token);
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java
index 93376e3c7c..b424036962 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksTokenValidator.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.eks;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -95,7 +96,7 @@ class EksTokenValidator {
String stringToSign = ALGORITHM + "\n"
+ parameters.get("X-Amz-Date") + "\n"
+ scope.value() + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
String expectedSignature = hexEncode(hmacSha256(
deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()), stringToSign));
boolean valid = MessageDigest.isEqual(
@@ -231,10 +232,6 @@ class EksTokenValidator {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
- private static String sha256Hex(String input) throws Exception {
- return hexEncode(MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8)));
- }
-
private static String hexEncode(byte[] bytes) {
StringBuilder encoded = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/FisService.java b/src/main/java/io/github/hectorvent/floci/services/fis/FisService.java
index 88d842ca1e..885a84acdd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/fis/FisService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/fis/FisService.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.TagHandler;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -1300,7 +1301,7 @@ public class FisService implements TagHandler {
private String encodeToken(String scope, String cursor) {
String raw = scope + "\n" + cursor;
- return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(raw);
}
private String decodeToken(String token, String expectedScope) {
@@ -1712,8 +1713,7 @@ public class FisService implements TagHandler {
}
private String idempotencyKey(String region, String operation, String token) {
- String encoded = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(token.getBytes(StandardCharsets.UTF_8));
+ String encoded = Base64Url.encode(token);
return key(region, "idempotency", operation + "::" + encoded);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java
index ce4134ca55..49d47ed6ee 100644
--- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -1272,7 +1273,7 @@ public class GlueService {
}
private static String encodePartitionValue(String value) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(value);
}
private static String partitionColumnStatisticsKey(
diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/schemaregistry/GlueSchemaRegistryService.java b/src/main/java/io/github/hectorvent/floci/services/glue/schemaregistry/GlueSchemaRegistryService.java
index 8e6a5d48fa..0c956fa533 100644
--- a/src/main/java/io/github/hectorvent/floci/services/glue/schemaregistry/GlueSchemaRegistryService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/glue/schemaregistry/GlueSchemaRegistryService.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.glue.schemaregistry;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -16,13 +17,9 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
@@ -984,16 +981,7 @@ public class GlueSchemaRegistryService {
} catch (RuntimeException e) {
canonical = definition;
}
- return sha256Hex(canonical);
- }
-
- private static String sha256Hex(String input) {
- try {
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- return HexFormat.of().formatHex(md.digest(input.getBytes(StandardCharsets.UTF_8)));
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 not available", e);
- }
+ return Digests.sha256Hex(canonical);
}
private Registry autoCreateDefaultRegistry(String region) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java
index e19e70568c..1a66494ddc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -634,8 +635,7 @@ public class GuardDutyService {
}
private static String encodeOffset(int offset) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString((TOKEN_PREFIX + offset).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(TOKEN_PREFIX + offset);
}
private static AwsException detectorNotFound() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/identitystore/ScimController.java b/src/main/java/io/github/hectorvent/floci/services/identitystore/ScimController.java
index 0cba2baa95..c45e0f2c04 100644
--- a/src/main/java/io/github/hectorvent/floci/services/identitystore/ScimController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/identitystore/ScimController.java
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.identitystore.model.Group;
import io.github.hectorvent.floci.services.identitystore.model.Membership;
import io.github.hectorvent.floci.services.identitystore.model.User;
@@ -1363,8 +1364,7 @@ public class ScimController {
private static String encodeCursor(int offset, String filter) {
String fingerprint = filter == null ? "" : filter;
- return Base64.getUrlEncoder().withoutPadding().encodeToString(
- (offset + "\n" + fingerprint).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(offset + "\n" + fingerprint);
}
private static int decodeCursor(String cursor, String filter) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingService.java
index 659b1e6284..a57fbd0d83 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingService.java
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration;
@@ -267,8 +268,7 @@ public class IotFleetIndexingService {
}
private static String pageToken(String parameters, String thingName) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(
- (parameters + pageCheck(parameters, thingName) + thingName).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(parameters + pageCheck(parameters, thingName) + thingName);
}
/** A checksum of a token's parameters and cursor, so an edited or truncated token is invalid, as on AWS. */
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
index a3c0cc0516..53c5c1dd03 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -51,8 +52,6 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.time.Clock;
@@ -62,7 +61,6 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashSet;
-import java.util.HexFormat;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -403,8 +401,8 @@ public class IotService {
}
/** AWS IoT's certificateId is the lowercase hex SHA-256 of the certificate's DER encoding. */
- private static String certificateIdOf(X509Certificate x509) throws CertificateEncodingException, NoSuchAlgorithmException {
- return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(x509.getEncoded()));
+ private static String certificateIdOf(X509Certificate x509) throws CertificateEncodingException {
+ return Digests.sha256Hex(x509.getEncoded());
}
public IotCertificate describeCertificate(String certificateId, String region) {
@@ -457,7 +455,7 @@ public class IotService {
String certificateId;
try {
certificateId = certificateIdOf(presented);
- } catch (CertificateEncodingException | NoSuchAlgorithmException e) {
+ } catch (CertificateEncodingException e) {
LOG.debugv("Could not fingerprint the presented device certificate: {0}", e.getMessage());
return Optional.empty();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java
index 807ff1537d..96e6ae8aac 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsEventStreamEncoder;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.kinesis.model.KinesisConsumer;
import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
@@ -765,8 +766,7 @@ public class KinesisJsonHandler {
*/
static String encodeShardToken(String streamName, String lastShardId, long issuedAtEpochMilli) {
String raw = streamName + "|" + lastShardId + "|" + issuedAtEpochMilli;
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(raw.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(raw);
}
ShardToken decodeShardToken(String nextToken) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java
index d52f3055b4..094efb3d07 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
@@ -510,7 +511,7 @@ public class KmsService implements ResourceProvider {
KmsGrant grant = new KmsGrant();
grant.setGrantId(grantId);
- grant.setGrantToken(Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes));
+ grant.setGrantToken(Base64Url.encode(tokenBytes));
grant.setName(name);
grant.setKeyId(key.getKeyId());
grant.setKeyArn(key.getArn());
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
index b8998f16bd..7dfa7a6428 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -31,14 +32,10 @@ import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
@@ -894,13 +891,7 @@ public class LambdaController {
* perpetual diff in anything that records it.
*/
private static String runtimeVersionId(String runtime) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(runtime.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(digest);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 unavailable", e);
- }
+ return Digests.sha256Hex(runtime);
}
private static List<String> stringList(Map<String, Object> config, String key) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java
index 3c69485a1d..e19a0dbe80 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
@@ -21,7 +23,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -360,8 +361,7 @@ public class LambdaLayerService {
*/
private static String encodeMarker(String cursor) {
String signed = cursor + MARKER_SEPARATOR + sign(cursor);
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(signed.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(signed);
}
private static String decodeMarker(String marker) {
@@ -390,8 +390,7 @@ public class LambdaLayerService {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(MARKER_KEY, "HmacSHA256"));
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(mac.doFinal(cursor.getBytes(StandardCharsets.UTF_8)));
+ return Base64Url.encode(mac.doFinal(cursor.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("HmacSHA256 is required to paginate layers", e);
}
@@ -594,12 +593,7 @@ public class LambdaLayerService {
}
private String computeSha256(byte[] data) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(data);
- return Base64.getEncoder().encodeToString(digest);
- } catch (NoSuchAlgorithmException e) {
- return "";
- }
+ return Base64.getEncoder().encodeToString(Digests.sha256(data));
}
private void deleteDirectory(Path dir) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index bc84a7c8b7..7215086605 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
@@ -3389,11 +3390,7 @@ public class LambdaService implements ResourceProvider {
// deploy move $LATEST between those two steps, so a version would carry code whose hash
// the caller never authorised even though the check passed. Extraction to disk stays
// outside the lock; only the fields that decide what a snapshot copies are inside it.
- String newSha256 = null;
- try {
- byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(zipBytes);
- newSha256 = Base64.getEncoder().encodeToString(digest);
- } catch (java.security.NoSuchAlgorithmException ignored) {}
+ String newSha256 = Base64.getEncoder().encodeToString(Digests.sha256(zipBytes));
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
fn.setCodeLocalPath(codePath.toAbsolutePath().normalize().toString());
fn.setCodeSizeBytes(zipBytes.length);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
index accb5c0971..4db129b97c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
@@ -35,17 +36,13 @@ import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
-import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -1166,7 +1163,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
private static String namespaceDisambiguator(EmulatorConfig config) {
String namespace = config.docker() == null || config.docker().resourceNamespace() == null
? "" : config.docker().resourceNamespace().orElse("").trim();
- return namespace.isEmpty() ? "" : "-" + sha256Hex(namespace).substring(0, 12);
+ return namespace.isEmpty() ? "" : "-" + Digests.sha256Hex(namespace).substring(0, 12);
}
/** Leading part shared by every code volume (and completion marker) this configuration names. */
@@ -1200,7 +1197,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
if (resourceId.isBlank()) {
throw new IllegalArgumentException("File system access point ARN must include a resource id");
}
- return "efs-" + resourceId + "-" + sha256Hex(accessPointArn);
+ return "efs-" + resourceId + "-" + Digests.sha256Hex(accessPointArn);
}
/**
@@ -1219,16 +1216,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
return ContainerStorageHelper.dockerName(config, token);
}
- private static String sha256Hex(String value) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(value.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(digest);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is required but not available", e);
- }
- }
-
@FunctionalInterface
interface DirectoryTarWriter {
void write(Path sourceDir, OutputStream out) throws IOException;
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java
index 470399d145..9fc875cd93 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -10,12 +12,10 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
-import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
@@ -294,13 +294,12 @@ final class EksTokenMinter {
+ canonicalHeaders + "\n" + signedHeaders + "\n" + EMPTY_BODY_SHA256;
String stringToSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(credentials.secretAccessKey(), dateStamp, region, "sts");
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
String url = "https://" + host + "/?" + canonicalQueryString + "&X-Amz-Signature=" + signature;
- return TOKEN_PREFIX + Base64.getUrlEncoder().withoutPadding()
- .encodeToString(url.getBytes(StandardCharsets.UTF_8));
+ return TOKEN_PREFIX + Base64Url.encode(url);
}
record AwsCredentials(String accessKeyId, String secretAccessKey, String sessionToken) {
@@ -461,15 +460,6 @@ final class EksTokenMinter {
}
}
- private static String sha256Hex(String input) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
- } catch (GeneralSecurityException e) {
- throw new IllegalStateException("Could not compute SHA-256: " + e.getMessage(), e);
- }
- }
-
private static String hexEncode(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java
index ee834c0535..b180eb0aab 100644
--- a/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/macie2/MacieService.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.macie2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -206,8 +207,7 @@ public class MacieService implements Resettable {
}
private static String encodeOffset(int offset) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(Integer.toString(offset).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(Integer.toString(offset));
}
private static String memberKey(String region, String accountId) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java
index f70bb3575a..3de7eafc02 100644
--- a/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/marketplace/MarketplaceMeteringService.java
@@ -7,6 +7,8 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -18,7 +20,6 @@ import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
-import java.security.MessageDigest;
import java.security.Signature;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
@@ -27,8 +28,8 @@ import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
-import java.util.Base64;
import java.util.HashSet;
+import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -157,7 +158,7 @@ public class MarketplaceMeteringService implements Resettable {
}
String productIdentity = licenseArn != null ? licenseArn : requestProduct;
String customerIdentity = customerAccount != null ? customerAccount : customerId;
- String key = region + "/batch/" + digest(productIdentity + "|" + customerIdentity + "|" + dimension + "|"
+ String key = region + "/batch/" + Digests.sha256Hex(productIdentity + "|" + customerIdentity + "|" + dimension + "|"
+ timestamp.truncatedTo(ChronoUnit.HOURS));
JsonNode prior = meterRecords.get(key).orElse(null);
String status = "Success";
@@ -201,10 +202,10 @@ public class MarketplaceMeteringService implements Resettable {
if (nonce != null) {
payload.put("Nonce", nonce);
}
- String encodedHeader = base64Url(header.toString());
- String encodedPayload = base64Url(payload.toString());
+ String encodedHeader = Base64Url.encode(header.toString());
+ String encodedPayload = Base64Url.encode(payload.toString());
String signingInput = encodedHeader + "." + encodedPayload;
- String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(signPs256(signingInput));
+ String signature = Base64Url.encode(signPs256(signingInput));
ObjectNode response = mapper.createObjectNode();
response.put("Signature", signingInput + "." + signature);
return response;
@@ -221,14 +222,14 @@ public class MarketplaceMeteringService implements Resettable {
return (ObjectNode) existing.deepCopy();
}
- byte[] hash = sha256(token);
+ byte[] hash = Digests.sha256(token.getBytes(StandardCharsets.UTF_8));
long number = 0;
for (int i = 0; i < 6; i++) {
number = (number << 8) | (hash[i] & 0xffL);
}
String customerAccount = String.format(Locale.ROOT, "%012d", number % 1_000_000_000_000L);
String productCode = localProductCode(region);
- String licenseId = toHex(hash).substring(0, 24);
+ String licenseId = HexFormat.of().formatHex(hash).substring(0, 24);
ObjectNode response = mapper.createObjectNode();
response.put("ProductCode", productCode);
response.put("CustomerAWSAccountId", customerAccount);
@@ -412,10 +413,5 @@ public class MarketplaceMeteringService implements Resettable {
}
}
- private static byte[] sha256(String value) { try { return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new IllegalStateException(e); } }
- private static String digest(String value) { return toHex(sha256(value)); }
- private static String base64Url(String value) { return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8)); }
- private static String toHex(byte[] bytes) { StringBuilder out=new StringBuilder(); for(byte b:bytes) out.append(String.format(Locale.ROOT,"%02x",b)); return out.toString(); }
-
@Override public void clear() { meterRecords.clear(); clientTokens.clear(); customerMappings.clear(); }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java
index 0e782c7168..57feaf107d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
@@ -708,7 +709,7 @@ public class MwaaEnvironmentManager {
private static String generateSecret(int bytes) {
byte[] buf = new byte[bytes];
new SecureRandom().nextBytes(buf);
- return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
+ return Base64Url.encode(buf);
}
/** A Fernet key must be 32 url-safe base64-encoded bytes (Airflow's {@code AIRFLOW__CORE__FERNET_KEY}). */
diff --git a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java
index 9f65cfead8..f39a721708 100644
--- a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.TagHandler;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
@@ -25,7 +26,6 @@ import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Instant;
-import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -417,7 +417,7 @@ public class MwaaService implements TagHandler {
private static String generateToken() {
byte[] buf = new byte[24];
new SecureRandom().nextBytes(buf);
- return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
+ return Base64Url.encode(buf);
}
@Override
diff --git a/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java b/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java
index e51ef21aa0..23f1c8bc63 100644
--- a/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallService.java
@@ -7,16 +7,13 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -806,13 +803,7 @@ public class NetworkFirewallService {
}
static String deterministicHex(String value, int length) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(value.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(digest).substring(0, length);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 unavailable", e);
- }
+ return Digests.sha256Hex(value).substring(0, length);
}
/** @see #associateSubnets for why this is synchronized. */
diff --git a/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java b/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java
index a6d17b8f3e..be2fd7a06d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/oam/OamService.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -374,7 +375,7 @@ public class OamService {
}
public static String encodeToken(int offset) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(String.valueOf(offset).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(String.valueOf(offset));
}
public static int decodeToken(String token) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java b/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java
index b706c537ba..33041bc0cf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.pipes;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -17,12 +18,8 @@ import org.jboss.logging.Logger;
import java.net.HttpURLConnection;
import java.net.URI;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Arrays;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -207,13 +204,7 @@ class KarapaceManager {
}
private static String targetKey(String bootstrapServers) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- byte[] hash = digest.digest(bootstrapServers.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(hash, 0, 8);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is not available", e);
- }
+ return Digests.sha256Hex(bootstrapServers).substring(0, 16);
}
@PreDestroy
diff --git a/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java b/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java
index ec36012e2a..47805b6f5d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -367,8 +368,7 @@ public class PricingService {
}
private static String encodeToken(int offset) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(Integer.toString(offset).getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ return Base64Url.encode(Integer.toString(offset));
}
private static int decodeToken(String token) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
index d15a2edba9..498c29c883 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.rds.proxy;
+import io.github.hectorvent.floci.core.common.Digests;
import org.jboss.logging.Logger;
import javax.crypto.Mac;
@@ -710,7 +711,7 @@ public class PostgresProtocolHandler {
byte[] saltedPassword = pbkdf2HmacSha256(password, salt, iterations);
byte[] clientKey = hmacSha256(saltedPassword, "Client Key");
- byte[] storedKey = sha256(clientKey);
+ byte[] storedKey = Digests.sha256(clientKey);
byte[] clientSignature = hmacSha256(storedKey, authMessage.getBytes(StandardCharsets.UTF_8));
byte[] clientProof = xor(clientKey, clientSignature);
@@ -777,14 +778,6 @@ public class PostgresProtocolHandler {
}
}
- private static byte[] sha256(byte[] data) {
- try {
- return MessageDigest.getInstance("SHA-256").digest(data);
- } catch (Exception e) {
- throw new RuntimeException("SHA-256 failed", e);
- }
- }
-
private static byte[] xor(byte[] a, byte[] b) {
byte[] result = new byte[a.length];
for (int i = 0; i < a.length; i++) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java
index 6c4b61b6a0..45c291fb1a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
@@ -23,9 +24,6 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -220,7 +218,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
}
ObjectNode record = objectMapper.createObjectNode()
- .put("eventID", "backfill#" + integration.getIntegrationArn() + "#" + sha256Hex(keys.toString()))
+ .put("eventID", "backfill#" + integration.getIntegrationArn() + "#" + Digests.sha256Hex(keys.toString()))
.put("eventName", "INSERT");
ObjectNode dynamodb = record.putObject("dynamodb").put("SequenceNumber", "backfill");
dynamodb.set("Keys", keys);
@@ -254,19 +252,6 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
}
- private static String sha256Hex(String value) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
- StringBuilder sb = new StringBuilder(digest.length * 2);
- for (byte b : digest) {
- sb.append(String.format("%02x", b));
- }
- return sb.toString();
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is not available", e);
- }
- }
-
/**
* Waits for the poll in progress, then keeps every poll from writing until {@link #afterReset()},
* and a poll submitted before that from writing at all.
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java
index 39eddc4569..64ff79c87d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.glue.GlueService;
@@ -22,14 +23,10 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -573,11 +570,7 @@ public class ExternalTableMaterializer {
for (S3Object object : objects) {
value.append(object.getKey()).append(':').append(object.getSize()).append(':').append(object.getETag()).append(';');
}
- try {
- return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.toString().getBytes(StandardCharsets.UTF_8)));
- } catch (NoSuchAlgorithmException exception) {
- throw new IllegalStateException("SHA-256 is not available", exception);
- }
+ return Digests.sha256Hex(value.toString());
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java
index 4316779c2f..1ac74c648f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java
+++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.core.common.dns.DnsLookupHelper;
import io.github.hectorvent.floci.core.common.dns.DnsRecordSource;
@@ -188,7 +189,7 @@ public class Route53DnsRecordSource implements DnsRecordSource {
String lower = name.toLowerCase();
for (String suffix : flociSuffixes) {
String s = suffix.toLowerCase();
- if (lower.equals(s) || lower.endsWith("." + s)) {
+ if (DomainNames.isWithin(lower, s)) {
return true;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java
index 36a16a4202..d11291b29f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.route53;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -602,7 +603,7 @@ public class Route53Service implements Resettable {
}
String normalizedQname = normalizeName(qname).toLowerCase();
if (privateZoneNameCounts.isEmpty()
- || privateZoneNameCounts.keySet().stream().noneMatch(z -> normalizedQname.equals(z) || normalizedQname.endsWith("." + z))) {
+ || privateZoneNameCounts.keySet().stream().noneMatch(z -> DomainNames.isWithin(normalizedQname, z))) {
return false;
}
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
@@ -611,7 +612,7 @@ public class Route53Service implements Resettable {
continue;
}
String zoneName = normalizeName(zone.getName()).toLowerCase();
- if (normalizedQname.equals(zoneName) || normalizedQname.endsWith("." + zoneName)) {
+ if (DomainNames.isWithin(normalizedQname, zoneName)) {
return true;
}
}
@@ -696,7 +697,7 @@ public class Route53Service implements Resettable {
/** The private zones with the longest name containing {@code normalizedQname}, so a parent zone never answers for a child. */
private List<OwnedZone> mostSpecificPrivateZones(String normalizedQname) {
if (privateZoneNameCounts.isEmpty()
- || privateZoneNameCounts.keySet().stream().noneMatch(z -> normalizedQname.equals(z) || normalizedQname.endsWith("." + z))) {
+ || privateZoneNameCounts.keySet().stream().noneMatch(z -> DomainNames.isWithin(normalizedQname, z))) {
return List.of();
}
List<OwnedZone> matchingZones = new ArrayList<>();
@@ -707,7 +708,7 @@ public class Route53Service implements Resettable {
continue;
}
String zoneName = normalizeName(zone.getName()).toLowerCase();
- if (!normalizedQname.equals(zoneName) && !normalizedQname.endsWith("." + zoneName)) {
+ if (!DomainNames.isWithin(normalizedQname, zoneName)) {
continue;
}
if (zoneName.length() > maxZoneLength) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java
index ef737808ad..c122354ffa 100644
--- a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java
@@ -8,20 +8,17 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -641,11 +638,6 @@ public class Route53ResolverService {
}
private static String deterministicHex(String seed, int length) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(seed.getBytes(StandardCharsets.UTF_8));
- return HexFormat.of().formatHex(digest).substring(0, length);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 unavailable", e);
- }
+ return Digests.sha256Hex(seed).substring(0, length);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java b/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java
index 382399acc1..ee447ba48a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -501,8 +502,7 @@ public class RumService implements ResourceProvider {
}
private static String encodeOffset(int offset) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString((TOKEN_PREFIX + offset).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(TOKEN_PREFIX + offset);
}
private static AwsException resourceConflict(String name) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java
index f8c967ddb7..f18166a490 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlGenerator.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.iam.IamService;
@@ -24,7 +25,6 @@ import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
-import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -309,7 +309,7 @@ public class PreSignedUrlGenerator {
private String randomUrlSafeValue(int byteCount) {
byte[] bytes = new byte[byteCount];
random.nextBytes(bytes);
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
private static String awsUriEncodePath(String value) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
index 7e759a7b6b..46b24ee608 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
@@ -233,7 +234,7 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ scopeDate + "/" + region + "/" + SIGNING_SERVICE + "/" + TERMINATOR + "\n"
- + SigV4RequestValidator.sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scopeDate, region, SIGNING_SERVICE);
String expected = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
return MessageDigest.isEqual(
@@ -270,14 +271,10 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
private static boolean bodyMatches(ContainerRequestContext ctx, String declaredHash) throws IOException {
byte[] body = ctx.getEntityStream() != null ? ctx.getEntityStream().readAllBytes() : new byte[0];
ctx.setEntityStream(new ByteArrayInputStream(body));
- try {
- String actual = SigV4RequestValidator.hexEncode(MessageDigest.getInstance("SHA-256").digest(body));
- return MessageDigest.isEqual(
- actual.getBytes(StandardCharsets.UTF_8),
- declaredHash.toLowerCase().getBytes(StandardCharsets.UTF_8));
- } catch (java.security.NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is required by SigV4", e);
- }
+ String actual = SigV4RequestValidator.hexEncode(Digests.sha256(body));
+ return MessageDigest.isEqual(
+ actual.getBytes(StandardCharsets.UTF_8),
+ declaredHash.toLowerCase().getBytes(StandardCharsets.UTF_8));
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java
index 6205348168..575c755b4f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java
@@ -1,6 +1,6 @@
package io.github.hectorvent.floci.services.s3;
-import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
+import io.github.hectorvent.floci.core.common.Digests;
import java.util.function.Function;
@@ -24,6 +24,6 @@ final class S3PresignedCanonicalRequest {
static String stringToSign(String amzDate, String credentialScope, String canonicalRequest) throws Exception {
return "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
- + SigV4RequestValidator.sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
index 7dfe9dccfa..bcde48e784 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
@@ -3024,8 +3026,7 @@ public class S3Service implements Resettable, ResourceProvider {
}
private String encodeAnnotationContinuationToken(String lastAnnotationName) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(lastAnnotationName.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(lastAnnotationName);
}
private String decodeAnnotationContinuationToken(String token) {
@@ -3054,22 +3055,8 @@ public class S3Service implements Resettable, ResourceProvider {
// collision-free across object keys that contain '#v#', '@', or path-like characters.
// Cleanup is metadata-driven, so the mapping never needs to be reversed.
// Every path component below bucketDir is SHA-256 hex, so no traversal is possible.
- Path parentDir = bucketDir.resolve(sha256Hex(annotationIdentity(key, versionId)));
- return parentDir.resolve(sha256Hex(annotationName) + ANNOTATION_DATA_SUFFIX);
- }
-
- private static String sha256Hex(String value) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(value.getBytes(StandardCharsets.UTF_8));
- StringBuilder sb = new StringBuilder(digest.length * 2);
- for (byte b : digest) {
- sb.append(String.format("%02x", b));
- }
- return sb.toString();
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 algorithm is not available", e);
- }
+ Path parentDir = bucketDir.resolve(Digests.sha256Hex(annotationIdentity(key, versionId)));
+ return parentDir.resolve(Digests.sha256Hex(annotationName) + ANNOTATION_DATA_SUFFIX);
}
private void writeAnnotationPayload(ObjectAnnotation annotation, byte[] payload) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java
index 4eb4bfac57..34398d4ac8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -185,8 +186,7 @@ public class ServiceQuotasService {
}
private static String encodeToken(int offset) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(Integer.toString(offset).getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(Integer.toString(offset));
}
private static int decodeToken(String token) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.java
index a07e4a6229..2bd6d33d7e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityCertificateService.java
@@ -4,8 +4,10 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.CertificateMaterialException;
+import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pem;
+import io.github.hectorvent.floci.core.common.PublicKeys;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.acm.AcmService;
@@ -16,14 +18,12 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
-import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.time.Clock;
import java.time.Instant;
@@ -269,9 +269,7 @@ public class SesIdentityCertificateService {
private static ECParameterSpec namedCurve(String name) {
try {
- AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
- parameters.init(new ECGenParameterSpec(name));
- return parameters.getParameterSpec(ECParameterSpec.class);
+ return PublicKeys.namedCurve(name);
} catch (GeneralSecurityException e) {
LOG.warnv(e, "EC curve {0} is unavailable, so no key on it counts as a signing key", name);
return null;
@@ -322,7 +320,7 @@ public class SesIdentityCertificateService {
if (domain) {
String addressDomain = fromAddress.substring(at + 1).toLowerCase(Locale.ROOT);
String identityDomain = emailIdentity.toLowerCase(Locale.ROOT);
- if (!addressDomain.equals(identityDomain) && !addressDomain.endsWith("." + identityDomain)) {
+ if (!DomainNames.isWithin(addressDomain, identityDomain)) {
throw badRequest("FromAddress <" + fromAddress + "> does not belong to the domain identity <"
+ emailIdentity + ">.");
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java
index ffb181eddd..e428c4842d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.signin;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
@@ -13,12 +15,10 @@ import jakarta.inject.Inject;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
-import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@@ -291,20 +291,13 @@ public class SigninService {
}
private String encodeJson(Map<String, ?> value) throws JsonProcessingException {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(objectMapper.writeValueAsBytes(value));
+ return Base64Url.encode(objectMapper.writeValueAsBytes(value));
}
private static boolean matchesPkce(String challenge, String verifier) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(verifier.getBytes(StandardCharsets.US_ASCII));
- String calculated = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
- return MessageDigest.isEqual(calculated.getBytes(StandardCharsets.US_ASCII),
- challenge.getBytes(StandardCharsets.US_ASCII));
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is required by the AWS Sign-In protocol", e);
- }
+ String calculated = Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
+ return MessageDigest.isEqual(calculated.getBytes(StandardCharsets.US_ASCII),
+ challenge.getBytes(StandardCharsets.US_ASCII));
}
private static void validateClient(String clientId) {
@@ -481,7 +474,7 @@ public class SigninService {
private String randomToken(int bytes) {
byte[] value = new byte[bytes];
random.nextBytes(value);
- return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
+ return Base64Url.encode(value);
}
private String randomAlphaNumeric(int length) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsMessageSigner.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsMessageSigner.java
index c77fdea912..3664687627 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsMessageSigner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsMessageSigner.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -19,12 +20,10 @@ import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
-import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Base64;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -210,8 +209,7 @@ public class SnsMessageSigner implements Resettable {
private static String fingerprint(X509Certificate certificate) {
try {
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded());
- return HexFormat.of().formatHex(digest, 0, 16);
+ return Digests.sha256Hex(certificate.getEncoded()).substring(0, 32);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Cannot fingerprint the SNS signing certificate", e);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
index c75379717e..57caf7c2d0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
@@ -45,8 +46,6 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
@@ -729,7 +728,7 @@ public class SnsService implements Resettable, ResourceProvider {
"MessageGroupId is required for FIFO topics.", 400);
}
if (dedupId == null && "true".equals(topic.getAttributes().get("ContentBasedDeduplication"))) {
- dedupId = sha256(message);
+ dedupId = Digests.sha256Hex(message);
}
if (dedupId != null && isDuplicate(effectiveArn, messageGroupId, dedupId,
isGroupScopedDeduplication(topic))) {
@@ -1196,7 +1195,7 @@ public class SnsService implements Resettable, ResourceProvider {
}
// Derive deduplication ID if ContentBasedDeduplication is enabled and not provided
if (isFifo && messageDeduplicationId == null && "true".equals(topic.getAttributes().get("ContentBasedDeduplication"))) {
- messageDeduplicationId = sha256(message);
+ messageDeduplicationId = Digests.sha256Hex(message);
}
if (isFifo && messageDeduplicationId != null && isDuplicate(topicArn, messageGroupId,
messageDeduplicationId, groupScopedDedup)) {
@@ -1999,7 +1998,7 @@ public class SnsService implements Resettable, ResourceProvider {
}
// Each failed subscription is a distinct DLQ delivery, even when
// several subscriptions share this queue for the same publish.
- deadLetterDeduplicationId = sha256(messageId + "\0" + sub.getSubscriptionArn());
+ deadLetterDeduplicationId = Digests.sha256Hex(messageId + "\0" + sub.getSubscriptionArn());
}
sqsService.sendMessage(sqsArnToUrl(deadLetterTargetArn), body, null,
deadLetterGroupId, deadLetterDeduplicationId, sqsAttributes, null,
@@ -2340,16 +2339,6 @@ public class SnsService implements Resettable, ResourceProvider {
return total;
}
- private static String sha256(String message) {
- try {
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] hash = md.digest(message.getBytes(StandardCharsets.UTF_8));
- return HEX.formatHex(hash);
- } catch (NoSuchAlgorithmException e) {
- return UUID.randomUUID().toString();
- }
- }
-
private String smsAttributesKey(String region) {
return regionResolver.getAccountId() + "::" + region;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcController.java b/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcController.java
index b8b9f6608d..35dea35d42 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcController.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService;
import io.github.hectorvent.floci.services.ssoadmin.model.ApplicationAccessScope;
@@ -171,8 +172,7 @@ public class SsoOidcController {
}
}
String idToken = localIdToken(applicationArn, requestContext.getAccountId());
- String identityContext = Base64.getUrlEncoder().withoutPadding().encodeToString(
- (requestContext.getAccountId() + ":" + applicationArn).getBytes(StandardCharsets.UTF_8));
+ String identityContext = Base64Url.encode(requestContext.getAccountId() + ":" + applicationArn);
return tokenResponse(session, scopes, issuedTokenType, new String[]{idToken, identityContext});
}
@@ -319,11 +319,8 @@ public class SsoOidcController {
.put("aud", applicationArn)
.put("iat", now)
.put("exp", now + 3600);
- return base64Url(header.toString()) + "." + base64Url(claims.toString()) + ".";
- }
-
- private static String base64Url(String value) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(header.toString()) + "."
+ + Base64Url.encode(claims.toString()) + ".";
}
private String resolveLocalPrincipal(String requestedPrincipalId) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcService.java b/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcService.java
index 573e54960c..9938b604af 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcService.java
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -15,10 +17,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
-import java.util.Base64;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -522,13 +521,7 @@ public class SsoOidcService implements Resettable {
}
private static String pkceChallenge(String verifier) {
- try {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(verifier.getBytes(StandardCharsets.US_ASCII));
- return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 is unavailable", e);
- }
+ return Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
}
private static String trimTrailingSlash(String value) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java
index cd426ab304..84b47d7ab6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.verifiedpermissions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.PublicKeys;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -28,10 +29,8 @@ import java.net.URI;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
-import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
-import java.security.spec.RSAPublicKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
@@ -234,9 +233,8 @@ public class VerifiedPermissionsOidcSignatureVerifier implements AutoCloseable {
}
private static RSAPublicKey toRsaPublicKey(String n, String e) throws GeneralSecurityException {
- BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(pad(n)));
- BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(pad(e)));
- return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
+ return PublicKeys.rsa(new BigInteger(1, Base64.getUrlDecoder().decode(pad(n))),
+ new BigInteger(1, Base64.getUrlDecoder().decode(pad(e))));
}
private static boolean signatureValid(String signingInput, String encodedSignature, RSAPublicKey key) {
diff --git a/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java
index 3537576027..d8c16e866b 100644
--- a/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.config;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.quarkus.test.junit.QuarkusTest;
@@ -25,8 +26,6 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -90,7 +89,7 @@ class EcrTlsDataPlaneDockerIntegrationTest {
// 2. Upload layer blob over TLS
byte[] layerBytes = "floci-ecr-tls-layer-content-v1".getBytes(StandardCharsets.UTF_8);
- String layerDigest = "sha256:" + sha256Hex(layerBytes);
+ String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes);
SimpleResponse startLayerUpload = execute(tlsClient, HttpMethod.POST, sslPort, tlsHost,
"/v2/tls-repo/blobs/uploads/", null, null, null);
@@ -106,7 +105,7 @@ class EcrTlsDataPlaneDockerIntegrationTest {
// 3. Upload config blob over TLS
byte[] configBytes = "{\"architecture\":\"amd64\",\"os\":\"linux\"}".getBytes(StandardCharsets.UTF_8);
- String configDigest = "sha256:" + sha256Hex(configBytes);
+ String configDigest = "sha256:" + Digests.sha256Hex(configBytes);
SimpleResponse startConfigUpload = execute(tlsClient, HttpMethod.POST, sslPort, tlsHost,
"/v2/tls-repo/blobs/uploads/", null, null, null);
@@ -219,24 +218,6 @@ class EcrTlsDataPlaneDockerIntegrationTest {
.toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
}
- private static String sha256Hex(byte[] data) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- byte[] hash = digest.digest(data);
- StringBuilder hexString = new StringBuilder();
- for (byte b : hash) {
- String hex = Integer.toHexString(0xff & b);
- if (hex.length() == 1) {
- hexString.append('0');
- }
- hexString.append(hex);
- }
- return hexString.toString();
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException(e);
- }
- }
-
private record SimpleResponse(int statusCode, MultiMap headers, Buffer body) {
String header(String name) {
return headers.get(name);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/Base64UrlTest.java b/src/test/java/io/github/hectorvent/floci/core/common/Base64UrlTest.java
new file mode 100644
index 0000000000..a062de5da2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/Base64UrlTest.java
@@ -0,0 +1,18 @@
+package io.github.hectorvent.floci.core.common;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class Base64UrlTest {
+
+ @Test
+ void encodesWithTheUrlAlphabetAndNoPadding() {
+ assertEquals("-_8", Base64Url.encode(new byte[] {(byte) 0xfb, (byte) 0xff}));
+ }
+
+ @Test
+ void encodesTextAsUtf8() {
+ assertEquals("w6k", Base64Url.encode("é"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java
new file mode 100644
index 0000000000..5d4665e18e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java
@@ -0,0 +1,28 @@
+package io.github.hectorvent.floci.core.common;
+
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HexFormat;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class DigestsTest {
+
+ private static final String ABC_SHA256 = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
+
+ @Test
+ void sha256MatchesTheFipsTestVector() {
+ assertEquals(ABC_SHA256, HexFormat.of().formatHex(Digests.sha256("abc".getBytes(StandardCharsets.UTF_8))));
+ }
+
+ @Test
+ void sha256HexIsLowercaseHexOfTheDigest() {
+ assertEquals(ABC_SHA256, Digests.sha256Hex("abc".getBytes(StandardCharsets.UTF_8)));
+ }
+
+ @Test
+ void sha256HexOfTextDigestsItsUtf8Bytes() {
+ assertEquals(Digests.sha256Hex("é".getBytes(StandardCharsets.UTF_8)), Digests.sha256Hex("é"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/DomainNamesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/DomainNamesTest.java
new file mode 100644
index 0000000000..5755c066eb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/DomainNamesTest.java
@@ -0,0 +1,23 @@
+package io.github.hectorvent.floci.core.common;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class DomainNamesTest {
+
+ @Test
+ void aDomainIsWithinItselfAndHoldsItsSubdomains() {
+ assertTrue(DomainNames.isWithin("example.com", "example.com"));
+ assertTrue(DomainNames.isWithin("app.example.com", "example.com"));
+ assertTrue(DomainNames.isWithin("a.b.example.com", "example.com"));
+ }
+
+ @Test
+ void aSharedSuffixWithoutALabelBoundaryIsNotASubdomain() {
+ assertFalse(DomainNames.isWithin("badexample.com", "example.com"));
+ assertFalse(DomainNames.isWithin("example.com", "app.example.com"));
+ assertFalse(DomainNames.isWithin("EXAMPLE.com", "example.com"), "names are compared as given");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PublicKeysTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PublicKeysTest.java
new file mode 100644
index 0000000000..71424ec6f6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/PublicKeysTest.java
@@ -0,0 +1,47 @@
+package io.github.hectorvent.floci.core.common;
+
+import org.junit.jupiter.api.Test;
+
+import java.security.GeneralSecurityException;
+import java.security.KeyPairGenerator;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.ECParameterSpec;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class PublicKeysTest {
+
+ @Test
+ void rsaKeyIsRebuiltFromItsModulusAndExponent() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic();
+
+ RSAPublicKey rebuilt = PublicKeys.rsa(key.getModulus(), key.getPublicExponent());
+
+ assertArrayEquals(key.getEncoded(), rebuilt.getEncoded());
+ }
+
+ @Test
+ void ecKeyIsRebuiltFromItsPointOnTheNamedCurve() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp256r1"));
+ ECPublicKey key = (ECPublicKey) generator.generateKeyPair().getPublic();
+
+ ECPublicKey rebuilt = PublicKeys.ec("secp256r1", key.getW().getAffineX(), key.getW().getAffineY());
+
+ assertArrayEquals(key.getEncoded(), rebuilt.getEncoded());
+ }
+
+ @Test
+ void namedCurveDescribesTheCurve() throws Exception {
+ ECParameterSpec p256 = PublicKeys.namedCurve("secp256r1");
+
+ assertEquals(256, p256.getOrder().bitLength());
+ assertThrows(GeneralSecurityException.class, () -> PublicKeys.namedCurve("not-a-curve"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java
index 5b2268fec0..dd16f6f45b 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java
@@ -17,7 +17,6 @@ import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
-import java.util.Base64;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -63,8 +62,7 @@ class WebIdentityTokenVerifierTest {
}
private static String base64Url(String value) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(value.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(value);
}
/** Signs an arbitrary claim set, so tests can build tokens the production mint path never would. */
@@ -76,7 +74,7 @@ class WebIdentityTokenVerifierTest {
signature.initSign(privateKey);
signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
return header + "." + payload + "."
- + Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ + Base64Url.encode(signature.sign());
}
@Test
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 6c41732a40..1538744dd8 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
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.core.common.auth;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
@@ -48,7 +49,7 @@ class SigV4RequestValidatorTest {
// This exact value is also hardcoded in validate()'s canonical request for the empty
// body ElastiCache/RDS presigned tokens always carry; this pins it independently.
assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- SigV4RequestValidator.sha256Hex(""));
+ Digests.sha256Hex(""));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java
index de31b4616b..f2b3f6de2f 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Digests;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@@ -19,8 +20,6 @@ import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
@@ -297,7 +296,7 @@ class DockerClientProducerTest {
Files.createDirectories(dockerConfigDir);
Files.writeString(dockerConfigDir.resolve("config.json"),
"{\"currentContext\":\"" + contextName + "\"}");
- Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(sha256Hex(contextName));
+ Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(Digests.sha256Hex(contextName));
Files.createDirectories(metaDir);
Files.writeString(metaDir.resolve("meta.json"),
"{\"Name\":\"" + contextName + "\",\"Metadata\":{},"
@@ -305,20 +304,6 @@ class DockerClientProducerTest {
+ skipTlsVerify + "}}}");
}
- private static String sha256Hex(String value) {
- try {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- byte[] hash = digest.digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
- StringBuilder hex = new StringBuilder(hash.length * 2);
- for (byte b : hash) {
- hex.append(String.format("%02x", b));
- }
- return hex.toString();
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException("SHA-256 algorithm not available", e);
- }
- }
-
/**
* When floci.docker.docker-host is at its default and DOCKER_HOST is unset, the endpoint of
* the active Docker context (e.g. Colima) is resolved from ~/.docker/config.json and its
@@ -571,7 +556,7 @@ class DockerClientProducerTest {
Path dockerConfigDir, String contextName, boolean withCa, boolean withCert, boolean withKey)
throws IOException {
Path tlsDir = dockerConfigDir.resolve("contexts").resolve("tls")
- .resolve(sha256Hex(contextName)).resolve("docker");
+ .resolve(Digests.sha256Hex(contextName)).resolve("docker");
Files.createDirectories(tlsDir);
if (withCa) {
Files.writeString(tlsDir.resolve("ca.pem"), "-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----");
@@ -602,7 +587,7 @@ class DockerClientProducerTest {
assertEquals("tcp://remote-docker:2376", result.host());
assertTrue(result.tlsCertPath().isPresent(), "TLS material should be surfaced when present");
- assertEquals(tempDir.resolve("contexts").resolve("tls").resolve(sha256Hex("remote-tls")).resolve("docker"),
+ assertEquals(tempDir.resolve("contexts").resolve("tls").resolve(Digests.sha256Hex("remote-tls")).resolve("docker"),
result.tlsCertPath().get());
assertFalse(result.skipTlsVerify(), "SkipTLSVerify defaults to false and should be reported as such");
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4AuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4AuthorizerTest.java
index 810a5ee939..32684fdedd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4AuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ExecuteApiSigV4AuthorizerTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
@@ -294,7 +295,7 @@ class ExecuteApiSigV4AuthorizerTest {
byte[] signedBody = "{\"amount\":1}".getBytes();
Map<String, String> signed = new java.util.LinkedHashMap<>(ExecuteApiRequestSigner.signedHeaders(
"POST", PATH, Map.of(), HOST, signedBody, "test", "test", REGION, Instant.now()));
- signed.put("x-amz-content-sha256", sha256Hex(signedBody));
+ signed.put("x-amz-content-sha256", Digests.sha256Hex(signedBody));
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"POST", headers(signed), uriInfo(PATH, null), "{\"amount\":9999}".getBytes(), null);
@@ -331,15 +332,6 @@ class ExecuteApiSigV4AuthorizerTest {
assertTrue(result.authorized(), String.valueOf(result.detail()));
}
- private static String sha256Hex(byte[] input) throws Exception {
- byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(input);
- StringBuilder hex = new StringBuilder(digest.length * 2);
- for (byte b : digest) {
- hex.append(String.format("%02x", b));
- }
- return hex.toString();
- }
-
private static HttpHeaders headers(Map<String, String> values) {
return headers(values, HOST);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
index 0bc6a398b1..a4fefb2f6a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java
@@ -1,11 +1,10 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import java.nio.charset.StandardCharsets;
-import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -34,9 +33,8 @@ class JwtClaimsWireFormatTest {
}
private static String unsignedToken(String claimsJson) {
- Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
- String header = enc.encodeToString("{\"alg\":\"RS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
- String payload = enc.encodeToString(claimsJson.getBytes(StandardCharsets.UTF_8));
+ String header = Base64Url.encode("{\"alg\":\"RS256\",\"typ\":\"JWT\"}");
+ String payload = Base64Url.encode(claimsJson);
return header + "." + payload + ".sig";
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java
index ee186c4f49..470acdb084 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerQuerystringTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
@@ -20,7 +21,6 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
-import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
@@ -259,14 +259,13 @@ class HttpApiJwtAuthorizerQuerystringTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String json) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(json.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(json);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -274,6 +273,6 @@ class HttpApiJwtAuthorizerQuerystringTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java
index d945b42c54..6201e7aaca 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
@@ -269,15 +270,13 @@ class HttpApiJwtAuthorizerScopesTest {
// ──────────────────────────── Helpers ────────────────────────────
private static String signedToken(Map<String, Object> claims) throws Exception {
- Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
- String header = enc.encodeToString(
- ("{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"" + KEY_ID + "\"}").getBytes(StandardCharsets.UTF_8));
- String payload = enc.encodeToString(MAPPER.writeValueAsBytes(claims));
+ String header = Base64Url.encode("{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"" + KEY_ID + "\"}");
+ String payload = Base64Url.encode(MAPPER.writeValueAsBytes(claims));
String signingInput = header + "." + payload;
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- return signingInput + "." + enc.encodeToString(signature.sign());
+ return signingInput + "." + Base64Url.encode(signature.sign());
}
private static long farFuture() {
@@ -289,7 +288,7 @@ class HttpApiJwtAuthorizerScopesTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java
index 97b6e05036..ba663ef6e9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyJwtClaimsMappingIntegrationTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
@@ -20,7 +21,6 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
-import java.util.Base64;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
@@ -217,7 +217,7 @@ class HttpProxyJwtClaimsMappingIntegrationTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
@@ -229,8 +229,7 @@ class HttpProxyJwtClaimsMappingIntegrationTest {
}
private static String base64Url(String json) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(json.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(json);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -238,6 +237,6 @@ class HttpProxyJwtClaimsMappingIntegrationTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java
index 934689db08..be67e23b82 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.core.common.Base64Url;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.junit.jupiter.api.AfterEach;
@@ -20,7 +21,6 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
-import java.util.Base64;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
@@ -310,13 +310,13 @@ class JwtSignatureVerifierTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String s) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(s.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(s);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -324,6 +324,6 @@ class JwtSignatureVerifierTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java
index 134bbd4991..e0a738f9bd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/CognitoAuthValidatorTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
@@ -190,11 +191,11 @@ class CognitoAuthValidatorTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String value) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(value);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java
index b5ba49db12..ed6fb022b8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import org.junit.jupiter.api.AfterEach;
@@ -24,7 +25,6 @@ import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
-import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@@ -210,12 +210,12 @@ class OidcAuthValidatorTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
- String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String value) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(value);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -223,6 +223,6 @@ class OidcAuthValidatorTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
- return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ return Base64Url.encode(bytes);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java
index 6ea17b011f..e889701e81 100644
--- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactAssetPersistenceTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
@@ -61,7 +62,7 @@ class CodeArtifactAssetPersistenceTest {
byte[] content = "hello world, this is the asset payload".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
String json = Files.readString(dir.resolve("codeartifact-package-versions.json"));
String base64Content = Base64.getEncoder().encodeToString(content);
@@ -76,7 +77,7 @@ class CodeArtifactAssetPersistenceTest {
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult published = first.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
CodeArtifactService restarted = newService(dir);
PackageVersionAssetResult result = restarted.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -122,11 +123,11 @@ class CodeArtifactAssetPersistenceTest {
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
first.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
CodeArtifactService restarted = newService(dir);
PublishPackageVersionResult result = restarted.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", result.packageVersion().getStatus());
assertEquals(1, result.packageVersion().getAssets().size());
@@ -139,12 +140,12 @@ class CodeArtifactAssetPersistenceTest {
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
first.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
CodeArtifactService restarted = newService(dir);
byte[] different = "different bytes".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> restarted.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "true", different));
+ "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "true", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
}
@@ -163,7 +164,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -173,7 +174,7 @@ class CodeArtifactAssetPersistenceTest {
}
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", result.packageVersion().getStatus());
PackageVersionAssetResult fetched = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -194,7 +195,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -204,7 +205,7 @@ class CodeArtifactAssetPersistenceTest {
}
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", result.packageVersion().getStatus());
PackageVersionAssetResult fetched = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -226,7 +227,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -236,7 +237,7 @@ class CodeArtifactAssetPersistenceTest {
}
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", result.packageVersion().getStatus());
PackageVersionAssetResult fetched = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -263,7 +264,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
@@ -277,7 +278,7 @@ class CodeArtifactAssetPersistenceTest {
try {
List<LogRecord> records = LogCapture.capture(CodeArtifactService.class, () ->
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0",
- "a.txt", sha256Hex(content), "true", content));
+ "a.txt", Digests.sha256Hex(content), "true", content));
assertTrue(records.stream().anyMatch(r -> r.getMessage() != null
&& r.getMessage().contains("Could not verify")
@@ -314,7 +315,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
assetFile = paths.filter(Files::isRegularFile).findFirst().orElseThrow();
@@ -323,7 +324,7 @@ class CodeArtifactAssetPersistenceTest {
assertNotNull(fileKeyBefore, "test filesystem must support file keys for this identity check to be meaningful");
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
Object fileKeyAfter = Files.readAttributes(assetFile, BasicFileAttributes.class).fileKey();
assertEquals(fileKeyBefore, fileKeyAfter, "an intact retry must not replace the backing file");
@@ -336,7 +337,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
assetFile = paths.filter(Files::isRegularFile).findFirst().orElseThrow();
@@ -345,7 +346,7 @@ class CodeArtifactAssetPersistenceTest {
assertNotNull(fileKeyBefore, "test filesystem must support file keys for this identity check to be meaningful");
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
Object fileKeyAfter = Files.readAttributes(assetFile, BasicFileAttributes.class).fileKey();
assertEquals(fileKeyBefore, fileKeyAfter, "an intact retry must not replace the backing file");
@@ -365,7 +366,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "true", content);
+ Digests.sha256Hex(content), "true", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -376,7 +377,7 @@ class CodeArtifactAssetPersistenceTest {
byte[] different = "different content".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "true", different));
+ "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "true", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
}
@@ -400,9 +401,9 @@ class CodeArtifactAssetPersistenceTest {
byte[] contentA = "content of a".getBytes(StandardCharsets.UTF_8);
byte[] contentB = "content of b".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(contentA), "true", contentA);
+ Digests.sha256Hex(contentA), "true", contentA);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "b.txt",
- sha256Hex(contentB), "true", contentB);
+ Digests.sha256Hex(contentB), "true", contentB);
Path assetFileA;
Path assetFileB;
@@ -448,7 +449,7 @@ class CodeArtifactAssetPersistenceTest {
for (String name : names) {
byte[] content = ("content of " + name).getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", longToken, longToken, longToken,
- name, sha256Hex(content), "true", content);
+ name, Digests.sha256Hex(content), "true", content);
}
CodeArtifactService restarted = newService(dir);
@@ -488,12 +489,4 @@ class CodeArtifactAssetPersistenceTest {
backend.load();
return new AccountAwareStorageBackend<>(backend, null, ACCOUNT_ID);
}
-
- private static String sha256Hex(byte[] content) {
- try {
- return io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator.sha256Hex(content);
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java
index 1a55af7001..5f1582135b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java
@@ -1,6 +1,6 @@
package io.github.hectorvent.floci.services.codeartifact;
-import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
@@ -147,7 +147,7 @@ class CodeArtifactIntegrationTest {
.body("{}").post("/v1/repository?domain=pkg-domain&repository=pkg-repo").then().statusCode(200);
byte[] content = "hello codeartifact".getBytes(StandardCharsets.UTF_8);
- String sha256 = sha256Hex(content);
+ String sha256 = Digests.sha256Hex(content);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256)
.contentType("application/octet-stream").body(content)
@@ -189,7 +189,7 @@ class CodeArtifactIntegrationTest {
given().contentType("application/json").header("Authorization", AUTH)
.body("{}").post("/v1/repository?domain=describe-domain&repository=repo").then().statusCode(200);
byte[] content = "describe".getBytes(StandardCharsets.UTF_8);
- given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content))
+ given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
.contentType("application/octet-stream").body(content)
.post("/v1/package/version/publish?domain=describe-domain&repository=repo&format=generic"
+ "&namespace=ns&package=my-pkg&version=1.0.0&asset=a.txt")
@@ -218,7 +218,7 @@ class CodeArtifactIntegrationTest {
given().contentType("application/json").header("Authorization", AUTH)
.body("{}").post("/v1/repository?domain=delete-domain&repository=repo").then().statusCode(200);
byte[] content = "delete-me".getBytes(StandardCharsets.UTF_8);
- given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content))
+ given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
.contentType("application/octet-stream").body(content)
.post("/v1/package/version/publish?domain=delete-domain&repository=repo&format=generic"
+ "&namespace=ns&package=my-pkg&version=1.0.0&asset=a.txt")
@@ -274,7 +274,7 @@ class CodeArtifactIntegrationTest {
.body("package.originConfiguration.restrictions.upstream", equalTo("ALLOW"));
byte[] content = "blocked".getBytes(StandardCharsets.UTF_8);
- given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content))
+ given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
.contentType("application/octet-stream").body(content)
.post("/v1/package/version/publish?domain=origin-config-domain&repository=repo&format=generic"
+ "&namespace=ns&package=never-published&version=1.0.0&asset=a.txt")
@@ -301,7 +301,7 @@ class CodeArtifactIntegrationTest {
.body("{}").post("/v1/repository?domain=unfinished-domain&repository=repo").then().statusCode(200);
byte[] content = "partial".getBytes(StandardCharsets.UTF_8);
- String sha256 = sha256Hex(content);
+ String sha256 = Digests.sha256Hex(content);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256)
.contentType("application/octet-stream").body(content)
@@ -363,12 +363,4 @@ class CodeArtifactIntegrationTest {
.then().statusCode(401)
.header("WWW-Authenticate", equalTo("Bearer"));
}
-
- private static String sha256Hex(byte[] content) {
- try {
- return SigV4RequestValidator.sha256Hex(content);
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java
index de66ffc4f5..366c6e81d1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java
@@ -2,9 +2,9 @@ package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
-import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationToken;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
@@ -448,7 +448,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", published.packageVersion().getStatus());
}
@@ -769,7 +769,7 @@ class CodeArtifactServiceTest {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
- String sha256 = sha256Hex(content);
+ String sha256 = Digests.sha256Hex(content);
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
"my-ns", "my-pkg", "1.0.0", "asset.txt", sha256, "false", content);
@@ -814,7 +814,7 @@ class CodeArtifactServiceTest {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
- String sha256 = sha256Hex(content);
+ String sha256 = Digests.sha256Hex(content);
// A newline here would land verbatim in the X-AssetName response header on GetPackageVersionAsset.
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
@@ -830,11 +830,11 @@ class CodeArtifactServiceTest {
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), "yes", content));
+ "repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), "yes", content));
assertEquals("ValidationException", e.getErrorCode());
PublishPackageVersionResult omitted = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), null, content);
+ null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), null, content);
assertEquals("Published", omitted.packageVersion().getStatus());
}
@@ -845,7 +845,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "npm", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), "false", content));
+ "repo", "npm", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ValidationException", e.getErrorCode());
}
@@ -855,7 +855,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "no-such-repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), "false", content));
+ "no-such-repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@@ -866,7 +866,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException publishMissingDomain = assertThrows(AwsException.class, () -> service.publishPackageVersion(
- REGION, null, null, "repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content),
+ REGION, null, null, "repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content),
"false", content));
assertEquals("ValidationException", publishMissingDomain.getErrorCode());
assertEquals("domain is required.", publishMissingDomain.getMessage());
@@ -891,11 +891,11 @@ class CodeArtifactServiceTest {
byte[] second = "second".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult r1 = service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null,
- "my-pkg", "1.0.0", "a.txt", sha256Hex(first), "true", first);
+ "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(first), "true", first);
assertEquals("Unfinished", r1.packageVersion().getStatus());
PublishPackageVersionResult r2 = service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null,
- "my-pkg", "1.0.0", "b.txt", sha256Hex(second), "false", second);
+ "my-pkg", "1.0.0", "b.txt", Digests.sha256Hex(second), "false", second);
assertEquals("Published", r2.packageVersion().getStatus());
assertEquals(2, r2.packageVersion().getAssets().size());
assertTrue(r2.packageVersion().getAssets().containsKey("a.txt"));
@@ -908,13 +908,13 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "same-bytes".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult first = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
// pv is the same mutable object across calls in this storage backend, so the revision has
// to be captured now, before the retry below has a chance to change it in place.
String firstRevision = first.packageVersion().getRevision();
PublishPackageVersionResult retry = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", retry.packageVersion().getStatus());
assertEquals(1, retry.packageVersion().getAssets().size());
@@ -933,13 +933,13 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "same-bytes".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult unfinished = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
// pv is the same mutable object across calls in this storage backend, so this must be
// checked before the second call mutates it, not read back afterward.
assertEquals("Unfinished", unfinished.packageVersion().getStatus());
PublishPackageVersionResult finalized = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", finalized.packageVersion().getStatus());
assertTrue(finalized.packageVersion().getPublishedTime() != null);
@@ -952,10 +952,10 @@ class CodeArtifactServiceTest {
byte[] first = "first-bytes".getBytes(StandardCharsets.UTF_8);
byte[] different = "different-bytes".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(first), "true", first);
+ Digests.sha256Hex(first), "true", first);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "true", different));
+ "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "true", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
assertEquals("asset", e.getExtendedData().get("resourceType"));
@@ -967,10 +967,10 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "b.txt", sha256Hex(content), "false", content));
+ "repo", "generic", null, "my-pkg", "1.0.0", "b.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("1.0.0", e.getExtendedData().get("resourceId"));
assertEquals("package-version", e.getExtendedData().get("resourceType"));
@@ -982,13 +982,13 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult first = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
// pv is the same mutable object across calls in this storage backend, so the revision has
// to be captured now, before the retry below has a chance to change it in place.
String firstRevision = first.packageVersion().getRevision();
PublishPackageVersionResult retry = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", retry.packageVersion().getStatus());
assertEquals(firstRevision, retry.packageVersion().getRevision());
@@ -1000,11 +1000,11 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
byte[] different = "y".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "false", different));
+ "repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "false", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
assertEquals("asset", e.getExtendedData().get("resourceType"));
@@ -1017,11 +1017,11 @@ class CodeArtifactServiceTest {
for (int i = 0; i < 350; i++) {
byte[] content = ("content-" + i).getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0",
- "asset-" + i + ".txt", sha256Hex(content), "true", content);
+ "asset-" + i + ".txt", Digests.sha256Hex(content), "true", content);
}
byte[] oneMore = "one-more".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
- "repo", "generic", null, "my-pkg", "1.0.0", "asset-350.txt", sha256Hex(oneMore), "true", oneMore));
+ "repo", "generic", null, "my-pkg", "1.0.0", "asset-350.txt", Digests.sha256Hex(oneMore), "true", oneMore));
assertEquals("ServiceQuotaExceededException", e.getErrorCode());
assertEquals("1.0.0", e.getExtendedData().get("resourceId"));
assertEquals("package-version", e.getExtendedData().get("resourceType"));
@@ -1029,7 +1029,7 @@ class CodeArtifactServiceTest {
// Re-publishing an asset name already on the version must not itself trip the cap.
byte[] resend = "content-0".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "asset-0.txt",
- sha256Hex(resend), "true", resend);
+ Digests.sha256Hex(resend), "true", resend);
}
@Test
@@ -1038,7 +1038,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
CodeArtifactPackageVersion pv = service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0");
@@ -1056,9 +1056,9 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my::pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo",
"generic", "ns", "my-pkg");
@@ -1199,7 +1199,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK",
"ALLOW");
@@ -1286,13 +1286,13 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException blocked = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom",
- null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content));
+ null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ConflictException", blocked.getErrorCode());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW",
"ALLOW");
PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", published.packageVersion().getStatus());
}
@@ -1334,9 +1334,9 @@ class CodeArtifactServiceTest {
byte[] secondContent = "second-package".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "a::b", "c", "1.0.0", "a.txt",
- sha256Hex(firstContent), "false", firstContent);
+ Digests.sha256Hex(firstContent), "false", firstContent);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "a", "b::c", "1.0.0", "a.txt",
- sha256Hex(secondContent), "false", secondContent);
+ Digests.sha256Hex(secondContent), "false", secondContent);
PackageVersionAssetResult first = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
"a::b", "c", "1.0.0", "a.txt", null);
@@ -1396,7 +1396,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "victim".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "a:b", "x", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
AwsException describeVersion = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION,
"dom", null, "repo", "generic", "a#cb", "x", "1.0.0"));
@@ -1413,11 +1413,11 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "2.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "other-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
CodeArtifactService.PackageDescription deleted = service.deletePackage(REGION, "dom", null, "repo",
"generic", "ns", "my-pkg");
@@ -1458,7 +1458,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW",
"ALLOW");
@@ -1479,7 +1479,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
- sha256Hex(content), "false", content);
+ Digests.sha256Hex(content), "false", content);
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK",
"BLOCK");
@@ -1638,7 +1638,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
- null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
+ null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
PackageVersionAssetResult result = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", null);
@@ -1673,7 +1673,7 @@ class CodeArtifactServiceTest {
"com.example", "my-artifact", "1.0.0", "my-artifact-1.0.0.jar", null);
assertEquals("jar bytes", new String(result.asset().getContent(), StandardCharsets.UTF_8));
- assertEquals(sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8)),
+ assertEquals(Digests.sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8)),
result.packageVersionRevision());
}
@@ -1808,7 +1808,7 @@ class CodeArtifactServiceTest {
go.await();
byte[] content = ("content-" + index).getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg",
- "1.0.0", "asset-" + index + ".txt", sha256Hex(content), "true", content);
+ "1.0.0", "asset-" + index + ".txt", Digests.sha256Hex(content), "true", content);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
@@ -1824,12 +1824,4 @@ class CodeArtifactServiceTest {
"my-pkg", "1.0.0");
assertEquals(assetCount, pv.getAssets().size());
}
-
- private static String sha256Hex(byte[] content) {
- try {
- return SigV4RequestValidator.sha256Hex(content);
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java
index 46e1e714fa..da2f62e79e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
import io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;
@@ -763,7 +764,7 @@ class CognitoOAuthControllerTest {
}
private static String jwtShape(String header, String signature) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes(StandardCharsets.UTF_8))
+ return Base64Url.encode(header)
+ ".payload." + signature;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
index 3637abef14..15322c1647 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -5496,8 +5497,7 @@ class CognitoServiceTest {
otherPool.getId(), "other-client", false, false, List.of(), List.of());
String[] parts = valid.split("\\.");
- String unsigned = Base64.getUrlEncoder().withoutPadding()
- .encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8))
+ String unsigned = Base64Url.encode("{\"alg\":\"none\",\"typ\":\"JWT\"}")
+ "." + parts[1] + ".";
assertInvalidAccessToken(unsigned, "alg=none");
assertInvalidAccessToken(withClaim(valid, "username", "mallory"), "modified payload");
@@ -5628,8 +5628,7 @@ class CognitoServiceTest {
String[] parts = token.split("\\.");
Map<String, Object> claims = MAPPER.readValue(jwtPayload(token), new TypeReference<>() {});
claims.put(name, value);
- String payload = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(MAPPER.writeValueAsBytes(claims));
+ String payload = Base64Url.encode(MAPPER.writeValueAsBytes(claims));
return parts[0] + "." + payload + "." + parts[2];
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java
index d65da41425..d01220395f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
@@ -365,7 +366,6 @@ class CognitoUserInfoIntegrationTest {
}
private static String base64Url(String raw) {
- return java.util.Base64.getUrlEncoder().withoutPadding()
- .encodeToString(raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ return Base64Url.encode(raw);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthnIntegrationTest.java
new file mode 100644
index 0000000000..a75f29d6c6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthnIntegrationTest.java
@@ -0,0 +1,246 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Passkey registration and sign-in over the JSON 1.1 wire protocol. */
+@QuarkusTest
+class CognitoWebAuthnIntegrationTest {
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final String PASSWORD = "Perm1234!";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void passkeyRegistrationAndSignInRoundTrip() throws Exception {
+ String poolId = cognitoJson("CreateUserPool", """
+ {"PoolName":"PasskeyProtocolPool","UserPoolTier":"ESSENTIALS",
+ "Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","WEB_AUTHN"]}}}
+ """).path("UserPool").path("Id").asText();
+ JsonNode mfaConfig = cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OFF",
+ "WebAuthnConfiguration":{"RelyingPartyId":"localhost"}}
+ """.formatted(poolId));
+ assertEquals("localhost", mfaConfig.path("WebAuthnConfiguration").path("RelyingPartyId").asText());
+ assertEquals("preferred", mfaConfig.path("WebAuthnConfiguration").path("UserVerification").asText());
+ cognitoAction("GetUserPoolMfaConfig", """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId))
+ .then().statusCode(200)
+ .body("WebAuthnConfiguration.RelyingPartyId", equalTo("localhost"))
+ .body("WebAuthnConfiguration", not(hasKey("FactorConfiguration")));
+
+ String clientId = cognitoJson("CreateUserPoolClient", """
+ {"UserPoolId":"%s","ClientName":"passkey-client",
+ "ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_AUTH"]}
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ String username = "passkey-" + UUID.randomUUID();
+ cognitoJson("AdminCreateUser", """
+ {"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS"}
+ """.formatted(poolId, username));
+ cognitoJson("AdminSetUserPassword", """
+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
+ """.formatted(poolId, username, PASSWORD));
+ String accessToken = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
+ """.formatted(clientId, username, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
+
+ JsonNode options = cognitoJson("StartWebAuthnRegistration", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken)).path("CredentialCreationOptions");
+ assertTrue(options.isObject(), "CredentialCreationOptions is a document");
+ assertEquals("localhost", options.path("rp").path("id").asText());
+ assertEquals(60000, options.path("timeout").asInt());
+
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
+ ObjectNode complete = JSON.createObjectNode();
+ complete.put("AccessToken", accessToken);
+ complete.set("Credential", authenticator.register(options, "packed"));
+ cognitoAction("CompleteWebAuthnRegistration", complete.toString()).then().statusCode(200);
+ cognitoAction("CompleteWebAuthnRegistration", complete.toString())
+ .then().statusCode(400).body("__type", equalTo("WebAuthnChallengeNotFoundException"));
+
+ cognitoAction("ListWebAuthnCredentials", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken))
+ .then().statusCode(200)
+ .body("Credentials", hasSize(1))
+ .body("Credentials[0].CredentialId", equalTo(authenticator.credentialId()))
+ .body("Credentials[0].RelyingPartyId", equalTo("localhost"))
+ .body("Credentials[0].AuthenticatorTransports", contains("internal", "hybrid"))
+ .body("$", not(hasKey("NextToken")));
+ cognitoAction("GetUserAuthFactors", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken))
+ .then().statusCode(200)
+ .body("ConfiguredUserAuthFactors", contains("PASSWORD", "WEB_AUTHN"));
+
+ JsonNode challenge = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"WEB_AUTHN"}}
+ """.formatted(clientId, username));
+ assertEquals("WEB_AUTHN", challenge.path("ChallengeName").asText());
+ String requestOptions = challenge.path("ChallengeParameters").path("CREDENTIAL_REQUEST_OPTIONS").asText();
+ ObjectNode respond = JSON.createObjectNode();
+ respond.put("ClientId", clientId);
+ respond.put("ChallengeName", "WEB_AUTHN");
+ respond.put("Session", challenge.path("Session").asText());
+ respond.putObject("ChallengeResponses")
+ .put("USERNAME", username)
+ .put("CREDENTIAL", authenticator.authenticate(requestOptions));
+ JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond.toString());
+ assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
+
+ cognitoAction("DeleteWebAuthnCredential", """
+ {"AccessToken":"%s","CredentialId":"%s"}
+ """.formatted(accessToken, authenticator.credentialId()))
+ .then().statusCode(200);
+ cognitoAction("ListWebAuthnCredentials", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken))
+ .then().statusCode(200)
+ .body("Credentials", empty());
+ cognitoAction("DeleteWebAuthnCredential", """
+ {"AccessToken":"%s","CredentialId":"%s"}
+ """.formatted(accessToken, authenticator.credentialId()))
+ .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ void passkeyMfaIsTurnedOnPerUserWithWebAuthnMfaSettings() throws Exception {
+ String poolId = cognitoJson("CreateUserPool", """
+ {"PoolName":"PasskeyMfaPool","UserPoolTier":"ESSENTIALS",
+ "Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","WEB_AUTHN"]}}}
+ """).path("UserPool").path("Id").asText();
+ cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OFF",
+ "WebAuthnConfiguration":{"RelyingPartyId":"localhost"}}
+ """.formatted(poolId));
+ String clientId = cognitoJson("CreateUserPoolClient", """
+ {"UserPoolId":"%s","ClientName":"passkey-mfa-client",
+ "ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_AUTH"]}
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ String username = "passkey-mfa-" + UUID.randomUUID();
+ cognitoJson("AdminCreateUser", """
+ {"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS"}
+ """.formatted(poolId, username));
+ cognitoJson("AdminSetUserPassword", """
+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
+ """.formatted(poolId, username, PASSWORD));
+ String accessToken = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
+ """.formatted(clientId, username, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
+ ObjectNode complete = JSON.createObjectNode();
+ complete.put("AccessToken", accessToken);
+ complete.set("Credential", authenticator.register(cognitoJson("StartWebAuthnRegistration", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken)).path("CredentialCreationOptions"), "none"));
+ cognitoAction("CompleteWebAuthnRegistration", complete.toString()).then().statusCode(200);
+
+ String turnOn = """
+ {"AccessToken":"%s","WebAuthnMfaSettings":{"Enabled":true}}
+ """.formatted(accessToken);
+ cognitoAction("SetUserMFAPreference", turnOn)
+ .then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
+
+ cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"ON",
+ "SoftwareTokenMfaConfiguration":{"Enabled":true},
+ "WebAuthnConfiguration":{"RelyingPartyId":"localhost",
+ "FactorConfiguration":"MULTI_FACTOR_WITH_USER_VERIFICATION"}}
+ """.formatted(poolId));
+ String userAuth = """
+ {"ClientId":"%s","AuthFlow":"USER_AUTH","AuthParameters":{"USERNAME":"%s"}}
+ """.formatted(clientId, username);
+ cognitoAction("InitiateAuth", userAuth)
+ .then().statusCode(200)
+ .body("ChallengeName", equalTo("SELECT_CHALLENGE"))
+ .body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP"));
+
+ cognitoAction("SetUserMFAPreference", turnOn).then().statusCode(200);
+ JsonNode challenge = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"WEB_AUTHN"}}
+ """.formatted(clientId, username));
+ assertEquals("WEB_AUTHN", challenge.path("ChallengeName").asText());
+ String requestOptions = challenge.path("ChallengeParameters").path("CREDENTIAL_REQUEST_OPTIONS").asText();
+ assertEquals("required", JSON.readTree(requestOptions).path("userVerification").asText());
+ ObjectNode respond = JSON.createObjectNode();
+ respond.put("ClientId", clientId);
+ respond.put("ChallengeName", "WEB_AUTHN");
+ respond.put("Session", challenge.path("Session").asText());
+ respond.putObject("ChallengeResponses")
+ .put("USERNAME", username)
+ .put("CREDENTIAL", authenticator.authenticate(requestOptions));
+ JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond.toString());
+ assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
+
+ cognitoAction("AdminSetUserMFAPreference", """
+ {"UserPoolId":"%s","Username":"%s","WebAuthnMfaSettings":{"Enabled":false}}
+ """.formatted(poolId, username))
+ .then().statusCode(200);
+ cognitoAction("InitiateAuth", userAuth)
+ .then().statusCode(200)
+ .body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP"));
+
+ cognitoAction("ListWebAuthnCredentials", """
+ {"AccessToken":"%s","NextToken":"bm90LWEtY3Vyc29y"}
+ """.formatted(accessToken))
+ .then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
+ }
+
+ @Test
+ void passkeyActionsNeedPasskeysEnabledOnThePool() throws Exception {
+ String poolId = cognitoJson("CreateUserPool", """
+ {"PoolName":"PasswordOnlyPool"}
+ """).path("UserPool").path("Id").asText();
+ String clientId = cognitoJson("CreateUserPoolClient", """
+ {"UserPoolId":"%s","ClientName":"password-client","ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH"]}
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ cognitoJson("AdminCreateUser", """
+ {"UserPoolId":"%s","Username":"no-passkeys","MessageAction":"SUPPRESS"}
+ """.formatted(poolId));
+ cognitoJson("AdminSetUserPassword", """
+ {"UserPoolId":"%s","Username":"no-passkeys","Password":"%s","Permanent":true}
+ """.formatted(poolId, PASSWORD));
+ String accessToken = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
+ "AuthParameters":{"USERNAME":"no-passkeys","PASSWORD":"%s"}}
+ """.formatted(clientId, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
+
+ cognitoAction("StartWebAuthnRegistration", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken))
+ .then().statusCode(400).body("__type", equalTo("WebAuthnNotEnabledException"));
+ cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OFF",
+ "WebAuthnConfiguration":{"RelyingPartyId":"localhost","UserVerification":"sometimes"}}
+ """.formatted(poolId))
+ .then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthnTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthnTest.java
new file mode 100644
index 0000000000..edc09f6aeb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoWebAuthnTest.java
@@ -0,0 +1,572 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.acm.AcmService;
+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
+import io.github.hectorvent.floci.services.cognito.model.UserPool;
+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
+import io.github.hectorvent.floci.services.cognito.model.WebAuthnConfiguration;
+import io.github.hectorvent.floci.testing.MutableClock;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+class CognitoWebAuthnTest {
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final String USERNAME = "alice";
+ private static final String PASSWORD = "Perm1234!";
+ private static final String RP_ID = "localhost";
+ private static final String ORIGIN = "http://localhost:3000";
+ /** Leaves a factor's MFA settings as they are, so a call changes passkey MFA alone. */
+ private static final CognitoService.MfaSettingsUpdate UNCHANGED = CognitoService.MfaSettingsUpdate.NONE;
+
+ private CognitoService service;
+ private MutableClock clock;
+ private UserPool pool;
+ private UserPoolClient client;
+
+ @BeforeEach
+ void setUp() {
+ clock = new MutableClock();
+ service = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ "http://localhost:4566", "cloudfront.net",
+ new RegionResolver("us-east-1", "000000000000"), null, mock(AcmService.class),
+ null, null, null, clock);
+ pool = createPool(List.of("PASSWORD", "WEB_AUTHN"));
+ service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false, webAuthnConfiguration(RP_ID, null, null));
+ client = createClient(pool);
+ service.adminCreateUser(pool.getId(), USERNAME, Map.of("email", "[email protected]"), null);
+ service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, true);
+ }
+
+ @Test
+ void registeredPasskeySignsInThroughUserAuth() throws Exception {
+ String accessToken = accessToken();
+ JsonNode options = creationOptions(accessToken);
+ assertEquals(RP_ID, options.path("rp").path("id").asText());
+ assertEquals("required", options.path("authenticatorSelection").path("residentKey").asText());
+ assertEquals("preferred", options.path("authenticatorSelection").path("userVerification").asText());
+ assertEquals(List.of(-7, -257), List.of(options.path("pubKeyCredParams").get(0).path("alg").asInt(),
+ options.path("pubKeyCredParams").get(1).path("alg").asInt()));
+ String sub = service.adminGetUser(pool.getId(), USERNAME).getAttributes().get("sub");
+ assertEquals(Base64Url.encode(sub.getBytes()), options.path("user").path("id").asText());
+
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(options, "none"));
+
+ Map<String, Object> listed = service.listWebAuthnCredentials(accessToken, null, null);
+ List<?> credentials = (List<?>) listed.get("Credentials");
+ assertEquals(1, credentials.size());
+ Map<?, ?> description = (Map<?, ?>) credentials.get(0);
+ assertEquals(authenticator.credentialId(), description.get("CredentialId"));
+ assertEquals(RP_ID, description.get("RelyingPartyId"));
+ assertEquals("platform", description.get("AuthenticatorAttachment"));
+ assertEquals(List.of("internal", "hybrid"), description.get("AuthenticatorTransports"));
+ assertNotNull(description.get("FriendlyCredentialName"));
+ assertFalse(listed.containsKey("NextToken"));
+
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ assertEquals("WEB_AUTHN", challenge.get("ChallengeName"));
+ JsonNode requestOptions = JSON.readTree(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertEquals(RP_ID, requestOptions.path("rpId").asText());
+ assertEquals(authenticator.credentialId(), requestOptions.path("allowCredentials").get(0).path("id").asText());
+ assertEquals("preferred", requestOptions.path("userVerification").asText());
+
+ String session = (String) challenge.get("Session");
+ Map<String, String> answer = Map.of("USERNAME", USERNAME,
+ "CREDENTIAL", authenticator.authenticate(requestOptions.toString()));
+ Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", session, answer);
+ assertNotNull(((Map<?, ?>) signedIn.get("AuthenticationResult")).get("AccessToken"));
+ assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().get(0).getSignCount());
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", session, answer))
+ .getErrorCode());
+ }
+
+ @Test
+ void packedSelfAttestationWithRs256IsAccepted() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.rs256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken),
+ "packed"));
+
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential))
+ .get("AuthenticationResult"));
+ }
+
+ @Test
+ void attestationStatementIsNotVerified() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN).corruptAttestation();
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken),
+ "packed"));
+ assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().size(),
+ "Cognito does not enforce attestation, so a statement that does not verify is not refused");
+
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential))
+ .get("AuthenticationResult"));
+ }
+
+ @Test
+ void registrationRejectsCredentialsCognitoDoesNotAccept() throws Exception {
+ String accessToken = accessToken();
+ assertRegistrationFails("WebAuthnCredentialNotSupportedException", accessToken,
+ WebAuthnTestAuthenticator.es384(ORIGIN));
+ assertRegistrationFails("WebAuthnOriginNotAllowedException", accessToken,
+ WebAuthnTestAuthenticator.es256("https://evil.example"));
+ assertRegistrationFails("WebAuthnRelyingPartyMismatchException", accessToken,
+ WebAuthnTestAuthenticator.es256(ORIGIN).relyingPartyId("example.com"));
+
+ AwsException noChallenge = assertThrows(AwsException.class, () -> service.completeWebAuthnRegistration(
+ accessToken, WebAuthnTestAuthenticator.es256(ORIGIN).register(JSON.readTree(
+ "{\"challenge\":\"AAAA\",\"rp\":{\"id\":\"localhost\"}}"), "none")));
+ assertEquals("WebAuthnChallengeNotFoundException", noChallenge.getErrorCode());
+ assertTrue(service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().isEmpty());
+ }
+
+ @Test
+ void httpsSubdomainOriginsAreAllowedAndHttpOnlyForLocalhost() throws Exception {
+ service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false,
+ webAuthnConfiguration("example.com", null, null));
+ String accessToken = accessToken();
+ assertRegistrationFails("WebAuthnOriginNotAllowedException", accessToken,
+ WebAuthnTestAuthenticator.es256("http://app.example.com"));
+ service.completeWebAuthnRegistration(accessToken,
+ WebAuthnTestAuthenticator.es256("https://app.example.com").register(creationOptions(accessToken),
+ "none"));
+ assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().size());
+ }
+
+ @Test
+ void registrationChallengeExpiresAndBelongsToTheStartingClient() throws Exception {
+ String accessToken = accessToken();
+ JsonNode options = creationOptions(accessToken);
+ UserPoolClient other = createClient(pool);
+ String otherToken = (String) ((Map<?, ?>) service.initiateAuth(other.getClientId(), "USER_PASSWORD_AUTH",
+ Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)).get("AuthenticationResult")).get("AccessToken");
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ assertEquals("WebAuthnClientMismatchException", assertThrows(AwsException.class,
+ () -> service.completeWebAuthnRegistration(otherToken, authenticator.register(options, "none")))
+ .getErrorCode());
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(options, "none"));
+ assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().size());
+
+ JsonNode expiring = creationOptions(accessToken);
+ clock.advance(Duration.ofMinutes(6));
+ String laterToken = accessToken();
+ assertEquals("WebAuthnChallengeNotFoundException", assertThrows(AwsException.class,
+ () -> service.completeWebAuthnRegistration(laterToken,
+ WebAuthnTestAuthenticator.es256(ORIGIN).register(expiring, "none"))).getErrorCode());
+ }
+
+ @Test
+ void requiredUserVerificationRejectsAnAuthenticatorThatSkipsIt() throws Exception {
+ service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false,
+ webAuthnConfiguration(RP_ID, "required", null));
+ String accessToken = accessToken();
+ assertRegistrationFails("WebAuthnCredentialNotSupportedException", accessToken,
+ WebAuthnTestAuthenticator.es256(ORIGIN).userVerified(false));
+
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+ authenticator.userVerified(false);
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential)))
+ .getErrorCode());
+ }
+
+ @Test
+ void signInRejectsABadSignatureAndAnUnknownPasskey() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator registered = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, registered.register(creationOptions(accessToken), "none"));
+
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ ObjectNode tampered = (ObjectNode) JSON.readTree(
+ registered.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS")));
+ ObjectNode response = (ObjectNode) tampered.path("response");
+ byte[] signature = Base64.getUrlDecoder().decode(response.path("signature").asText());
+ signature[signature.length - 1] ^= 0x01;
+ response.put("signature", Base64Url.encode(signature));
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"),
+ Map.of("USERNAME", USERNAME, "CREDENTIAL", tampered.toString()))).getErrorCode());
+
+ Map<String, Object> retry = userAuth("WEB_AUTHN");
+ String unknown = WebAuthnTestAuthenticator.es256(ORIGIN)
+ .authenticate(challengeParameters(retry).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) retry.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", unknown)))
+ .getErrorCode());
+ }
+
+ @Test
+ void signInRejectsASignatureCounterThatDoesNotMoveForward() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+
+ Map<String, Object> earlier = userAuth("WEB_AUTHN");
+ String earlierCredential = authenticator.authenticate(
+ challengeParameters(earlier).get("CREDENTIAL_REQUEST_OPTIONS"));
+ Map<String, Object> later = userAuth("WEB_AUTHN");
+ String laterCredential = authenticator.authenticate(
+ challengeParameters(later).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", (String) later.get("Session"),
+ Map.of("USERNAME", USERNAME, "CREDENTIAL", laterCredential)).get("AuthenticationResult"));
+
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) earlier.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", earlierCredential)))
+ .getErrorCode(), "a counter below the stored one suggests a cloned authenticator");
+ assertEquals(2, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().get(0).getSignCount());
+ }
+
+ @Test
+ void selectChallengeOffersPasskeysOnceRegisteredAndDeletingRemovesThem() throws Exception {
+ String accessToken = accessToken();
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
+
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+ Map<String, Object> select = userAuth(null);
+ assertEquals("SELECT_CHALLENGE", select.get("ChallengeName"));
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP", "WEB_AUTHN"), select.get("AvailableChallenges"));
+ assertEquals(List.of("PASSWORD", "WEB_AUTHN"),
+ service.getUserAuthFactors(accessToken).get("ConfiguredUserAuthFactors"));
+
+ Map<String, Object> chosen = service.respondToAuthChallenge(client.getClientId(), "SELECT_CHALLENGE",
+ (String) select.get("Session"), Map.of("USERNAME", USERNAME, "ANSWER", "WEB_AUTHN"));
+ assertEquals("WEB_AUTHN", chosen.get("ChallengeName"));
+ assertFalse(chosen.containsKey("AvailableChallenges"));
+ String credential = authenticator.authenticate(challengeParameters(chosen).get("CREDENTIAL_REQUEST_OPTIONS"));
+ assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", (String) chosen.get("Session"),
+ Map.of("USERNAME", USERNAME, "CREDENTIAL", credential)).get("AuthenticationResult"));
+
+ service.deleteWebAuthnCredential(accessToken, authenticator.credentialId());
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
+ assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
+ () -> service.deleteWebAuthnCredential(accessToken, authenticator.credentialId())).getErrorCode());
+ }
+
+ @Test
+ void poolsWithoutPasskeysOrARelyingPartyAreRefused() {
+ UserPool passwordOnly = createPool(List.of("PASSWORD"));
+ UserPoolClient passwordClient = createClient(passwordOnly);
+ service.adminCreateUser(passwordOnly.getId(), USERNAME, Map.of(), null);
+ service.adminSetUserPassword(passwordOnly.getId(), USERNAME, PASSWORD, true);
+ String passwordToken = accessToken(passwordClient);
+ assertEquals("WebAuthnNotEnabledException", assertThrows(AwsException.class,
+ () -> service.startWebAuthnRegistration(passwordToken)).getErrorCode());
+
+ UserPool unconfigured = createPool(List.of("PASSWORD", "WEB_AUTHN"));
+ UserPoolClient unconfiguredClient = createClient(unconfigured);
+ service.adminCreateUser(unconfigured.getId(), USERNAME, Map.of(), null);
+ service.adminSetUserPassword(unconfigured.getId(), USERNAME, PASSWORD, true);
+ String unconfiguredToken = accessToken(unconfiguredClient);
+ assertEquals("WebAuthnConfigurationMissingException", assertThrows(AwsException.class,
+ () -> service.startWebAuthnRegistration(unconfiguredToken)).getErrorCode());
+
+ service.createUserPoolDomain("passkeys-prefix", unconfigured.getId(), null, null);
+ Map<?, ?> options = (Map<?, ?>) service.startWebAuthnRegistration(unconfiguredToken)
+ .get("CredentialCreationOptions");
+ assertEquals("passkeys-prefix.auth.us-east-1.amazoncognito.com", ((Map<?, ?>) options.get("rp")).get("id"));
+ }
+
+ @Test
+ void requiredMfaOffersPasskeysOnlyToUsersWhoTurnedPasskeyMfaOn() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+
+ service.setUserPoolMfaConfig(pool.getId(), "ON", true, false, null);
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
+ assertEquals("InvalidParameterException", assertThrows(AwsException.class,
+ () -> service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true)).getErrorCode(),
+ "passkey MFA needs a pool whose passkeys can satisfy MFA");
+ assertFalse(service.adminGetUser(pool.getId(), USERNAME).isWebAuthnMfaEnabled());
+
+ service.setUserPoolMfaConfig(pool.getId(), "ON", true, false,
+ webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"),
+ "the pool's FactorConfiguration alone does not let a passkey skip MFA");
+ assertEquals("SELECT_CHALLENGE", userAuth("WEB_AUTHN").get("ChallengeName"));
+
+ service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
+ assertTrue(service.adminGetUser(pool.getId(), USERNAME).isWebAuthnMfaEnabled());
+ Map<String, Object> unverified = userAuth("WEB_AUTHN");
+ String requestOptions = challengeParameters(unverified).get("CREDENTIAL_REQUEST_OPTIONS");
+ assertEquals("required", JSON.readTree(requestOptions).path("userVerification").asText(),
+ "a passkey standing in for required MFA must verify the user");
+ String withoutVerification = authenticator.userVerified(false).authenticate(requestOptions);
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) unverified.get("Session"),
+ Map.of("USERNAME", USERNAME, "CREDENTIAL", withoutVerification))).getErrorCode());
+
+ authenticator.userVerified(true);
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ assertEquals("WEB_AUTHN", challenge.get("ChallengeName"));
+ String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential));
+ assertNotNull(signedIn.get("AuthenticationResult"), "a verified passkey satisfies required MFA");
+ assertNull(signedIn.get("ChallengeName"));
+
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, UNCHANGED, UNCHANGED, false);
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
+ }
+
+ @Test
+ void passkeyMfaTurnedOffMidSignInLeavesMfaToBeDone() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+ service.setUserPoolMfaConfig(pool.getId(), "ON", true, false,
+ webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
+ service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
+
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ assertEquals("WEB_AUTHN", challenge.get("ChallengeName"));
+ String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, UNCHANGED, UNCHANGED, false);
+
+ Map<String, Object> answered = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential));
+ assertNull(answered.get("AuthenticationResult"), "the passkey no longer stands in for MFA");
+ assertEquals("MFA_SETUP", answered.get("ChallengeName"));
+ }
+
+ @Test
+ void optionalMfaAsksForUserVerificationOnlyFromUsersWithPasskeyMfa() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN).userVerified(false);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+ service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false,
+ webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
+
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ String requestOptions = challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS");
+ assertEquals("preferred", JSON.readTree(requestOptions).path("userVerification").asText());
+ assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"),
+ Map.of("USERNAME", USERNAME, "CREDENTIAL", authenticator.authenticate(requestOptions)))
+ .get("AuthenticationResult"));
+
+ service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
+ Map<String, Object> mfaChallenge = userAuth("WEB_AUTHN");
+ String mfaOptions = challengeParameters(mfaChallenge).get("CREDENTIAL_REQUEST_OPTIONS");
+ assertEquals("required", JSON.readTree(mfaOptions).path("userVerification").asText());
+ String withoutVerification = authenticator.authenticate(mfaOptions);
+ assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
+ () -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) mfaChallenge.get("Session"),
+ Map.of("USERNAME", USERNAME, "CREDENTIAL", withoutVerification))).getErrorCode());
+ }
+
+ @Test
+ void optionalMfaKeepsPasskeysForTotpUsersWhosePasskeySatisfiesMfa() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+ service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false,
+ webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
+ String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
+ service.verifySoftwareToken(accessToken, null, CognitoTotp.code(secret, clock.instant()));
+ service.setUserMFAPreference(accessToken, UNCHANGED, new CognitoService.MfaSettingsUpdate(true, true));
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"),
+ "a user with MFA in an optional-MFA pool signs in with a password");
+
+ service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP", "WEB_AUTHN"), userAuth(null).get("AvailableChallenges"),
+ "a user-verified passkey satisfies MFA on its own");
+ Map<String, Object> challenge = userAuth("WEB_AUTHN");
+ String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
+ Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
+ (String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential));
+ assertNotNull(signedIn.get("AuthenticationResult"));
+ assertNull(signedIn.get("ChallengeName"));
+ }
+
+ @Test
+ void passkeyMfaNeedsTheEssentialsTierOrHigher() {
+ UserPool lite = service.createUserPool(Map.of("PoolName", "LitePool", "UserPoolTier", "LITE"), "us-east-1");
+ service.setUserPoolMfaConfig(lite.getId(), "OFF", null, false,
+ webAuthnConfiguration(RP_ID, null, "MULTI_FACTOR_WITH_USER_VERIFICATION"));
+ service.adminCreateUser(lite.getId(), USERNAME, Map.of(), null);
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.adminSetUserMFAPreference(lite.getId(), USERNAME, UNCHANGED, UNCHANGED, true));
+ assertEquals("InvalidParameterException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("Essentials"), refused.getMessage());
+ assertFalse(service.adminGetUser(lite.getId(), USERNAME).isWebAuthnMfaEnabled());
+ service.adminSetUserMFAPreference(lite.getId(), USERNAME, UNCHANGED, UNCHANGED, false);
+ }
+
+ @Test
+ void userCanRegisterAtMostTwentyPasskeys() throws Exception {
+ String accessToken = accessToken();
+ for (int i = 0; i < CognitoWebAuthn.MAX_CREDENTIALS_PER_USER; i++) {
+ service.completeWebAuthnRegistration(accessToken,
+ WebAuthnTestAuthenticator.es256(ORIGIN).register(creationOptions(accessToken), "none"));
+ }
+ assertEquals("LimitExceededException", assertThrows(AwsException.class,
+ () -> service.startWebAuthnRegistration(accessToken)).getErrorCode());
+
+ Map<String, Object> firstPage = service.listWebAuthnCredentials(accessToken, 15, null);
+ assertEquals(15, ((List<?>) firstPage.get("Credentials")).size());
+ Map<String, Object> secondPage = service.listWebAuthnCredentials(accessToken, 15,
+ (String) firstPage.get("NextToken"));
+ assertEquals(5, ((List<?>) secondPage.get("Credentials")).size());
+ assertFalse(secondPage.containsKey("NextToken"));
+ }
+
+ @Test
+ void pagesListPasskeysOldestFirstAndSkipNoneWhenOneIsDeleted() throws Exception {
+ String accessToken = accessToken();
+ List<String> registered = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken),
+ "none"));
+ registered.add(authenticator.credentialId());
+ clock.advance(Duration.ofMillis(1));
+ }
+
+ Map<String, Object> firstPage = service.listWebAuthnCredentials(accessToken, 1, null);
+ assertEquals(List.of(registered.get(0)), credentialIds(firstPage));
+ service.deleteWebAuthnCredential(accessToken, registered.get(0));
+ Map<String, Object> secondPage = service.listWebAuthnCredentials(accessToken, 1,
+ (String) firstPage.get("NextToken"));
+ assertEquals(List.of(registered.get(1)), credentialIds(secondPage),
+ "deleting a listed passkey does not move the next page past one");
+ Map<String, Object> lastPage = service.listWebAuthnCredentials(accessToken, 1,
+ (String) secondPage.get("NextToken"));
+ assertEquals(List.of(registered.get(2)), credentialIds(lastPage));
+ assertFalse(lastPage.containsKey("NextToken"));
+
+ assertEquals(List.of(registered.get(1), registered.get(2)),
+ credentialIds(service.listWebAuthnCredentials(accessToken, 0, null)));
+ for (String token : List.of("not-a-token!", Base64.getUrlEncoder().encodeToString("ListUsers:x".getBytes()))) {
+ assertEquals("InvalidParameterException", assertThrows(AwsException.class,
+ () -> service.listWebAuthnCredentials(accessToken, null, token)).getErrorCode());
+ }
+ AwsException negative = assertThrows(AwsException.class,
+ () -> service.listWebAuthnCredentials(accessToken, -1, null));
+ assertTrue(negative.getMessage().endsWith("Member must have value greater than or equal to 0"),
+ negative.getMessage());
+ }
+
+ @Test
+ void passkeysSurviveUserSerialization() throws Exception {
+ String accessToken = accessToken();
+ WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
+ service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
+
+ CognitoUser restored = JSON.readValue(
+ JSON.writeValueAsBytes(service.adminGetUser(pool.getId(), USERNAME)), CognitoUser.class);
+ assertEquals(authenticator.credentialId(), restored.getWebAuthnCredentials().get(0).getCredentialId());
+ assertEquals(service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().get(0)
+ .getAttestedCredentialData(), restored.getWebAuthnCredentials().get(0).getAttestedCredentialData());
+
+ service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false,
+ webAuthnConfiguration(RP_ID, null, "MULTI_FACTOR_WITH_USER_VERIFICATION"));
+ service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
+ assertTrue(JSON.readValue(JSON.writeValueAsBytes(service.adminGetUser(pool.getId(), USERNAME)),
+ CognitoUser.class).isWebAuthnMfaEnabled());
+ }
+
+ private void assertRegistrationFails(String errorCode, String accessToken, WebAuthnTestAuthenticator authenticator)
+ throws Exception {
+ JsonNode options = creationOptions(accessToken);
+ Executable complete = () -> service.completeWebAuthnRegistration(accessToken,
+ authenticator.register(options, "none"));
+ assertEquals(errorCode, assertThrows(AwsException.class, complete).getErrorCode());
+ }
+
+ private static List<String> credentialIds(Map<String, Object> page) {
+ return ((List<?>) page.get("Credentials")).stream()
+ .map(description -> (String) ((Map<?, ?>) description).get("CredentialId"))
+ .toList();
+ }
+
+ private JsonNode creationOptions(String accessToken) {
+ return JSON.valueToTree(service.startWebAuthnRegistration(accessToken).get("CredentialCreationOptions"));
+ }
+
+ private Map<String, Object> userAuth(String preferredChallenge) {
+ Map<String, String> params = preferredChallenge == null
+ ? Map.of("USERNAME", USERNAME)
+ : Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", preferredChallenge);
+ return service.initiateAuth(client.getClientId(), "USER_AUTH", params);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map<String, String> challengeParameters(Map<String, Object> challenge) {
+ return (Map<String, String>) challenge.get("ChallengeParameters");
+ }
+
+ private String accessToken() {
+ return accessToken(client);
+ }
+
+ private String accessToken(UserPoolClient appClient) {
+ return (String) ((Map<?, ?>) service.initiateAuth(appClient.getClientId(), "USER_PASSWORD_AUTH",
+ Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)).get("AuthenticationResult")).get("AccessToken");
+ }
+
+ private UserPool createPool(List<String> allowedFirstAuthFactors) {
+ return service.createUserPool(Map.of("PoolName", "PasskeyPool",
+ "Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", allowedFirstAuthFactors))),
+ "us-east-1");
+ }
+
+ private UserPoolClient createClient(UserPool userPool) {
+ UserPoolClient appClient = service.createUserPoolClient(userPool.getId(), "passkey-client", false, false,
+ List.of(), List.of());
+ appClient.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_AUTH"));
+ return appClient;
+ }
+
+ private static WebAuthnConfiguration webAuthnConfiguration(String relyingPartyId, String userVerification,
+ String factorConfiguration) {
+ WebAuthnConfiguration configuration = new WebAuthnConfiguration();
+ configuration.setRelyingPartyId(relyingPartyId);
+ configuration.setUserVerification(userVerification);
+ configuration.setFactorConfiguration(factorConfiguration);
+ return configuration;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java
index 5a226ccc93..3b7fafc624 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/GlobalSignOutIntegrationTest.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
@@ -10,7 +11,6 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
-import java.util.Base64;
import java.util.UUID;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
@@ -266,6 +266,6 @@ class GlobalSignOutIntegrationTest {
}
private static String base64Url(String value) {
- return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes());
+ return Base64Url.encode(value.getBytes());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/WebAuthnTestAuthenticator.java b/src/test/java/io/github/hectorvent/floci/services/cognito/WebAuthnTestAuthenticator.java
new file mode 100644
index 0000000000..e2fb890d33
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/WebAuthnTestAuthenticator.java
@@ -0,0 +1,266 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.ECGenParameterSpec;
+import java.util.Arrays;
+import java.util.UUID;
+
+/**
+ * A software passkey authenticator for tests, standing in for a browser and its authenticator:
+ * it answers creation options with a {@code RegistrationResponseJSON} ({@code none} or
+ * {@code packed} self attestation) and request options with an {@code AuthenticationResponseJSON}.
+ */
+final class WebAuthnTestAuthenticator {
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final byte FLAG_UP = 0x01;
+ private static final byte FLAG_UV = 0x04;
+ private static final byte FLAG_AT = 0x40;
+
+ private final String origin;
+ private final KeyPair keyPair;
+ private final long algorithm;
+ private final String signatureAlgorithm;
+ private final byte[] credentialId = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
+ private String relyingPartyIdOverride;
+ private boolean userVerified = true;
+ private boolean corruptAttestation;
+ private long signCount;
+
+ private WebAuthnTestAuthenticator(String origin, KeyPair keyPair, long algorithm, String signatureAlgorithm) {
+ this.origin = origin;
+ this.keyPair = keyPair;
+ this.algorithm = algorithm;
+ this.signatureAlgorithm = signatureAlgorithm;
+ }
+
+ static WebAuthnTestAuthenticator es256(String origin) throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp256r1"));
+ return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -7, "SHA256withECDSA");
+ }
+
+ static WebAuthnTestAuthenticator es384(String origin) throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp384r1"));
+ return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -35, "SHA384withECDSA");
+ }
+
+ static WebAuthnTestAuthenticator rs256(String origin) throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -257, "SHA256withRSA");
+ }
+
+ /** Claims {@code relyingPartyId} instead of the one the options name. */
+ WebAuthnTestAuthenticator relyingPartyId(String relyingPartyId) {
+ this.relyingPartyIdOverride = relyingPartyId;
+ return this;
+ }
+
+ WebAuthnTestAuthenticator userVerified(boolean userVerified) {
+ this.userVerified = userVerified;
+ return this;
+ }
+
+ /** Signs a {@code packed} attestation statement over the wrong data. */
+ WebAuthnTestAuthenticator corruptAttestation() {
+ this.corruptAttestation = true;
+ return this;
+ }
+
+ String credentialId() {
+ return Base64Url.encode(credentialId);
+ }
+
+ ObjectNode register(JsonNode creationOptions, String format) throws Exception {
+ String relyingPartyId = relyingPartyIdOverride != null
+ ? relyingPartyIdOverride : creationOptions.path("rp").path("id").asText();
+ byte[] clientData = clientData("webauthn.create", creationOptions.path("challenge").asText());
+ ByteArrayOutputStream authData = new ByteArrayOutputStream();
+ authData.write(Digests.sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)));
+ authData.write(FLAG_UP | FLAG_AT | (userVerified ? FLAG_UV : 0));
+ authData.write(ByteBuffer.allocate(4).putInt((int) signCount).array());
+ authData.write(new byte[16]);
+ authData.write(ByteBuffer.allocate(2).putShort((short) credentialId.length).array());
+ authData.write(credentialId);
+ authData.write(coseKey());
+ byte[] authenticatorData = authData.toByteArray();
+
+ Cbor statement = new Cbor();
+ if ("packed".equals(format)) {
+ byte[] signed = concat(authenticatorData, Digests.sha256(clientData));
+ if (corruptAttestation) {
+ signed[0] ^= 0x01;
+ }
+ statement.map(2).text("alg").integer(algorithm).text("sig").bytes(sign(signed));
+ } else {
+ statement.map(0);
+ }
+ byte[] attestationObject = new Cbor().map(3)
+ .text("fmt").text(format)
+ .text("attStmt").raw(statement.toByteArray())
+ .text("authData").bytes(authenticatorData)
+ .toByteArray();
+
+ ObjectNode credential = JSON.createObjectNode();
+ credential.put("id", credentialId());
+ credential.put("rawId", credentialId());
+ credential.put("type", "public-key");
+ credential.put("authenticatorAttachment", "platform");
+ credential.putObject("clientExtensionResults");
+ ObjectNode response = credential.putObject("response");
+ response.put("clientDataJSON", Base64Url.encode(clientData));
+ response.put("attestationObject", Base64Url.encode(attestationObject));
+ response.putArray("transports").add("internal").add("hybrid");
+ return credential;
+ }
+
+ String authenticate(String requestOptionsJson) throws Exception {
+ JsonNode options = JSON.readTree(requestOptionsJson);
+ String relyingPartyId = relyingPartyIdOverride != null ? relyingPartyIdOverride : options.path("rpId").asText();
+ byte[] clientData = clientData("webauthn.get", options.path("challenge").asText());
+ signCount++;
+ byte[] authenticatorData = concat(Digests.sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)),
+ new byte[] {(byte) (FLAG_UP | (userVerified ? FLAG_UV : 0))},
+ ByteBuffer.allocate(4).putInt((int) signCount).array());
+
+ ObjectNode credential = JSON.createObjectNode();
+ credential.put("id", credentialId());
+ credential.put("rawId", credentialId());
+ credential.put("type", "public-key");
+ credential.put("authenticatorAttachment", "platform");
+ credential.putObject("clientExtensionResults");
+ ObjectNode response = credential.putObject("response");
+ response.put("authenticatorData", Base64Url.encode(authenticatorData));
+ response.put("clientDataJSON", Base64Url.encode(clientData));
+ response.put("signature", Base64Url.encode(sign(concat(authenticatorData, Digests.sha256(clientData)))));
+ return JSON.writeValueAsString(credential);
+ }
+
+ private byte[] clientData(String type, String challenge) throws Exception {
+ ObjectNode clientData = JSON.createObjectNode();
+ clientData.put("type", type);
+ clientData.put("challenge", challenge);
+ clientData.put("origin", origin);
+ clientData.put("crossOrigin", false);
+ return JSON.writeValueAsBytes(clientData);
+ }
+
+ private byte[] coseKey() {
+ if (keyPair.getPublic() instanceof RSAPublicKey rsa) {
+ return new Cbor().map(4)
+ .integer(1).integer(3)
+ .integer(3).integer(algorithm)
+ .integer(-1).bytes(unsigned(rsa.getModulus()))
+ .integer(-2).bytes(unsigned(rsa.getPublicExponent()))
+ .toByteArray();
+ }
+ ECPublicKey ec = (ECPublicKey) keyPair.getPublic();
+ int size = algorithm == -35 ? 48 : 32;
+ return new Cbor().map(5)
+ .integer(1).integer(2)
+ .integer(3).integer(algorithm)
+ .integer(-1).integer(algorithm == -35 ? 2 : 1)
+ .integer(-2).bytes(fixed(ec.getW().getAffineX(), size))
+ .integer(-3).bytes(fixed(ec.getW().getAffineY(), size))
+ .toByteArray();
+ }
+
+ private byte[] sign(byte[] data) throws Exception {
+ Signature signature = Signature.getInstance(signatureAlgorithm);
+ signature.initSign(keyPair.getPrivate());
+ signature.update(data);
+ return signature.sign();
+ }
+
+ private static byte[] concat(byte[]... parts) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ for (byte[] part : parts) {
+ out.writeBytes(part);
+ }
+ return out.toByteArray();
+ }
+
+ private static byte[] unsigned(BigInteger value) {
+ byte[] bytes = value.toByteArray();
+ return bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes;
+ }
+
+ private static byte[] fixed(BigInteger value, int size) {
+ byte[] bytes = unsigned(value);
+ byte[] padded = new byte[size];
+ System.arraycopy(bytes, 0, padded, size - bytes.length, bytes.length);
+ return padded;
+ }
+
+ /** The few CBOR items an attestation object and a COSE key need. */
+ private static final class Cbor {
+ private final ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+ Cbor map(int entries) {
+ head(5, entries);
+ return this;
+ }
+
+ Cbor text(String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ head(3, bytes.length);
+ out.writeBytes(bytes);
+ return this;
+ }
+
+ Cbor bytes(byte[] value) {
+ head(2, value.length);
+ out.writeBytes(value);
+ return this;
+ }
+
+ Cbor integer(long value) {
+ if (value >= 0) {
+ head(0, value);
+ } else {
+ head(1, -1 - value);
+ }
+ return this;
+ }
+
+ Cbor raw(byte[] encoded) {
+ out.writeBytes(encoded);
+ return this;
+ }
+
+ byte[] toByteArray() {
+ return out.toByteArray();
+ }
+
+ private void head(int majorType, long value) {
+ int major = majorType << 5;
+ if (value < 24) {
+ out.write(major | (int) value);
+ } else if (value < 0x100) {
+ out.write(major | 24);
+ out.write((int) value);
+ } else if (value < 0x10000) {
+ out.write(major | 25);
+ out.writeBytes(ByteBuffer.allocate(2).putShort((short) value).array());
+ } else {
+ out.write(major | 26);
+ out.writeBytes(ByteBuffer.allocate(4).putInt((int) value).array());
+ }
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClientTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClientTest.java
index 41a9f63c5e..65b403024d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClientTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbLocalClientTest.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
@@ -237,10 +238,10 @@ class DynamoDbLocalClientTest {
+ "x-amz-date:" + amzDate + "\n"
+ "x-amz-target:" + headers.getFirst("X-Amz-Target") + "\n\n"
+ "content-type;host;x-amz-date;x-amz-target\n"
- + SigV4RequestValidator.sha256Hex(request.body());
+ + Digests.sha256Hex(request.body());
String credentialScope = date + "/eu-west-1/dynamodb/aws4_request";
String toSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
- + SigV4RequestValidator.sha256Hex(canonical);
+ + Digests.sha256Hex(canonical);
byte[] key = SigV4RequestValidator.deriveSigningKey("floci", date, "eu-west-1", "dynamodb");
return SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(key, toSign));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java
index 1bf80cccca..c3a6a8d68f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.RegisterTaskDefinitionRequest;
@@ -14,11 +15,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.security.MessageDigest;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -463,8 +461,7 @@ class EcsJsonHandlerVolumesTest {
private static void writeContextFixture(Path dockerConfigDir, String contextName, String host) throws Exception {
Files.createDirectories(dockerConfigDir);
Files.writeString(dockerConfigDir.resolve("config.json"), "{\"currentContext\":\"" + contextName + "\"}");
- byte[] nameHash = MessageDigest.getInstance("SHA-256").digest(contextName.getBytes(StandardCharsets.UTF_8));
- Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(HexFormat.of().formatHex(nameHash));
+ Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(Digests.sha256Hex(contextName));
Files.createDirectories(metaDir);
Files.writeString(metaDir.resolve("meta.json"),
"{\"Name\":\"" + contextName + "\",\"Metadata\":{},"
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessageTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessageTest.java
index f06de505d2..11b92dda20 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessageTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/exec/AgentMessageTest.java
@@ -1,10 +1,10 @@
package io.github.hectorvent.floci.services.ecs.exec;
+import io.github.hectorvent.floci.core.common.Digests;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@@ -45,7 +45,7 @@ class AgentMessageTest {
assertEquals(messageId.getMostSignificantBits(), buffer.getLong());
byte[] digest = new byte[32];
buffer.get(digest);
- assertArrayEquals(MessageDigest.getInstance("SHA-256").digest(payload), digest,
+ assertArrayEquals(Digests.sha256(payload), digest,
"the digest covers the payload");
assertEquals(AgentMessage.PAYLOAD_OUTPUT, buffer.getInt(), "payload type");
assertEquals(payload.length, buffer.getInt(), "payload length");
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java
index 893dfe32ef..69a783d7d3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.eks;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
@@ -117,8 +118,7 @@ class EksIrsaEndToEndIntegrationTest {
}
private static String base64Url(String value) {
- return Base64.getUrlEncoder().withoutPadding()
- .encodeToString(value.getBytes(StandardCharsets.UTF_8));
+ return Base64Url.encode(value);
}
private Response assumeRole(String token) {
@@ -236,7 +236,7 @@ class EksIrsaEndToEndIntegrationTest {
signature.initSign(clusterSigningKey());
signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
String token = header + "." + payload + "."
- + Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ + Base64Url.encode(signature.sign());
assumeRole(token)
.then()
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java
index 2a0a3f810e..ca08eef182 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
@@ -22,7 +23,6 @@ import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
-import java.util.Base64;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -105,13 +105,12 @@ class EksPodIdentityCredentialsControllerTest {
}
private static String signRs256(PrivateKey key, String claims) throws GeneralSecurityException {
- Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
- String header = enc.encodeToString("{\"alg\":\"RS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
- String payload = enc.encodeToString(claims.getBytes(StandardCharsets.UTF_8));
+ String header = Base64Url.encode("{\"alg\":\"RS256\",\"typ\":\"JWT\"}");
+ String payload = Base64Url.encode(claims);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(key);
sig.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
- return header + "." + payload + "." + enc.encodeToString(sig.sign());
+ return header + "." + payload + "." + Base64Url.encode(sig.sign());
}
private String buildToken(PrivateKey key, String iss, String aud, String sub, long expOffset) throws GeneralSecurityException {
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksRegistryHostsDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksRegistryHostsDockerIntegrationTest.java
index e1c11aea1e..71880a3d95 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksRegistryHostsDockerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksRegistryHostsDockerIntegrationTest.java
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
@@ -29,9 +30,7 @@ import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.util.Base64;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -289,13 +288,13 @@ class EksRegistryHostsDockerIntegrationTest {
gzip.write(tarBytes);
}
byte[] layerBytes = gzOut.toByteArray();
- String diffId = "sha256:" + sha256Hex(tarBytes);
- String layerDigest = "sha256:" + sha256Hex(layerBytes);
+ String diffId = "sha256:" + Digests.sha256Hex(tarBytes);
+ String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes);
byte[] configBytes = ("{\"architecture\":\"" + arch + "\",\"os\":\"linux\",\"config\":{},"
+ "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"" + diffId + "\"]}}")
.getBytes(StandardCharsets.UTF_8);
- String configDigest = "sha256:" + sha256Hex(configBytes);
+ String configDigest = "sha256:" + Digests.sha256Hex(configBytes);
uploadBlob(host, repo, layerDigest, layerBytes);
uploadBlob(host, repo, configDigest, configBytes);
@@ -405,10 +404,6 @@ class EksRegistryHostsDockerIntegrationTest {
.then().statusCode(201);
}
- private static String sha256Hex(byte[] data) throws Exception {
- return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data));
- }
-
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.java
index da17ef1c84..2c1032b9bf 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksTokenValidatorTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.eks;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
@@ -245,7 +246,6 @@ class EksTokenValidatorTest {
String encodedRequest = token.substring(prefix.length());
String request = new String(Base64.getUrlDecoder().decode(encodedRequest), StandardCharsets.UTF_8);
String tamperedRequest = request.replace(target, replacement);
- return prefix + Base64.getUrlEncoder().withoutPadding()
- .encodeToString(tamperedRequest.getBytes(StandardCharsets.UTF_8));
+ return prefix + Base64Url.encode(tamperedRequest);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsWebIdentityEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsWebIdentityEnforcementIntegrationTest.java
index 8c8be71133..8f56424373 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsWebIdentityEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsWebIdentityEnforcementIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
@@ -22,11 +23,8 @@ class StsWebIdentityEnforcementIntegrationTest {
@Test
void rejectsUnknownIssuerWhenIamEnforcementIsEnabled() {
- String header = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
- "{\"alg\":\"none\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
- String payload = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
- "{\"iss\":\"https://untrusted.example\",\"aud\":\"sts.amazonaws.com\"}"
- .getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ String header = Base64Url.encode("{\"alg\":\"none\"}");
+ String payload = Base64Url.encode("{\"iss\":\"https://untrusted.example\",\"aud\":\"sts.amazonaws.com\"}");
assumeRole(header + "." + payload + ".")
.then()
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java
index 5ce89d86f3..99a72c58e6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceCertificateIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iot;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.quarkus.test.junit.QuarkusTest;
@@ -16,13 +17,11 @@ import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
-import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
-import java.util.HexFormat;
import java.util.List;
import java.util.Map;
@@ -77,7 +76,7 @@ class IotDeviceCertificateIntegrationTest {
"AWS IoT-issued certificates all expire at the end of 2049, never past the CA");
assertTrue(!cert.getNotBefore().toInstant().isAfter(java.time.Instant.now()), "valid from issue time");
- String expectedId = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()));
+ String expectedId = Digests.sha256Hex(cert.getEncoded());
assertEquals(expectedId, body.getString("certificateId"), "AWS certificateId is sha256(DER), lowercase hex");
assertTrue(body.getString("certificateArn").endsWith(":cert/" + expectedId));
@@ -146,7 +145,7 @@ class IotDeviceCertificateIntegrationTest {
assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage(), "clientAuth");
assertEquals(-1, cert.getBasicConstraints());
assertEquals(expectedNotAfter(ca), cert.getNotAfter().toInstant());
- String expectedId = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()));
+ String expectedId = Digests.sha256Hex(cert.getEncoded());
assertEquals(expectedId, body.getString("certificateId"));
assertNull(body.get("keyPair"), "AWS never returns a private key for a CSR: the device holds it");
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingServiceTest.java
index 2c0dcb9730..37cd876551 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotFleetIndexingServiceTest.java
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration;
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.Field;
@@ -1212,8 +1213,7 @@ class IotFleetIndexingServiceTest {
@Test
void aTokenThisOperationCouldNotHaveIssuedIsInvalid() {
fleet();
- String bareThingName = Base64.getUrlEncoder().withoutPadding()
- .encodeToString("alpha-1".getBytes(StandardCharsets.UTF_8));
+ String bareThingName = Base64Url.encode("alpha-1");
for (String token : List.of("YQ", "", "AAAA", bareThingName)) {
assertSearchFails(query("*").put("nextToken", token), "InvalidRequestException", 400,
@@ -1222,10 +1222,8 @@ class IotFleetIndexingServiceTest {
String issued = search(query("thingName:alpha*").put("maxResults", 1)).nextToken();
String decoded = new String(Base64.getUrlDecoder().decode(issued), StandardCharsets.UTF_8);
- String edited = Base64.getUrlEncoder().withoutPadding()
- .encodeToString((decoded.substring(0, decoded.length() - 1) + "0").getBytes(StandardCharsets.UTF_8));
- String shortened = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(decoded.substring(0, decoded.length() - 1).getBytes(StandardCharsets.UTF_8));
+ String edited = Base64Url.encode(decoded.substring(0, decoded.length() - 1) + "0");
+ String shortened = Base64Url.encode(decoded.substring(0, decoded.length() - 1));
String truncated = issued.substring(0, issued.length() - 2);
for (String token : List.of(edited, shortened, truncated)) {
assertSearchFails(query("thingName:alpha*").put("nextToken", token), "InvalidRequestException", 400,
diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java
index 4e0f900e7f..054731895b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
@@ -1846,12 +1847,7 @@ class KmsServiceTest {
void signWithDigestMessageTypeMatchesRawSignature() {
KmsKey key = kmsService.createKey("rsa digest key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
byte[] message = "deterministic pkcs1".getBytes(StandardCharsets.UTF_8);
- byte[] digest;
- try {
- digest = MessageDigest.getInstance("SHA-256").digest(message);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
+ byte[] digest = Digests.sha256(message);
// PKCS#1 v1.5 is deterministic, so signing the digest (DIGEST) and signing the
// message (RAW) with the same algorithm must produce identical signatures.
@@ -1866,7 +1862,7 @@ class KmsServiceTest {
void signWithDigestMessageTypePssVerifiesWithExternalVerifier() throws Exception {
KmsKey key = kmsService.createKey("rsa pss digest key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
byte[] message = "floci kms pss round-trip".getBytes(StandardCharsets.UTF_8);
- byte[] digest = MessageDigest.getInstance("SHA-256").digest(message);
+ byte[] digest = Digests.sha256(message);
byte[] sig = kmsService.sign(key.getKeyId(), digest,
"RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION);
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java
index 94f969c68d..c3bd628be0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
+import io.github.hectorvent.floci.core.common.Digests;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -602,8 +603,7 @@ class LambdaIntegrationTest {
org.junit.jupiter.api.Assertions.assertEquals('K', pkg[1]);
// Byte-exact: downloaded package hashes to the stored CodeSha256.
- byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(pkg);
- String downloadedSha256 = Base64.getEncoder().encodeToString(digest);
+ String downloadedSha256 = Base64.getEncoder().encodeToString(Digests.sha256(pkg));
org.junit.jupiter.api.Assertions.assertEquals(expectedSha256, downloadedSha256,
"downloaded package must be byte-identical to the uploaded zip");
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListLayersParametersIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListLayersParametersIntegrationTest.java
index 8b1fe1169b..e1283bc67a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListLayersParametersIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListLayersParametersIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
+import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -235,8 +236,7 @@ class LambdaListLayersParametersIntegrationTest {
// as a cursor, which would silently skip or empty the page.
for (String forged : new String[] {"lp-alpha.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"lp-alpha.", ".signature", "lp-alpha"}) {
- String encoded = Base64.getUrlEncoder().withoutPadding()
- .encodeToString(forged.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ String encoded = Base64Url.encode(forged);
given()
.queryParam("CompatibleRuntime", PAGE_RUNTIME)
.queryParam("Marker", encoded)
@@ -268,8 +268,7 @@ class LambdaListLayersParametersIntegrationTest {
String spliced = LAYER_B + decoded.substring(decoded.lastIndexOf('.'));
given()
.queryParam("CompatibleRuntime", PAGE_RUNTIME)
- .queryParam("Marker", Base64.getUrlEncoder().withoutPadding()
- .encodeToString(spliced.getBytes(java.nio.charset.StandardCharsets.UTF_8)))
+ .queryParam("Marker", Base64Url.encode(spliced))
.when()
.get("/2018-10-31/layers")
.then()
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java
index 93a71a59d5..77733a034c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
@@ -20,7 +21,6 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -585,7 +585,7 @@ class S3AuthEnforcementIntegrationTest {
@Order(22)
void presignedRequestWithExplicitContentSha256IsAccepted() throws Exception {
String path = "/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY;
- String contentHash = sha256Hex("private body");
+ String contentHash = Digests.sha256Hex("private body");
String sig = presignedSignature("GET", path, "test", "test", "3600", contentHash);
given()
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
@@ -629,8 +629,8 @@ class S3AuthEnforcementIntegrationTest {
@Order(24)
void presignedRequestWithMismatchedContentSha256IsRejected() throws Exception {
String path = "/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY;
- String contentHash = sha256Hex("private body");
- String wrongHash = sha256Hex("wrong body");
+ String contentHash = Digests.sha256Hex("private body");
+ String wrongHash = Digests.sha256Hex("wrong body");
String sig = presignedSignature("GET", path, "test", "test", "3600", contentHash);
given()
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
@@ -1873,7 +1873,7 @@ class S3AuthEnforcementIntegrationTest {
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=deadbeef")
.header("x-amz-date", SIGNING_TIMESTAMP)
- .header("x-amz-content-sha256", sha256Hex("forged"))
+ .header("x-amz-content-sha256", Digests.sha256Hex("forged"))
.body("forged")
.when()
.put("/" + WRITE_BUCKET + "/" + key)
@@ -1904,7 +1904,7 @@ class S3AuthEnforcementIntegrationTest {
.body(containsString("SignatureDoesNotMatch"));
given()
- .filter(LOCAL_SIGNER.withContentSha256(sha256Hex("the body that was signed")))
+ .filter(LOCAL_SIGNER.withContentSha256(Digests.sha256Hex("the body that was signed")))
.body("a different body")
.when()
.put("/" + WRITE_BUCKET + "/" + key)
@@ -1935,7 +1935,7 @@ class S3AuthEnforcementIntegrationTest {
assertThat(putWithoutContentType(WRITE_BUCKET + "?versioning", suspend, LOCAL_SIGNER).statusCode(),
equalTo(200));
HttpResponse<String> mismatch = putWithoutContentType(WRITE_BUCKET + "?versioning", suspend,
- LOCAL_SIGNER.withContentSha256(sha256Hex("something else")));
+ LOCAL_SIGNER.withContentSha256(Digests.sha256Hex("something else")));
assertThat(mismatch.statusCode(), equalTo(400));
assertThat(mismatch.body(), containsString("XAmzContentSHA256Mismatch"));
@@ -1975,7 +1975,7 @@ class S3AuthEnforcementIntegrationTest {
given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=abc")
- .header("x-amz-content-sha256", sha256Hex(""))
+ .header("x-amz-content-sha256", Digests.sha256Hex(""))
.when()
.get(path)
.then()
@@ -1987,7 +1987,7 @@ class S3AuthEnforcementIntegrationTest {
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/s3/aws4_request")
.header("x-amz-date", SIGNING_TIMESTAMP)
- .header("x-amz-content-sha256", sha256Hex(""))
+ .header("x-amz-content-sha256", Digests.sha256Hex(""))
.when()
.get(path)
.then()
@@ -1998,7 +1998,7 @@ class S3AuthEnforcementIntegrationTest {
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/sqs/aws4_request, SignedHeaders=host;x-amz-date, Signature=abc")
.header("x-amz-date", SIGNING_TIMESTAMP)
- .header("x-amz-content-sha256", sha256Hex(""))
+ .header("x-amz-content-sha256", Digests.sha256Hex(""))
.when()
.get(path)
.then()
@@ -2214,7 +2214,7 @@ class S3AuthEnforcementIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ SIGNING_TIMESTAMP + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(secretKey, SIGNING_DATE, "us-east-1", "s3");
return hexEncode(hmacSha256(signingKey, stringToSign));
@@ -2238,11 +2238,6 @@ class S3AuthEnforcementIntegrationTest {
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) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3LeadingSlashKeyAuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3LeadingSlashKeyAuthEnforcementIntegrationTest.java
index 320561c33e..4b3c9b89f2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3LeadingSlashKeyAuthEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3LeadingSlashKeyAuthEnforcementIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
@@ -22,7 +23,6 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -240,7 +240,7 @@ class S3LeadingSlashKeyAuthEnforcementIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ timestamp + "\n"
+ credentialScope + "\n"
- + hex(MessageDigest.getInstance("SHA-256").digest(canonicalRequest.getBytes(StandardCharsets.UTF_8)));
+ + Digests.sha256Hex(canonicalRequest);
byte[] kDate = hmac(("AWS4test").getBytes(StandardCharsets.UTF_8), date);
byte[] kRegion = hmac(kDate, "us-east-1");
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java
index 23b7a30a68..806cb4475b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.s3.model.S3Checksum;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
@@ -11,7 +12,6 @@ import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -382,7 +382,7 @@ class S3PresignedChecksumIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] kDate = hmacSha256(("AWS4" + SECRET_KEY).getBytes(StandardCharsets.UTF_8), date);
byte[] kRegion = hmacSha256(kDate, "us-east-1");
@@ -413,11 +413,6 @@ class S3PresignedChecksumIntegrationTest {
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 hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedTaggingSigV4EnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedTaggingSigV4EnforcementIntegrationTest.java
index e5009846f4..b217f7a631 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedTaggingSigV4EnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedTaggingSigV4EnforcementIntegrationTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
@@ -10,7 +11,6 @@ import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -215,7 +215,7 @@ class S3PresignedTaggingSigV4EnforcementIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] kDate = hmacSha256(("AWS4" + SECRET_KEY).getBytes(StandardCharsets.UTF_8), date);
byte[] kRegion = hmacSha256(kDate, "us-east-1");
@@ -247,11 +247,6 @@ class S3PresignedTaggingSigV4EnforcementIntegrationTest {
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 hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java
index 2d3ab21773..06f3993168 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ValidateSignaturesIntegrationTest.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.s3;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.testing.MutableClock;
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
@@ -20,7 +22,6 @@ import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -424,12 +425,11 @@ class S3ValidateSignaturesIntegrationTest {
/** Runs the AWS Sign-In authorization-code flow through its consent page and returns the token response. */
private static Response signIn() throws Exception {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(SIGNIN_VERIFIER.getBytes(StandardCharsets.US_ASCII));
+ byte[] digest = Digests.sha256(SIGNIN_VERIFIER.getBytes(StandardCharsets.US_ASCII));
String consent = given()
.redirects().follow(false)
.queryParam("client_id", SIGNIN_CLIENT_ID)
- .queryParam("code_challenge", Base64.getUrlEncoder().withoutPadding().encodeToString(digest))
+ .queryParam("code_challenge", Base64Url.encode(digest))
.queryParam("code_challenge_method", "SHA-256")
.queryParam("redirect_uri", SIGNIN_REDIRECT_URI)
.queryParam("response_type", "code")
diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java
index a006ae4f50..6d782aea8e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.signin;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
@@ -8,8 +10,6 @@ import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.util.Base64;
import java.util.Map;
import java.util.UUID;
@@ -528,9 +528,7 @@ class SigninIntegrationTest {
}
private static String challenge(String verifier) throws Exception {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(verifier.getBytes(StandardCharsets.US_ASCII));
- return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+ return Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
}
private static Map<String, String> queryParams(String query) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java
index bf5f8181e9..e5325506a6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.signin;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.signin.model.TokenResult;
@@ -10,10 +12,8 @@ import org.junit.jupiter.api.Test;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
-import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@@ -464,9 +464,7 @@ class SigninServiceTest {
}
private static String challenge(String verifier) throws Exception {
- byte[] digest = MessageDigest.getInstance("SHA-256")
- .digest(verifier.getBytes(StandardCharsets.US_ASCII));
- return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+ return Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
}
private static Map<String, String> query(String redirect) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcIntegrationTest.java
index 8611400301..791b42675a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcIntegrationTest.java
@@ -2,12 +2,16 @@ package io.github.hectorvent.floci.services.ssooidc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
+import java.nio.charset.StandardCharsets;
+
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
@@ -179,7 +183,7 @@ class SsoOidcIntegrationTest {
ssoAdminService.putApplicationGrant(grant);
String verifier = "01234567890123456789012345678901234567890123456789";
- String challenge = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(sha256(verifier));
+ String challenge = Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
String code = ssoOidcService.createIamAuthorizationCode(applicationArn, redirectUri, challenge,
java.util.List.of(redirectUri)).code();
String body = "{\"clientId\":\"" + applicationArn + "\",\"grantType\":\"authorization_code\","
@@ -200,15 +204,6 @@ class SsoOidcIntegrationTest {
.body("awsAdditionalDetails.identityContext", org.hamcrest.Matchers.not(org.hamcrest.Matchers.blankOrNullString()));
}
- private static byte[] sha256(String value) {
- try {
- return java.security.MessageDigest.getInstance("SHA-256")
- .digest(value.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
- } catch (java.security.NoSuchAlgorithmException e) {
- throw new IllegalStateException(e);
- }
- }
-
@Test
void registerClientReturnsOidcErrorShape() {
given()
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcServiceTest.java
index 457ae79d64..526c8f577b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssooidc/SsoOidcServiceTest.java
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.ssooidc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ssooidc.model.AuthorizationCode;
import io.github.hectorvent.floci.services.ssooidc.model.DeviceAuthorization;
@@ -10,6 +12,7 @@ import io.github.hectorvent.floci.services.ssooidc.model.TokenSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -125,8 +128,7 @@ class SsoOidcServiceTest {
register.putArray("redirectUris").add("http://127.0.0.1:8400/callback");
RegisteredClient client = service.registerClient(register);
String verifier = "01234567890123456789012345678901234567890123456789";
- String challenge = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
- sha256(verifier));
+ String challenge = Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
AuthorizationCode code = service.createAuthorizationCode(client.clientId(),
"http://127.0.0.1:8400/callback", challenge);
@@ -173,14 +175,6 @@ class SsoOidcServiceTest {
assertOidcError("invalid_grant",
() -> service.createIamToken(exchange, sourceApplication, java.util.List.of("openid")));
}
- private static byte[] sha256(String value) {
- try {
- return java.security.MessageDigest.getInstance("SHA-256")
- .digest(value.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
- } catch (java.security.NoSuchAlgorithmException e) {
- throw new IllegalStateException(e);
- }
- }
@Test
void registerClientValidatesPublicClientAndGrantType() {
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java
index 5b07c81e6e..1138a8cb08 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/AppSyncRequestSigner.java
@@ -1,9 +1,10 @@
package io.github.hectorvent.floci.testutil;
+import io.github.hectorvent.floci.core.common.Digests;
+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -50,12 +51,12 @@ public final class AppSyncRequestSigner {
+ "x-amz-date:" + amzDate + "\n"
+ "\n"
+ signedHeaderNames + "\n"
- + sha256Hex(body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8));
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = deriveSigningKey(secretKey, scopeDate, region);
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
@@ -83,10 +84,6 @@ public final class AppSyncRequestSigner {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
- private static String sha256Hex(byte[] input) throws Exception {
- return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
- }
-
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java
index e25bec215f..931e71a968 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.testutil;
+import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
@@ -124,10 +125,10 @@ public final class AwsRequestSigner implements Filter {
+ S3RequestSigner.canonicalQueryString(uri.getRawQuery()) + "\n"
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
- + SigV4RequestValidator.sha256Hex(body);
+ + Digests.sha256Hex(body);
String credentialScope = scopeDate + "/us-east-1/" + service + "/aws4_request";
String stringToSign = ALGORITHM + "\n" + amzDate + "\n" + credentialScope + "\n"
- + SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scopeDate, "us-east-1", service);
String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/ExecuteApiRequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/ExecuteApiRequestSigner.java
index 515ad9621f..bba3338863 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/ExecuteApiRequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/ExecuteApiRequestSigner.java
@@ -1,9 +1,10 @@
package io.github.hectorvent.floci.testutil;
+import io.github.hectorvent.floci.core.common.Digests;
+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -68,7 +69,7 @@ public final class ExecuteApiRequestSigner {
+ "x-amz-date:" + amzDate + "\n"
+ "\n"
+ signedHeaderNames + "\n"
- + sha256Hex(body == null ? new byte[0] : body);
+ + Digests.sha256Hex(body == null ? new byte[0] : body);
String signature = sign(secretKey, scopeDate, region, credentialScope, amzDate, canonicalRequest);
@@ -134,7 +135,7 @@ public final class ExecuteApiRequestSigner {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = deriveSigningKey(secretKey, scopeDate, region);
return hexEncode(hmacSha256(signingKey, stringToSign));
}
@@ -178,10 +179,6 @@ public final class ExecuteApiRequestSigner {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
- private static String sha256Hex(byte[] input) throws Exception {
- return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
- }
-
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
index bb8c98cd0a..3bacf4a31e 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.testutil;
+import io.github.hectorvent.floci.core.common.Digests;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
@@ -11,7 +12,6 @@ import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -132,7 +132,7 @@ public final class S3RequestSigner implements Filter {
String scopeDate = amzDate.substring(0, 8);
String contentSha256 = contentSha256Override != null
? contentSha256Override
- : sha256Hex(body);
+ : Digests.sha256Hex(body);
List<String[]> headers = new ArrayList<>();
if (signHost) {
@@ -159,7 +159,7 @@ public final class S3RequestSigner implements Filter {
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String signature = signatureOverride != null
? signatureOverride
: hexEncode(hmacSha256(signingKey(scopeDate), stringToSign));
@@ -213,7 +213,7 @@ public final class S3RequestSigner implements Filter {
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String signature = signatureOverride != null
? signatureOverride
: hexEncode(hmacSha256(signingKey(scopeDate), stringToSign));
@@ -284,10 +284,6 @@ public final class S3RequestSigner implements Filter {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
- private static String sha256Hex(byte[] input) throws Exception {
- return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
- }
-
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
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 a080f8ff1f..c7672093c5 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/SigV4TokenTestHelper.java
@@ -1,14 +1,15 @@
package io.github.hectorvent.floci.testutil;
+import io.github.hectorvent.floci.core.common.Base64Url;
+import io.github.hectorvent.floci.core.common.Digests;
+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
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.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -156,7 +157,7 @@ public final class SigV4TokenTestHelper {
+ "host\n"
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
String stringToSign = "AWS4-HMAC-SHA256\n" + dateTime + "\n" + credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
String signature = hexEncode(hmacSha256(
deriveSigningKey(secretKey, date, "us-east-1", "rds-db"), stringToSign));
@@ -196,8 +197,7 @@ public final class SigV4TokenTestHelper {
String url = "https://" + signToken(host, null, accessKeyId, secretKey, "us-east-1", "sts",
timestamp, expiresSeconds, params,
Map.of("host", host, "x-k8s-aws-id", clusterName));
- return "k8s-aws-v1." + Base64.getUrlEncoder().withoutPadding()
- .encodeToString(url.getBytes(StandardCharsets.UTF_8));
+ return "k8s-aws-v1." + Base64Url.encode(url);
}
private static String signToken(
@@ -250,7 +250,7 @@ public final class SigV4TokenTestHelper {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ dateTime + "\n"
+ credentialScope + "\n"
- + sha256Hex(canonicalRequest);
+ + Digests.sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(secretKey, date, region, service);
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
@@ -299,11 +299,6 @@ public final class SigV4TokenTestHelper {
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) {
diff --git a/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java b/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java
index 26e923f895..9e2a6d3c8f 100644
--- a/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java
+++ b/src/test/java/io/github/hectorvent/floci/tools/ami/AmiImageToolTest.java
@@ -1,13 +1,12 @@
package io.github.hectorvent.floci.tools.ami;
+import io.github.hectorvent.floci.core.common.Digests;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.security.MessageDigest;
-import java.util.HexFormat;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -159,8 +158,6 @@ class AmiImageToolTest {
}
private static String sha256(Path path) throws Exception {
- MessageDigest digest = MessageDigest.getInstance("SHA-256");
- digest.update(Files.readAllBytes(path));
- return HexFormat.of().formatHex(digest.digest());
+ return Digests.sha256Hex(Files.readAllBytes(path));
}
}