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

* feat(cognito): register passkeys and sign in with WEB_AUTHN

* test(cognito): cover passkeys with the Java SDK

* docs(cognito): document passkey registration and sign-in

* fix(cognito): check passkey counters under the user lock and tighten passkey origins

* fix(cognito): turn passkey MFA on per user and page passkeys with a cursor

* fix(cognito): verify passkeys without webauthn4j and gate passkey MFA on tier

Drops the webauthn4j dependency and its native-image entries. Cognito
recognizes only ES256 and RS256 passkeys and does not enforce
attestation, so jackson-dataformat-cbor decodes the attestation object,
the authenticator data and the COSE key, and java.security checks the
signature. The attestation statement is no longer verified.

The helpers the verifier needs live in core.common, and the existing
copies across main and test code now call them:
- PublicKeys builds a public key from its raw components, for the JWT
  verifiers of API Gateway and Verified Permissions, SshPublicKeys, and
  the CloudFront and SES curve lookups.
- Digests.sha256 and Digests.sha256Hex replace every one-shot SHA-256
  digest and the private hex helpers built on one, including the two
  public sha256Hex methods on SigV4RequestValidator; incremental and
  streaming digests keep MessageDigest.
- Base64Url.encode, for bytes or the UTF-8 bytes of a string, replaces
  every unpadded base64url encode and the private helpers wrapping it.
- DomainNames.isWithin replaces the same-domain-or-subdomain check in
  SES, ACM, Route 53, the embedded DNS server, the TLS certificate
  manager and the Cognito message dispatcher.
Every replacement produces the same bytes as the code it replaces.

Turning passkey MFA on now also needs a pool in the Essentials tier or
higher, and in an optional-MFA pool a user with software-token MFA keeps
WEB_AUTHN when passkey MFA is on, as the AWS MFA table describes.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
outofplaceandPriamo authored and GitHub committed 2026-10-12 15:27:36 -04:00
1 parent 162ac6dea7
commit 5092713a6e
149 files changed
+3494 -919

No files matched your search

@@ -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());
}
}
@@ -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());
}
}
}
}
+59 -10
View File
@@ -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.
@@ -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);
}
@@ -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;
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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,
@@ -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);
}
}
@@ -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);
}
}
@@ -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. */
@@ -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) {
@@ -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);
}
/**
@@ -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;
}
}
@@ -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();
@@ -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) {
@@ -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) {
@@ -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);
}
/**
@@ -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) {
@@ -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(
@@ -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);
@@ -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) {
@@ -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() {
@@ -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;
@@ -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) {
@@ -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())
@@ -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() {
@@ -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);
@@ -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");
}
@@ -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) {
@@ -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();
}
}
@@ -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) {
@@ -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.
@@ -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);
}
}
}
@@ -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);
}
}
@@ -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;
}
@@ -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; }
@@ -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; }
}
@@ -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; }
}
@@ -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. */
@@ -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;
@@ -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) {
@@ -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
@@ -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.
@@ -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);
}
@@ -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}
}
@@ -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);
}
}
}
@@ -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);
@@ -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);
}
@@ -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.
@@ -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);
}
}
@@ -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);
@@ -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) {
@@ -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);
}
@@ -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(
@@ -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) {
@@ -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() {
@@ -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) {
@@ -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. */
@@ -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();
}
@@ -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) {
@@ -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());
@@ -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) {
@@ -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) {
@@ -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);
@@ -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;
@@ -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) {
@@ -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) {
@@ -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(); }
}
@@ -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}). */
@@ -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
@@ -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. */
@@ -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) {
@@ -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
@@ -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) {
@@ -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++) {
@@ -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.
@@ -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());
}
/**
@@ -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;
}
}
@@ -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) {
@@ -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);
}
}
@@ -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) {
@@ -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) {
@@ -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));
}
/**
@@ -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);
}
}
@@ -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) {
@@ -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) {
@@ -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 + ">.");
}
@@ -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) {
@@ -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);
}
@@ -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;
}
@@ -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) {
@@ -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) {
@@ -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) {
@@ -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);
@@ -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("é"));
}
}
@@ -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("é"));
}
}
@@ -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");
}
}
@@ -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"));
}
}
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more