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

@@ -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"));
}
}
@@ -17,7 +17,6 @@ import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -63,8 +62,7 @@ class WebIdentityTokenVerifierTest {
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(value.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(value);
}
/** Signs an arbitrary claim set, so tests can build tokens the production mint path never would. */
@@ -76,7 +74,7 @@ class WebIdentityTokenVerifierTest {
signature.initSign(privateKey);
signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
return header + "." + payload + "."
+ Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ Base64Url.encode(signature.sign());
}
@Test
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.core.common.auth;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
@@ -48,7 +49,7 @@ class SigV4RequestValidatorTest {
// This exact value is also hardcoded in validate()'s canonical request for the empty
// body ElastiCache/RDS presigned tokens always carry; this pins it independently.
assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
SigV4RequestValidator.sha256Hex(""));
Digests.sha256Hex(""));
}
@Test
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Digests;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@@ -19,8 +20,6 @@ import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
@@ -297,7 +296,7 @@ class DockerClientProducerTest {
Files.createDirectories(dockerConfigDir);
Files.writeString(dockerConfigDir.resolve("config.json"),
"{\"currentContext\":\"" + contextName + "\"}");
Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(sha256Hex(contextName));
Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(Digests.sha256Hex(contextName));
Files.createDirectories(metaDir);
Files.writeString(metaDir.resolve("meta.json"),
"{\"Name\":\"" + contextName + "\",\"Metadata\":{},"
@@ -305,20 +304,6 @@ class DockerClientProducerTest {
+ skipTlsVerify + "}}}");
}
private static String sha256Hex(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
hex.append(String.format("%02x", b));
}
return hex.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 algorithm not available", e);
}
}
/**
* When floci.docker.docker-host is at its default and DOCKER_HOST is unset, the endpoint of
* the active Docker context (e.g. Colima) is resolved from ~/.docker/config.json and its
@@ -571,7 +556,7 @@ class DockerClientProducerTest {
Path dockerConfigDir, String contextName, boolean withCa, boolean withCert, boolean withKey)
throws IOException {
Path tlsDir = dockerConfigDir.resolve("contexts").resolve("tls")
.resolve(sha256Hex(contextName)).resolve("docker");
.resolve(Digests.sha256Hex(contextName)).resolve("docker");
Files.createDirectories(tlsDir);
if (withCa) {
Files.writeString(tlsDir.resolve("ca.pem"), "-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----");
@@ -602,7 +587,7 @@ class DockerClientProducerTest {
assertEquals("tcp://remote-docker:2376", result.host());
assertTrue(result.tlsCertPath().isPresent(), "TLS material should be surfaced when present");
assertEquals(tempDir.resolve("contexts").resolve("tls").resolve(sha256Hex("remote-tls")).resolve("docker"),
assertEquals(tempDir.resolve("contexts").resolve("tls").resolve(Digests.sha256Hex("remote-tls")).resolve("docker"),
result.tlsCertPath().get());
assertFalse(result.skipTlsVerify(), "SkipTLSVerify defaults to false and should be reported as such");
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
@@ -294,7 +295,7 @@ class ExecuteApiSigV4AuthorizerTest {
byte[] signedBody = "{\"amount\":1}".getBytes();
Map<String, String> signed = new java.util.LinkedHashMap<>(ExecuteApiRequestSigner.signedHeaders(
"POST", PATH, Map.of(), HOST, signedBody, "test", "test", REGION, Instant.now()));
signed.put("x-amz-content-sha256", sha256Hex(signedBody));
signed.put("x-amz-content-sha256", Digests.sha256Hex(signedBody));
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"POST", headers(signed), uriInfo(PATH, null), "{\"amount\":9999}".getBytes(), null);
@@ -331,15 +332,6 @@ class ExecuteApiSigV4AuthorizerTest {
assertTrue(result.authorized(), String.valueOf(result.detail()));
}
private static String sha256Hex(byte[] input) throws Exception {
byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(input);
StringBuilder hex = new StringBuilder(digest.length * 2);
for (byte b : digest) {
hex.append(String.format("%02x", b));
}
return hex.toString();
}
private static HttpHeaders headers(Map<String, String> values) {
return headers(values, HOST);
}
@@ -1,11 +1,10 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.Base64Url;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -34,9 +33,8 @@ class JwtClaimsWireFormatTest {
}
private static String unsignedToken(String claimsJson) {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
String header = enc.encodeToString("{\"alg\":\"RS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
String payload = enc.encodeToString(claimsJson.getBytes(StandardCharsets.UTF_8));
String header = Base64Url.encode("{\"alg\":\"RS256\",\"typ\":\"JWT\"}");
String payload = Base64Url.encode(claimsJson);
return header + "." + payload + ".sig";
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
@@ -20,7 +21,6 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
@@ -259,14 +259,13 @@ class HttpApiJwtAuthorizerQuerystringTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String json) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(json.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(json);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -274,6 +273,6 @@ class HttpApiJwtAuthorizerQuerystringTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
return Base64Url.encode(bytes);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
@@ -269,15 +270,13 @@ class HttpApiJwtAuthorizerScopesTest {
// ──────────────────────────── Helpers ────────────────────────────
private static String signedToken(Map<String, Object> claims) throws Exception {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
String header = enc.encodeToString(
("{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"" + KEY_ID + "\"}").getBytes(StandardCharsets.UTF_8));
String payload = enc.encodeToString(MAPPER.writeValueAsBytes(claims));
String header = Base64Url.encode("{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"" + KEY_ID + "\"}");
String payload = Base64Url.encode(MAPPER.writeValueAsBytes(claims));
String signingInput = header + "." + payload;
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
return signingInput + "." + enc.encodeToString(signature.sign());
return signingInput + "." + Base64Url.encode(signature.sign());
}
private static long farFuture() {
@@ -289,7 +288,7 @@ class HttpApiJwtAuthorizerScopesTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
return Base64Url.encode(bytes);
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
@@ -20,7 +21,6 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
@@ -217,7 +217,7 @@ class HttpProxyJwtClaimsMappingIntegrationTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
@@ -229,8 +229,7 @@ class HttpProxyJwtClaimsMappingIntegrationTest {
}
private static String base64Url(String json) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(json.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(json);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -238,6 +237,6 @@ class HttpProxyJwtClaimsMappingIntegrationTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
return Base64Url.encode(bytes);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.Base64Url;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.junit.jupiter.api.AfterEach;
@@ -20,7 +21,6 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
@@ -310,13 +310,13 @@ class JwtSignatureVerifierTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String s) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(s.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(s);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -324,6 +324,6 @@ class JwtSignatureVerifierTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
return Base64Url.encode(bytes);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
@@ -190,11 +191,11 @@ class CognitoAuthValidatorTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(value);
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import org.junit.jupiter.api.AfterEach;
@@ -24,7 +25,6 @@ import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@@ -210,12 +210,12 @@ class OidcAuthValidatorTest {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(signingKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
String encodedSignature = Base64Url.encode(signature.sign());
return signingInput + "." + encodedSignature;
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(value);
}
private static String base64UrlUnsigned(BigInteger value) {
@@ -223,6 +223,6 @@ class OidcAuthValidatorTest {
if (bytes.length > 1 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
return Base64Url.encode(bytes);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
@@ -61,7 +62,7 @@ class CodeArtifactAssetPersistenceTest {
byte[] content = "hello world, this is the asset payload".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
String json = Files.readString(dir.resolve("codeartifact-package-versions.json"));
String base64Content = Base64.getEncoder().encodeToString(content);
@@ -76,7 +77,7 @@ class CodeArtifactAssetPersistenceTest {
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult published = first.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
CodeArtifactService restarted = newService(dir);
PackageVersionAssetResult result = restarted.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -122,11 +123,11 @@ class CodeArtifactAssetPersistenceTest {
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
first.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
CodeArtifactService restarted = newService(dir);
PublishPackageVersionResult result = restarted.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", result.packageVersion().getStatus());
assertEquals(1, result.packageVersion().getAssets().size());
@@ -139,12 +140,12 @@ class CodeArtifactAssetPersistenceTest {
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
first.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
CodeArtifactService restarted = newService(dir);
byte[] different = "different bytes".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> restarted.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "true", different));
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "true", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
}
@@ -163,7 +164,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -173,7 +174,7 @@ class CodeArtifactAssetPersistenceTest {
}
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", result.packageVersion().getStatus());
PackageVersionAssetResult fetched = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -194,7 +195,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -204,7 +205,7 @@ class CodeArtifactAssetPersistenceTest {
}
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", result.packageVersion().getStatus());
PackageVersionAssetResult fetched = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -226,7 +227,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -236,7 +237,7 @@ class CodeArtifactAssetPersistenceTest {
}
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", result.packageVersion().getStatus());
PackageVersionAssetResult fetched = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
@@ -263,7 +264,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
@@ -277,7 +278,7 @@ class CodeArtifactAssetPersistenceTest {
try {
List<LogRecord> records = LogCapture.capture(CodeArtifactService.class, () ->
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0",
"a.txt", sha256Hex(content), "true", content));
"a.txt", Digests.sha256Hex(content), "true", content));
assertTrue(records.stream().anyMatch(r -> r.getMessage() != null
&& r.getMessage().contains("Could not verify")
@@ -314,7 +315,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
assetFile = paths.filter(Files::isRegularFile).findFirst().orElseThrow();
@@ -323,7 +324,7 @@ class CodeArtifactAssetPersistenceTest {
assertNotNull(fileKeyBefore, "test filesystem must support file keys for this identity check to be meaningful");
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
Object fileKeyAfter = Files.readAttributes(assetFile, BasicFileAttributes.class).fileKey();
assertEquals(fileKeyBefore, fileKeyAfter, "an intact retry must not replace the backing file");
@@ -336,7 +337,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
Path assetFile;
try (Stream<Path> paths = Files.walk(dir.resolve("codeartifact-assets"))) {
assetFile = paths.filter(Files::isRegularFile).findFirst().orElseThrow();
@@ -345,7 +346,7 @@ class CodeArtifactAssetPersistenceTest {
assertNotNull(fileKeyBefore, "test filesystem must support file keys for this identity check to be meaningful");
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
Object fileKeyAfter = Files.readAttributes(assetFile, BasicFileAttributes.class).fileKey();
assertEquals(fileKeyBefore, fileKeyAfter, "an intact retry must not replace the backing file");
@@ -365,7 +366,7 @@ class CodeArtifactAssetPersistenceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "true", content);
Digests.sha256Hex(content), "true", content);
Path assetRoot = dir.resolve("codeartifact-assets");
try (Stream<Path> paths = Files.walk(assetRoot)) {
@@ -376,7 +377,7 @@ class CodeArtifactAssetPersistenceTest {
byte[] different = "different content".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "true", different));
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "true", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
}
@@ -400,9 +401,9 @@ class CodeArtifactAssetPersistenceTest {
byte[] contentA = "content of a".getBytes(StandardCharsets.UTF_8);
byte[] contentB = "content of b".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(contentA), "true", contentA);
Digests.sha256Hex(contentA), "true", contentA);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "b.txt",
sha256Hex(contentB), "true", contentB);
Digests.sha256Hex(contentB), "true", contentB);
Path assetFileA;
Path assetFileB;
@@ -448,7 +449,7 @@ class CodeArtifactAssetPersistenceTest {
for (String name : names) {
byte[] content = ("content of " + name).getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", longToken, longToken, longToken,
name, sha256Hex(content), "true", content);
name, Digests.sha256Hex(content), "true", content);
}
CodeArtifactService restarted = newService(dir);
@@ -488,12 +489,4 @@ class CodeArtifactAssetPersistenceTest {
backend.load();
return new AccountAwareStorageBackend<>(backend, null, ACCOUNT_ID);
}
private static String sha256Hex(byte[] content) {
try {
return io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator.sha256Hex(content);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -1,6 +1,6 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
@@ -147,7 +147,7 @@ class CodeArtifactIntegrationTest {
.body("{}").post("/v1/repository?domain=pkg-domain&repository=pkg-repo").then().statusCode(200);
byte[] content = "hello codeartifact".getBytes(StandardCharsets.UTF_8);
String sha256 = sha256Hex(content);
String sha256 = Digests.sha256Hex(content);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256)
.contentType("application/octet-stream").body(content)
@@ -189,7 +189,7 @@ class CodeArtifactIntegrationTest {
given().contentType("application/json").header("Authorization", AUTH)
.body("{}").post("/v1/repository?domain=describe-domain&repository=repo").then().statusCode(200);
byte[] content = "describe".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content))
given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
.contentType("application/octet-stream").body(content)
.post("/v1/package/version/publish?domain=describe-domain&repository=repo&format=generic"
+ "&namespace=ns&package=my-pkg&version=1.0.0&asset=a.txt")
@@ -218,7 +218,7 @@ class CodeArtifactIntegrationTest {
given().contentType("application/json").header("Authorization", AUTH)
.body("{}").post("/v1/repository?domain=delete-domain&repository=repo").then().statusCode(200);
byte[] content = "delete-me".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content))
given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
.contentType("application/octet-stream").body(content)
.post("/v1/package/version/publish?domain=delete-domain&repository=repo&format=generic"
+ "&namespace=ns&package=my-pkg&version=1.0.0&asset=a.txt")
@@ -274,7 +274,7 @@ class CodeArtifactIntegrationTest {
.body("package.originConfiguration.restrictions.upstream", equalTo("ALLOW"));
byte[] content = "blocked".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256Hex(content))
given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
.contentType("application/octet-stream").body(content)
.post("/v1/package/version/publish?domain=origin-config-domain&repository=repo&format=generic"
+ "&namespace=ns&package=never-published&version=1.0.0&asset=a.txt")
@@ -301,7 +301,7 @@ class CodeArtifactIntegrationTest {
.body("{}").post("/v1/repository?domain=unfinished-domain&repository=repo").then().statusCode(200);
byte[] content = "partial".getBytes(StandardCharsets.UTF_8);
String sha256 = sha256Hex(content);
String sha256 = Digests.sha256Hex(content);
given().header("Authorization", AUTH).header("x-amz-content-sha256", sha256)
.contentType("application/octet-stream").body(content)
@@ -363,12 +363,4 @@ class CodeArtifactIntegrationTest {
.then().statusCode(401)
.header("WWW-Authenticate", equalTo("Bearer"));
}
private static String sha256Hex(byte[] content) {
try {
return SigV4RequestValidator.sha256Hex(content);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -2,9 +2,9 @@ package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationToken;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
@@ -448,7 +448,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
"ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
"ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", published.packageVersion().getStatus());
}
@@ -769,7 +769,7 @@ class CodeArtifactServiceTest {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
String sha256 = sha256Hex(content);
String sha256 = Digests.sha256Hex(content);
PublishPackageVersionResult result = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
"my-ns", "my-pkg", "1.0.0", "asset.txt", sha256, "false", content);
@@ -814,7 +814,7 @@ class CodeArtifactServiceTest {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
String sha256 = sha256Hex(content);
String sha256 = Digests.sha256Hex(content);
// A newline here would land verbatim in the X-AssetName response header on GetPackageVersionAsset.
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
@@ -830,11 +830,11 @@ class CodeArtifactServiceTest {
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), "yes", content));
"repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), "yes", content));
assertEquals("ValidationException", e.getErrorCode());
PublishPackageVersionResult omitted = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), null, content);
null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), null, content);
assertEquals("Published", omitted.packageVersion().getStatus());
}
@@ -845,7 +845,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "npm", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), "false", content));
"repo", "npm", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ValidationException", e.getErrorCode());
}
@@ -855,7 +855,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"no-such-repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content), "false", content));
"no-such-repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@@ -866,7 +866,7 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException publishMissingDomain = assertThrows(AwsException.class, () -> service.publishPackageVersion(
REGION, null, null, "repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", sha256Hex(content),
REGION, null, null, "repo", "generic", null, "my-pkg", "1.0.0", "asset.txt", Digests.sha256Hex(content),
"false", content));
assertEquals("ValidationException", publishMissingDomain.getErrorCode());
assertEquals("domain is required.", publishMissingDomain.getMessage());
@@ -891,11 +891,11 @@ class CodeArtifactServiceTest {
byte[] second = "second".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult r1 = service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null,
"my-pkg", "1.0.0", "a.txt", sha256Hex(first), "true", first);
"my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(first), "true", first);
assertEquals("Unfinished", r1.packageVersion().getStatus());
PublishPackageVersionResult r2 = service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null,
"my-pkg", "1.0.0", "b.txt", sha256Hex(second), "false", second);
"my-pkg", "1.0.0", "b.txt", Digests.sha256Hex(second), "false", second);
assertEquals("Published", r2.packageVersion().getStatus());
assertEquals(2, r2.packageVersion().getAssets().size());
assertTrue(r2.packageVersion().getAssets().containsKey("a.txt"));
@@ -908,13 +908,13 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "same-bytes".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult first = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
// pv is the same mutable object across calls in this storage backend, so the revision has
// to be captured now, before the retry below has a chance to change it in place.
String firstRevision = first.packageVersion().getRevision();
PublishPackageVersionResult retry = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
assertEquals("Unfinished", retry.packageVersion().getStatus());
assertEquals(1, retry.packageVersion().getAssets().size());
@@ -933,13 +933,13 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "same-bytes".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult unfinished = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "true", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "true", content);
// pv is the same mutable object across calls in this storage backend, so this must be
// checked before the second call mutates it, not read back afterward.
assertEquals("Unfinished", unfinished.packageVersion().getStatus());
PublishPackageVersionResult finalized = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", finalized.packageVersion().getStatus());
assertTrue(finalized.packageVersion().getPublishedTime() != null);
@@ -952,10 +952,10 @@ class CodeArtifactServiceTest {
byte[] first = "first-bytes".getBytes(StandardCharsets.UTF_8);
byte[] different = "different-bytes".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(first), "true", first);
Digests.sha256Hex(first), "true", first);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "true", different));
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "true", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
assertEquals("asset", e.getExtendedData().get("resourceType"));
@@ -967,10 +967,10 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "b.txt", sha256Hex(content), "false", content));
"repo", "generic", null, "my-pkg", "1.0.0", "b.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("1.0.0", e.getExtendedData().get("resourceId"));
assertEquals("package-version", e.getExtendedData().get("resourceType"));
@@ -982,13 +982,13 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult first = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
// pv is the same mutable object across calls in this storage backend, so the revision has
// to be captured now, before the retry below has a chance to change it in place.
String firstRevision = first.packageVersion().getRevision();
PublishPackageVersionResult retry = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", retry.packageVersion().getStatus());
assertEquals(firstRevision, retry.packageVersion().getRevision());
@@ -1000,11 +1000,11 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
byte[] different = "y".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", sha256Hex(different), "false", different));
"repo", "generic", null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(different), "false", different));
assertEquals("ConflictException", e.getErrorCode());
assertEquals("a.txt", e.getExtendedData().get("resourceId"));
assertEquals("asset", e.getExtendedData().get("resourceType"));
@@ -1017,11 +1017,11 @@ class CodeArtifactServiceTest {
for (int i = 0; i < 350; i++) {
byte[] content = ("content-" + i).getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0",
"asset-" + i + ".txt", sha256Hex(content), "true", content);
"asset-" + i + ".txt", Digests.sha256Hex(content), "true", content);
}
byte[] oneMore = "one-more".getBytes(StandardCharsets.UTF_8);
AwsException e = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom", null,
"repo", "generic", null, "my-pkg", "1.0.0", "asset-350.txt", sha256Hex(oneMore), "true", oneMore));
"repo", "generic", null, "my-pkg", "1.0.0", "asset-350.txt", Digests.sha256Hex(oneMore), "true", oneMore));
assertEquals("ServiceQuotaExceededException", e.getErrorCode());
assertEquals("1.0.0", e.getExtendedData().get("resourceId"));
assertEquals("package-version", e.getExtendedData().get("resourceType"));
@@ -1029,7 +1029,7 @@ class CodeArtifactServiceTest {
// Re-publishing an asset name already on the version must not itself trip the cap.
byte[] resend = "content-0".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg", "1.0.0", "asset-0.txt",
sha256Hex(resend), "true", resend);
Digests.sha256Hex(resend), "true", resend);
}
@Test
@@ -1038,7 +1038,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
CodeArtifactPackageVersion pv = service.describePackageVersion(REGION, "dom", null, "repo", "generic", "ns",
"my-pkg", "1.0.0");
@@ -1056,9 +1056,9 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my::pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
CodeArtifactService.PackageDescription described = service.describePackage(REGION, "dom", null, "repo",
"generic", "ns", "my-pkg");
@@ -1199,7 +1199,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK",
"ALLOW");
@@ -1286,13 +1286,13 @@ class CodeArtifactServiceTest {
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
AwsException blocked = assertThrows(AwsException.class, () -> service.publishPackageVersion(REGION, "dom",
null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content));
null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content));
assertEquals("ConflictException", blocked.getErrorCode());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW",
"ALLOW");
PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
"ns", "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
"ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
assertEquals("Published", published.packageVersion().getStatus());
}
@@ -1334,9 +1334,9 @@ class CodeArtifactServiceTest {
byte[] secondContent = "second-package".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "a::b", "c", "1.0.0", "a.txt",
sha256Hex(firstContent), "false", firstContent);
Digests.sha256Hex(firstContent), "false", firstContent);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "a", "b::c", "1.0.0", "a.txt",
sha256Hex(secondContent), "false", secondContent);
Digests.sha256Hex(secondContent), "false", secondContent);
PackageVersionAssetResult first = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
"a::b", "c", "1.0.0", "a.txt", null);
@@ -1396,7 +1396,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "victim".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "a:b", "x", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
AwsException describeVersion = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION,
"dom", null, "repo", "generic", "a#cb", "x", "1.0.0"));
@@ -1413,11 +1413,11 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "2.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "other-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
CodeArtifactService.PackageDescription deleted = service.deletePackage(REGION, "dom", null, "repo",
"generic", "ns", "my-pkg");
@@ -1458,7 +1458,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "ALLOW",
"ALLOW");
@@ -1479,7 +1479,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "x".getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
sha256Hex(content), "false", content);
Digests.sha256Hex(content), "false", content);
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "BLOCK",
"BLOCK");
@@ -1638,7 +1638,7 @@ class CodeArtifactServiceTest {
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
byte[] content = "hello world".getBytes(StandardCharsets.UTF_8);
PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", sha256Hex(content), "false", content);
null, "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false", content);
PackageVersionAssetResult result = service.getPackageVersionAsset(REGION, "dom", null, "repo", "generic",
null, "my-pkg", "1.0.0", "a.txt", null);
@@ -1673,7 +1673,7 @@ class CodeArtifactServiceTest {
"com.example", "my-artifact", "1.0.0", "my-artifact-1.0.0.jar", null);
assertEquals("jar bytes", new String(result.asset().getContent(), StandardCharsets.UTF_8));
assertEquals(sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8)),
assertEquals(Digests.sha256Hex((repoId + "/com.example/my-artifact/1.0.0").getBytes(StandardCharsets.UTF_8)),
result.packageVersionRevision());
}
@@ -1808,7 +1808,7 @@ class CodeArtifactServiceTest {
go.await();
byte[] content = ("content-" + index).getBytes(StandardCharsets.UTF_8);
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", null, "my-pkg",
"1.0.0", "asset-" + index + ".txt", sha256Hex(content), "true", content);
"1.0.0", "asset-" + index + ".txt", Digests.sha256Hex(content), "true", content);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
@@ -1824,12 +1824,4 @@ class CodeArtifactServiceTest {
"my-pkg", "1.0.0");
assertEquals(assetCount, pv.getAssets().size());
}
private static String sha256Hex(byte[] content) {
try {
return SigV4RequestValidator.sha256Hex(content);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
import io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;
@@ -763,7 +764,7 @@ class CognitoOAuthControllerTest {
}
private static String jwtShape(String header, String signature) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes(StandardCharsets.UTF_8))
return Base64Url.encode(header)
+ ".payload." + signature;
}
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -5496,8 +5497,7 @@ class CognitoServiceTest {
otherPool.getId(), "other-client", false, false, List.of(), List.of());
String[] parts = valid.split("\\.");
String unsigned = Base64.getUrlEncoder().withoutPadding()
.encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8))
String unsigned = Base64Url.encode("{\"alg\":\"none\",\"typ\":\"JWT\"}")
+ "." + parts[1] + ".";
assertInvalidAccessToken(unsigned, "alg=none");
assertInvalidAccessToken(withClaim(valid, "username", "mallory"), "modified payload");
@@ -5628,8 +5628,7 @@ class CognitoServiceTest {
String[] parts = token.split("\\.");
Map<String, Object> claims = MAPPER.readValue(jwtPayload(token), new TypeReference<>() {});
claims.put(name, value);
String payload = Base64.getUrlEncoder().withoutPadding()
.encodeToString(MAPPER.writeValueAsBytes(claims));
String payload = Base64Url.encode(MAPPER.writeValueAsBytes(claims));
return parts[0] + "." + payload + "." + parts[2];
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
@@ -365,7 +366,6 @@ class CognitoUserInfoIntegrationTest {
}
private static String base64Url(String raw) {
return java.util.Base64.getUrlEncoder().withoutPadding()
.encodeToString(raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
return Base64Url.encode(raw);
}
}
@@ -0,0 +1,246 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Passkey registration and sign-in over the JSON 1.1 wire protocol. */
@QuarkusTest
class CognitoWebAuthnIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String PASSWORD = "Perm1234!";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void passkeyRegistrationAndSignInRoundTrip() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"PasskeyProtocolPool","UserPoolTier":"ESSENTIALS",
"Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","WEB_AUTHN"]}}}
""").path("UserPool").path("Id").asText();
JsonNode mfaConfig = cognitoJson("SetUserPoolMfaConfig", """
{"UserPoolId":"%s","MfaConfiguration":"OFF",
"WebAuthnConfiguration":{"RelyingPartyId":"localhost"}}
""".formatted(poolId));
assertEquals("localhost", mfaConfig.path("WebAuthnConfiguration").path("RelyingPartyId").asText());
assertEquals("preferred", mfaConfig.path("WebAuthnConfiguration").path("UserVerification").asText());
cognitoAction("GetUserPoolMfaConfig", """
{"UserPoolId":"%s"}
""".formatted(poolId))
.then().statusCode(200)
.body("WebAuthnConfiguration.RelyingPartyId", equalTo("localhost"))
.body("WebAuthnConfiguration", not(hasKey("FactorConfiguration")));
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"passkey-client",
"ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
String username = "passkey-" + UUID.randomUUID();
cognitoJson("AdminCreateUser", """
{"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS"}
""".formatted(poolId, username));
cognitoJson("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
""".formatted(poolId, username, PASSWORD));
String accessToken = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(clientId, username, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
JsonNode options = cognitoJson("StartWebAuthnRegistration", """
{"AccessToken":"%s"}
""".formatted(accessToken)).path("CredentialCreationOptions");
assertTrue(options.isObject(), "CredentialCreationOptions is a document");
assertEquals("localhost", options.path("rp").path("id").asText());
assertEquals(60000, options.path("timeout").asInt());
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
ObjectNode complete = JSON.createObjectNode();
complete.put("AccessToken", accessToken);
complete.set("Credential", authenticator.register(options, "packed"));
cognitoAction("CompleteWebAuthnRegistration", complete.toString()).then().statusCode(200);
cognitoAction("CompleteWebAuthnRegistration", complete.toString())
.then().statusCode(400).body("__type", equalTo("WebAuthnChallengeNotFoundException"));
cognitoAction("ListWebAuthnCredentials", """
{"AccessToken":"%s"}
""".formatted(accessToken))
.then().statusCode(200)
.body("Credentials", hasSize(1))
.body("Credentials[0].CredentialId", equalTo(authenticator.credentialId()))
.body("Credentials[0].RelyingPartyId", equalTo("localhost"))
.body("Credentials[0].AuthenticatorTransports", contains("internal", "hybrid"))
.body("$", not(hasKey("NextToken")));
cognitoAction("GetUserAuthFactors", """
{"AccessToken":"%s"}
""".formatted(accessToken))
.then().statusCode(200)
.body("ConfiguredUserAuthFactors", contains("PASSWORD", "WEB_AUTHN"));
JsonNode challenge = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_AUTH",
"AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"WEB_AUTHN"}}
""".formatted(clientId, username));
assertEquals("WEB_AUTHN", challenge.path("ChallengeName").asText());
String requestOptions = challenge.path("ChallengeParameters").path("CREDENTIAL_REQUEST_OPTIONS").asText();
ObjectNode respond = JSON.createObjectNode();
respond.put("ClientId", clientId);
respond.put("ChallengeName", "WEB_AUTHN");
respond.put("Session", challenge.path("Session").asText());
respond.putObject("ChallengeResponses")
.put("USERNAME", username)
.put("CREDENTIAL", authenticator.authenticate(requestOptions));
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond.toString());
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
cognitoAction("DeleteWebAuthnCredential", """
{"AccessToken":"%s","CredentialId":"%s"}
""".formatted(accessToken, authenticator.credentialId()))
.then().statusCode(200);
cognitoAction("ListWebAuthnCredentials", """
{"AccessToken":"%s"}
""".formatted(accessToken))
.then().statusCode(200)
.body("Credentials", empty());
cognitoAction("DeleteWebAuthnCredential", """
{"AccessToken":"%s","CredentialId":"%s"}
""".formatted(accessToken, authenticator.credentialId()))
.then().statusCode(400).body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void passkeyMfaIsTurnedOnPerUserWithWebAuthnMfaSettings() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"PasskeyMfaPool","UserPoolTier":"ESSENTIALS",
"Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","WEB_AUTHN"]}}}
""").path("UserPool").path("Id").asText();
cognitoJson("SetUserPoolMfaConfig", """
{"UserPoolId":"%s","MfaConfiguration":"OFF",
"WebAuthnConfiguration":{"RelyingPartyId":"localhost"}}
""".formatted(poolId));
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"passkey-mfa-client",
"ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
String username = "passkey-mfa-" + UUID.randomUUID();
cognitoJson("AdminCreateUser", """
{"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS"}
""".formatted(poolId, username));
cognitoJson("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
""".formatted(poolId, username, PASSWORD));
String accessToken = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(clientId, username, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
ObjectNode complete = JSON.createObjectNode();
complete.put("AccessToken", accessToken);
complete.set("Credential", authenticator.register(cognitoJson("StartWebAuthnRegistration", """
{"AccessToken":"%s"}
""".formatted(accessToken)).path("CredentialCreationOptions"), "none"));
cognitoAction("CompleteWebAuthnRegistration", complete.toString()).then().statusCode(200);
String turnOn = """
{"AccessToken":"%s","WebAuthnMfaSettings":{"Enabled":true}}
""".formatted(accessToken);
cognitoAction("SetUserMFAPreference", turnOn)
.then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
cognitoJson("SetUserPoolMfaConfig", """
{"UserPoolId":"%s","MfaConfiguration":"ON",
"SoftwareTokenMfaConfiguration":{"Enabled":true},
"WebAuthnConfiguration":{"RelyingPartyId":"localhost",
"FactorConfiguration":"MULTI_FACTOR_WITH_USER_VERIFICATION"}}
""".formatted(poolId));
String userAuth = """
{"ClientId":"%s","AuthFlow":"USER_AUTH","AuthParameters":{"USERNAME":"%s"}}
""".formatted(clientId, username);
cognitoAction("InitiateAuth", userAuth)
.then().statusCode(200)
.body("ChallengeName", equalTo("SELECT_CHALLENGE"))
.body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP"));
cognitoAction("SetUserMFAPreference", turnOn).then().statusCode(200);
JsonNode challenge = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_AUTH",
"AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"WEB_AUTHN"}}
""".formatted(clientId, username));
assertEquals("WEB_AUTHN", challenge.path("ChallengeName").asText());
String requestOptions = challenge.path("ChallengeParameters").path("CREDENTIAL_REQUEST_OPTIONS").asText();
assertEquals("required", JSON.readTree(requestOptions).path("userVerification").asText());
ObjectNode respond = JSON.createObjectNode();
respond.put("ClientId", clientId);
respond.put("ChallengeName", "WEB_AUTHN");
respond.put("Session", challenge.path("Session").asText());
respond.putObject("ChallengeResponses")
.put("USERNAME", username)
.put("CREDENTIAL", authenticator.authenticate(requestOptions));
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond.toString());
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
cognitoAction("AdminSetUserMFAPreference", """
{"UserPoolId":"%s","Username":"%s","WebAuthnMfaSettings":{"Enabled":false}}
""".formatted(poolId, username))
.then().statusCode(200);
cognitoAction("InitiateAuth", userAuth)
.then().statusCode(200)
.body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP"));
cognitoAction("ListWebAuthnCredentials", """
{"AccessToken":"%s","NextToken":"bm90LWEtY3Vyc29y"}
""".formatted(accessToken))
.then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
}
@Test
void passkeyActionsNeedPasskeysEnabledOnThePool() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"PasswordOnlyPool"}
""").path("UserPool").path("Id").asText();
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"password-client","ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
cognitoJson("AdminCreateUser", """
{"UserPoolId":"%s","Username":"no-passkeys","MessageAction":"SUPPRESS"}
""".formatted(poolId));
cognitoJson("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"no-passkeys","Password":"%s","Permanent":true}
""".formatted(poolId, PASSWORD));
String accessToken = cognitoJson("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"no-passkeys","PASSWORD":"%s"}}
""".formatted(clientId, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
cognitoAction("StartWebAuthnRegistration", """
{"AccessToken":"%s"}
""".formatted(accessToken))
.then().statusCode(400).body("__type", equalTo("WebAuthnNotEnabledException"));
cognitoAction("SetUserPoolMfaConfig", """
{"UserPoolId":"%s","MfaConfiguration":"OFF",
"WebAuthnConfiguration":{"RelyingPartyId":"localhost","UserVerification":"sometimes"}}
""".formatted(poolId))
.then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
}
}
@@ -0,0 +1,572 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.WebAuthnConfiguration;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class CognitoWebAuthnTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String USERNAME = "alice";
private static final String PASSWORD = "Perm1234!";
private static final String RP_ID = "localhost";
private static final String ORIGIN = "http://localhost:3000";
/** Leaves a factor's MFA settings as they are, so a call changes passkey MFA alone. */
private static final CognitoService.MfaSettingsUpdate UNCHANGED = CognitoService.MfaSettingsUpdate.NONE;
private CognitoService service;
private MutableClock clock;
private UserPool pool;
private UserPoolClient client;
@BeforeEach
void setUp() {
clock = new MutableClock();
service = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
"http://localhost:4566", "cloudfront.net",
new RegionResolver("us-east-1", "000000000000"), null, mock(AcmService.class),
null, null, null, clock);
pool = createPool(List.of("PASSWORD", "WEB_AUTHN"));
service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false, webAuthnConfiguration(RP_ID, null, null));
client = createClient(pool);
service.adminCreateUser(pool.getId(), USERNAME, Map.of("email", "alice@example.com"), null);
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, true);
}
@Test
void registeredPasskeySignsInThroughUserAuth() throws Exception {
String accessToken = accessToken();
JsonNode options = creationOptions(accessToken);
assertEquals(RP_ID, options.path("rp").path("id").asText());
assertEquals("required", options.path("authenticatorSelection").path("residentKey").asText());
assertEquals("preferred", options.path("authenticatorSelection").path("userVerification").asText());
assertEquals(List.of(-7, -257), List.of(options.path("pubKeyCredParams").get(0).path("alg").asInt(),
options.path("pubKeyCredParams").get(1).path("alg").asInt()));
String sub = service.adminGetUser(pool.getId(), USERNAME).getAttributes().get("sub");
assertEquals(Base64Url.encode(sub.getBytes()), options.path("user").path("id").asText());
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(options, "none"));
Map<String, Object> listed = service.listWebAuthnCredentials(accessToken, null, null);
List<?> credentials = (List<?>) listed.get("Credentials");
assertEquals(1, credentials.size());
Map<?, ?> description = (Map<?, ?>) credentials.get(0);
assertEquals(authenticator.credentialId(), description.get("CredentialId"));
assertEquals(RP_ID, description.get("RelyingPartyId"));
assertEquals("platform", description.get("AuthenticatorAttachment"));
assertEquals(List.of("internal", "hybrid"), description.get("AuthenticatorTransports"));
assertNotNull(description.get("FriendlyCredentialName"));
assertFalse(listed.containsKey("NextToken"));
Map<String, Object> challenge = userAuth("WEB_AUTHN");
assertEquals("WEB_AUTHN", challenge.get("ChallengeName"));
JsonNode requestOptions = JSON.readTree(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
assertEquals(RP_ID, requestOptions.path("rpId").asText());
assertEquals(authenticator.credentialId(), requestOptions.path("allowCredentials").get(0).path("id").asText());
assertEquals("preferred", requestOptions.path("userVerification").asText());
String session = (String) challenge.get("Session");
Map<String, String> answer = Map.of("USERNAME", USERNAME,
"CREDENTIAL", authenticator.authenticate(requestOptions.toString()));
Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", session, answer);
assertNotNull(((Map<?, ?>) signedIn.get("AuthenticationResult")).get("AccessToken"));
assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().get(0).getSignCount());
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", session, answer))
.getErrorCode());
}
@Test
void packedSelfAttestationWithRs256IsAccepted() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.rs256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken),
"packed"));
Map<String, Object> challenge = userAuth("WEB_AUTHN");
String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential))
.get("AuthenticationResult"));
}
@Test
void attestationStatementIsNotVerified() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN).corruptAttestation();
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken),
"packed"));
assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().size(),
"Cognito does not enforce attestation, so a statement that does not verify is not refused");
Map<String, Object> challenge = userAuth("WEB_AUTHN");
String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential))
.get("AuthenticationResult"));
}
@Test
void registrationRejectsCredentialsCognitoDoesNotAccept() throws Exception {
String accessToken = accessToken();
assertRegistrationFails("WebAuthnCredentialNotSupportedException", accessToken,
WebAuthnTestAuthenticator.es384(ORIGIN));
assertRegistrationFails("WebAuthnOriginNotAllowedException", accessToken,
WebAuthnTestAuthenticator.es256("https://evil.example"));
assertRegistrationFails("WebAuthnRelyingPartyMismatchException", accessToken,
WebAuthnTestAuthenticator.es256(ORIGIN).relyingPartyId("example.com"));
AwsException noChallenge = assertThrows(AwsException.class, () -> service.completeWebAuthnRegistration(
accessToken, WebAuthnTestAuthenticator.es256(ORIGIN).register(JSON.readTree(
"{\"challenge\":\"AAAA\",\"rp\":{\"id\":\"localhost\"}}"), "none")));
assertEquals("WebAuthnChallengeNotFoundException", noChallenge.getErrorCode());
assertTrue(service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().isEmpty());
}
@Test
void httpsSubdomainOriginsAreAllowedAndHttpOnlyForLocalhost() throws Exception {
service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false,
webAuthnConfiguration("example.com", null, null));
String accessToken = accessToken();
assertRegistrationFails("WebAuthnOriginNotAllowedException", accessToken,
WebAuthnTestAuthenticator.es256("http://app.example.com"));
service.completeWebAuthnRegistration(accessToken,
WebAuthnTestAuthenticator.es256("https://app.example.com").register(creationOptions(accessToken),
"none"));
assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().size());
}
@Test
void registrationChallengeExpiresAndBelongsToTheStartingClient() throws Exception {
String accessToken = accessToken();
JsonNode options = creationOptions(accessToken);
UserPoolClient other = createClient(pool);
String otherToken = (String) ((Map<?, ?>) service.initiateAuth(other.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)).get("AuthenticationResult")).get("AccessToken");
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
assertEquals("WebAuthnClientMismatchException", assertThrows(AwsException.class,
() -> service.completeWebAuthnRegistration(otherToken, authenticator.register(options, "none")))
.getErrorCode());
service.completeWebAuthnRegistration(accessToken, authenticator.register(options, "none"));
assertEquals(1, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().size());
JsonNode expiring = creationOptions(accessToken);
clock.advance(Duration.ofMinutes(6));
String laterToken = accessToken();
assertEquals("WebAuthnChallengeNotFoundException", assertThrows(AwsException.class,
() -> service.completeWebAuthnRegistration(laterToken,
WebAuthnTestAuthenticator.es256(ORIGIN).register(expiring, "none"))).getErrorCode());
}
@Test
void requiredUserVerificationRejectsAnAuthenticatorThatSkipsIt() throws Exception {
service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false,
webAuthnConfiguration(RP_ID, "required", null));
String accessToken = accessToken();
assertRegistrationFails("WebAuthnCredentialNotSupportedException", accessToken,
WebAuthnTestAuthenticator.es256(ORIGIN).userVerified(false));
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
authenticator.userVerified(false);
Map<String, Object> challenge = userAuth("WEB_AUTHN");
String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential)))
.getErrorCode());
}
@Test
void signInRejectsABadSignatureAndAnUnknownPasskey() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator registered = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, registered.register(creationOptions(accessToken), "none"));
Map<String, Object> challenge = userAuth("WEB_AUTHN");
ObjectNode tampered = (ObjectNode) JSON.readTree(
registered.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS")));
ObjectNode response = (ObjectNode) tampered.path("response");
byte[] signature = Base64.getUrlDecoder().decode(response.path("signature").asText());
signature[signature.length - 1] ^= 0x01;
response.put("signature", Base64Url.encode(signature));
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"),
Map.of("USERNAME", USERNAME, "CREDENTIAL", tampered.toString()))).getErrorCode());
Map<String, Object> retry = userAuth("WEB_AUTHN");
String unknown = WebAuthnTestAuthenticator.es256(ORIGIN)
.authenticate(challengeParameters(retry).get("CREDENTIAL_REQUEST_OPTIONS"));
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) retry.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", unknown)))
.getErrorCode());
}
@Test
void signInRejectsASignatureCounterThatDoesNotMoveForward() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
Map<String, Object> earlier = userAuth("WEB_AUTHN");
String earlierCredential = authenticator.authenticate(
challengeParameters(earlier).get("CREDENTIAL_REQUEST_OPTIONS"));
Map<String, Object> later = userAuth("WEB_AUTHN");
String laterCredential = authenticator.authenticate(
challengeParameters(later).get("CREDENTIAL_REQUEST_OPTIONS"));
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", (String) later.get("Session"),
Map.of("USERNAME", USERNAME, "CREDENTIAL", laterCredential)).get("AuthenticationResult"));
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) earlier.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", earlierCredential)))
.getErrorCode(), "a counter below the stored one suggests a cloned authenticator");
assertEquals(2, service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().get(0).getSignCount());
}
@Test
void selectChallengeOffersPasskeysOnceRegisteredAndDeletingRemovesThem() throws Exception {
String accessToken = accessToken();
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
Map<String, Object> select = userAuth(null);
assertEquals("SELECT_CHALLENGE", select.get("ChallengeName"));
assertEquals(List.of("PASSWORD", "PASSWORD_SRP", "WEB_AUTHN"), select.get("AvailableChallenges"));
assertEquals(List.of("PASSWORD", "WEB_AUTHN"),
service.getUserAuthFactors(accessToken).get("ConfiguredUserAuthFactors"));
Map<String, Object> chosen = service.respondToAuthChallenge(client.getClientId(), "SELECT_CHALLENGE",
(String) select.get("Session"), Map.of("USERNAME", USERNAME, "ANSWER", "WEB_AUTHN"));
assertEquals("WEB_AUTHN", chosen.get("ChallengeName"));
assertFalse(chosen.containsKey("AvailableChallenges"));
String credential = authenticator.authenticate(challengeParameters(chosen).get("CREDENTIAL_REQUEST_OPTIONS"));
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN", (String) chosen.get("Session"),
Map.of("USERNAME", USERNAME, "CREDENTIAL", credential)).get("AuthenticationResult"));
service.deleteWebAuthnCredential(accessToken, authenticator.credentialId());
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> service.deleteWebAuthnCredential(accessToken, authenticator.credentialId())).getErrorCode());
}
@Test
void poolsWithoutPasskeysOrARelyingPartyAreRefused() {
UserPool passwordOnly = createPool(List.of("PASSWORD"));
UserPoolClient passwordClient = createClient(passwordOnly);
service.adminCreateUser(passwordOnly.getId(), USERNAME, Map.of(), null);
service.adminSetUserPassword(passwordOnly.getId(), USERNAME, PASSWORD, true);
String passwordToken = accessToken(passwordClient);
assertEquals("WebAuthnNotEnabledException", assertThrows(AwsException.class,
() -> service.startWebAuthnRegistration(passwordToken)).getErrorCode());
UserPool unconfigured = createPool(List.of("PASSWORD", "WEB_AUTHN"));
UserPoolClient unconfiguredClient = createClient(unconfigured);
service.adminCreateUser(unconfigured.getId(), USERNAME, Map.of(), null);
service.adminSetUserPassword(unconfigured.getId(), USERNAME, PASSWORD, true);
String unconfiguredToken = accessToken(unconfiguredClient);
assertEquals("WebAuthnConfigurationMissingException", assertThrows(AwsException.class,
() -> service.startWebAuthnRegistration(unconfiguredToken)).getErrorCode());
service.createUserPoolDomain("passkeys-prefix", unconfigured.getId(), null, null);
Map<?, ?> options = (Map<?, ?>) service.startWebAuthnRegistration(unconfiguredToken)
.get("CredentialCreationOptions");
assertEquals("passkeys-prefix.auth.us-east-1.amazoncognito.com", ((Map<?, ?>) options.get("rp")).get("id"));
}
@Test
void requiredMfaOffersPasskeysOnlyToUsersWhoTurnedPasskeyMfaOn() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false, null);
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
assertEquals("InvalidParameterException", assertThrows(AwsException.class,
() -> service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true)).getErrorCode(),
"passkey MFA needs a pool whose passkeys can satisfy MFA");
assertFalse(service.adminGetUser(pool.getId(), USERNAME).isWebAuthnMfaEnabled());
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false,
webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"),
"the pool's FactorConfiguration alone does not let a passkey skip MFA");
assertEquals("SELECT_CHALLENGE", userAuth("WEB_AUTHN").get("ChallengeName"));
service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
assertTrue(service.adminGetUser(pool.getId(), USERNAME).isWebAuthnMfaEnabled());
Map<String, Object> unverified = userAuth("WEB_AUTHN");
String requestOptions = challengeParameters(unverified).get("CREDENTIAL_REQUEST_OPTIONS");
assertEquals("required", JSON.readTree(requestOptions).path("userVerification").asText(),
"a passkey standing in for required MFA must verify the user");
String withoutVerification = authenticator.userVerified(false).authenticate(requestOptions);
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) unverified.get("Session"),
Map.of("USERNAME", USERNAME, "CREDENTIAL", withoutVerification))).getErrorCode());
authenticator.userVerified(true);
Map<String, Object> challenge = userAuth("WEB_AUTHN");
assertEquals("WEB_AUTHN", challenge.get("ChallengeName"));
String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential));
assertNotNull(signedIn.get("AuthenticationResult"), "a verified passkey satisfies required MFA");
assertNull(signedIn.get("ChallengeName"));
service.adminSetUserMFAPreference(pool.getId(), USERNAME, UNCHANGED, UNCHANGED, false);
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"));
}
@Test
void passkeyMfaTurnedOffMidSignInLeavesMfaToBeDone() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
service.setUserPoolMfaConfig(pool.getId(), "ON", true, false,
webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
Map<String, Object> challenge = userAuth("WEB_AUTHN");
assertEquals("WEB_AUTHN", challenge.get("ChallengeName"));
String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
service.adminSetUserMFAPreference(pool.getId(), USERNAME, UNCHANGED, UNCHANGED, false);
Map<String, Object> answered = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential));
assertNull(answered.get("AuthenticationResult"), "the passkey no longer stands in for MFA");
assertEquals("MFA_SETUP", answered.get("ChallengeName"));
}
@Test
void optionalMfaAsksForUserVerificationOnlyFromUsersWithPasskeyMfa() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN).userVerified(false);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false,
webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
Map<String, Object> challenge = userAuth("WEB_AUTHN");
String requestOptions = challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS");
assertEquals("preferred", JSON.readTree(requestOptions).path("userVerification").asText());
assertNotNull(service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"),
Map.of("USERNAME", USERNAME, "CREDENTIAL", authenticator.authenticate(requestOptions)))
.get("AuthenticationResult"));
service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
Map<String, Object> mfaChallenge = userAuth("WEB_AUTHN");
String mfaOptions = challengeParameters(mfaChallenge).get("CREDENTIAL_REQUEST_OPTIONS");
assertEquals("required", JSON.readTree(mfaOptions).path("userVerification").asText());
String withoutVerification = authenticator.authenticate(mfaOptions);
assertEquals("NotAuthorizedException", assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) mfaChallenge.get("Session"),
Map.of("USERNAME", USERNAME, "CREDENTIAL", withoutVerification))).getErrorCode());
}
@Test
void optionalMfaKeepsPasskeysForTotpUsersWhosePasskeySatisfiesMfa() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false,
webAuthnConfiguration(RP_ID, "preferred", "MULTI_FACTOR_WITH_USER_VERIFICATION"));
String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
service.verifySoftwareToken(accessToken, null, CognitoTotp.code(secret, clock.instant()));
service.setUserMFAPreference(accessToken, UNCHANGED, new CognitoService.MfaSettingsUpdate(true, true));
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), userAuth(null).get("AvailableChallenges"),
"a user with MFA in an optional-MFA pool signs in with a password");
service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
assertEquals(List.of("PASSWORD", "PASSWORD_SRP", "WEB_AUTHN"), userAuth(null).get("AvailableChallenges"),
"a user-verified passkey satisfies MFA on its own");
Map<String, Object> challenge = userAuth("WEB_AUTHN");
String credential = authenticator.authenticate(challengeParameters(challenge).get("CREDENTIAL_REQUEST_OPTIONS"));
Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "WEB_AUTHN",
(String) challenge.get("Session"), Map.of("USERNAME", USERNAME, "CREDENTIAL", credential));
assertNotNull(signedIn.get("AuthenticationResult"));
assertNull(signedIn.get("ChallengeName"));
}
@Test
void passkeyMfaNeedsTheEssentialsTierOrHigher() {
UserPool lite = service.createUserPool(Map.of("PoolName", "LitePool", "UserPoolTier", "LITE"), "us-east-1");
service.setUserPoolMfaConfig(lite.getId(), "OFF", null, false,
webAuthnConfiguration(RP_ID, null, "MULTI_FACTOR_WITH_USER_VERIFICATION"));
service.adminCreateUser(lite.getId(), USERNAME, Map.of(), null);
AwsException refused = assertThrows(AwsException.class,
() -> service.adminSetUserMFAPreference(lite.getId(), USERNAME, UNCHANGED, UNCHANGED, true));
assertEquals("InvalidParameterException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("Essentials"), refused.getMessage());
assertFalse(service.adminGetUser(lite.getId(), USERNAME).isWebAuthnMfaEnabled());
service.adminSetUserMFAPreference(lite.getId(), USERNAME, UNCHANGED, UNCHANGED, false);
}
@Test
void userCanRegisterAtMostTwentyPasskeys() throws Exception {
String accessToken = accessToken();
for (int i = 0; i < CognitoWebAuthn.MAX_CREDENTIALS_PER_USER; i++) {
service.completeWebAuthnRegistration(accessToken,
WebAuthnTestAuthenticator.es256(ORIGIN).register(creationOptions(accessToken), "none"));
}
assertEquals("LimitExceededException", assertThrows(AwsException.class,
() -> service.startWebAuthnRegistration(accessToken)).getErrorCode());
Map<String, Object> firstPage = service.listWebAuthnCredentials(accessToken, 15, null);
assertEquals(15, ((List<?>) firstPage.get("Credentials")).size());
Map<String, Object> secondPage = service.listWebAuthnCredentials(accessToken, 15,
(String) firstPage.get("NextToken"));
assertEquals(5, ((List<?>) secondPage.get("Credentials")).size());
assertFalse(secondPage.containsKey("NextToken"));
}
@Test
void pagesListPasskeysOldestFirstAndSkipNoneWhenOneIsDeleted() throws Exception {
String accessToken = accessToken();
List<String> registered = new ArrayList<>();
for (int i = 0; i < 3; i++) {
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken),
"none"));
registered.add(authenticator.credentialId());
clock.advance(Duration.ofMillis(1));
}
Map<String, Object> firstPage = service.listWebAuthnCredentials(accessToken, 1, null);
assertEquals(List.of(registered.get(0)), credentialIds(firstPage));
service.deleteWebAuthnCredential(accessToken, registered.get(0));
Map<String, Object> secondPage = service.listWebAuthnCredentials(accessToken, 1,
(String) firstPage.get("NextToken"));
assertEquals(List.of(registered.get(1)), credentialIds(secondPage),
"deleting a listed passkey does not move the next page past one");
Map<String, Object> lastPage = service.listWebAuthnCredentials(accessToken, 1,
(String) secondPage.get("NextToken"));
assertEquals(List.of(registered.get(2)), credentialIds(lastPage));
assertFalse(lastPage.containsKey("NextToken"));
assertEquals(List.of(registered.get(1), registered.get(2)),
credentialIds(service.listWebAuthnCredentials(accessToken, 0, null)));
for (String token : List.of("not-a-token!", Base64.getUrlEncoder().encodeToString("ListUsers:x".getBytes()))) {
assertEquals("InvalidParameterException", assertThrows(AwsException.class,
() -> service.listWebAuthnCredentials(accessToken, null, token)).getErrorCode());
}
AwsException negative = assertThrows(AwsException.class,
() -> service.listWebAuthnCredentials(accessToken, -1, null));
assertTrue(negative.getMessage().endsWith("Member must have value greater than or equal to 0"),
negative.getMessage());
}
@Test
void passkeysSurviveUserSerialization() throws Exception {
String accessToken = accessToken();
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256(ORIGIN);
service.completeWebAuthnRegistration(accessToken, authenticator.register(creationOptions(accessToken), "none"));
CognitoUser restored = JSON.readValue(
JSON.writeValueAsBytes(service.adminGetUser(pool.getId(), USERNAME)), CognitoUser.class);
assertEquals(authenticator.credentialId(), restored.getWebAuthnCredentials().get(0).getCredentialId());
assertEquals(service.adminGetUser(pool.getId(), USERNAME).getWebAuthnCredentials().get(0)
.getAttestedCredentialData(), restored.getWebAuthnCredentials().get(0).getAttestedCredentialData());
service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false,
webAuthnConfiguration(RP_ID, null, "MULTI_FACTOR_WITH_USER_VERIFICATION"));
service.setUserMFAPreference(accessToken, UNCHANGED, UNCHANGED, true);
assertTrue(JSON.readValue(JSON.writeValueAsBytes(service.adminGetUser(pool.getId(), USERNAME)),
CognitoUser.class).isWebAuthnMfaEnabled());
}
private void assertRegistrationFails(String errorCode, String accessToken, WebAuthnTestAuthenticator authenticator)
throws Exception {
JsonNode options = creationOptions(accessToken);
Executable complete = () -> service.completeWebAuthnRegistration(accessToken,
authenticator.register(options, "none"));
assertEquals(errorCode, assertThrows(AwsException.class, complete).getErrorCode());
}
private static List<String> credentialIds(Map<String, Object> page) {
return ((List<?>) page.get("Credentials")).stream()
.map(description -> (String) ((Map<?, ?>) description).get("CredentialId"))
.toList();
}
private JsonNode creationOptions(String accessToken) {
return JSON.valueToTree(service.startWebAuthnRegistration(accessToken).get("CredentialCreationOptions"));
}
private Map<String, Object> userAuth(String preferredChallenge) {
Map<String, String> params = preferredChallenge == null
? Map.of("USERNAME", USERNAME)
: Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", preferredChallenge);
return service.initiateAuth(client.getClientId(), "USER_AUTH", params);
}
@SuppressWarnings("unchecked")
private static Map<String, String> challengeParameters(Map<String, Object> challenge) {
return (Map<String, String>) challenge.get("ChallengeParameters");
}
private String accessToken() {
return accessToken(client);
}
private String accessToken(UserPoolClient appClient) {
return (String) ((Map<?, ?>) service.initiateAuth(appClient.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)).get("AuthenticationResult")).get("AccessToken");
}
private UserPool createPool(List<String> allowedFirstAuthFactors) {
return service.createUserPool(Map.of("PoolName", "PasskeyPool",
"Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", allowedFirstAuthFactors))),
"us-east-1");
}
private UserPoolClient createClient(UserPool userPool) {
UserPoolClient appClient = service.createUserPoolClient(userPool.getId(), "passkey-client", false, false,
List.of(), List.of());
appClient.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_AUTH"));
return appClient;
}
private static WebAuthnConfiguration webAuthnConfiguration(String relyingPartyId, String userVerification,
String factorConfiguration) {
WebAuthnConfiguration configuration = new WebAuthnConfiguration();
configuration.setRelyingPartyId(relyingPartyId);
configuration.setUserVerification(userVerification);
configuration.setFactorConfiguration(factorConfiguration);
return configuration;
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
@@ -10,7 +11,6 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.Base64;
import java.util.UUID;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
@@ -266,6 +266,6 @@ class GlobalSignOutIntegrationTest {
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(value.getBytes());
return Base64Url.encode(value.getBytes());
}
}
@@ -0,0 +1,266 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.util.Arrays;
import java.util.UUID;
/**
* A software passkey authenticator for tests, standing in for a browser and its authenticator:
* it answers creation options with a {@code RegistrationResponseJSON} ({@code none} or
* {@code packed} self attestation) and request options with an {@code AuthenticationResponseJSON}.
*/
final class WebAuthnTestAuthenticator {
private static final ObjectMapper JSON = new ObjectMapper();
private static final byte FLAG_UP = 0x01;
private static final byte FLAG_UV = 0x04;
private static final byte FLAG_AT = 0x40;
private final String origin;
private final KeyPair keyPair;
private final long algorithm;
private final String signatureAlgorithm;
private final byte[] credentialId = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
private String relyingPartyIdOverride;
private boolean userVerified = true;
private boolean corruptAttestation;
private long signCount;
private WebAuthnTestAuthenticator(String origin, KeyPair keyPair, long algorithm, String signatureAlgorithm) {
this.origin = origin;
this.keyPair = keyPair;
this.algorithm = algorithm;
this.signatureAlgorithm = signatureAlgorithm;
}
static WebAuthnTestAuthenticator es256(String origin) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec("secp256r1"));
return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -7, "SHA256withECDSA");
}
static WebAuthnTestAuthenticator es384(String origin) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec("secp384r1"));
return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -35, "SHA384withECDSA");
}
static WebAuthnTestAuthenticator rs256(String origin) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -257, "SHA256withRSA");
}
/** Claims {@code relyingPartyId} instead of the one the options name. */
WebAuthnTestAuthenticator relyingPartyId(String relyingPartyId) {
this.relyingPartyIdOverride = relyingPartyId;
return this;
}
WebAuthnTestAuthenticator userVerified(boolean userVerified) {
this.userVerified = userVerified;
return this;
}
/** Signs a {@code packed} attestation statement over the wrong data. */
WebAuthnTestAuthenticator corruptAttestation() {
this.corruptAttestation = true;
return this;
}
String credentialId() {
return Base64Url.encode(credentialId);
}
ObjectNode register(JsonNode creationOptions, String format) throws Exception {
String relyingPartyId = relyingPartyIdOverride != null
? relyingPartyIdOverride : creationOptions.path("rp").path("id").asText();
byte[] clientData = clientData("webauthn.create", creationOptions.path("challenge").asText());
ByteArrayOutputStream authData = new ByteArrayOutputStream();
authData.write(Digests.sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)));
authData.write(FLAG_UP | FLAG_AT | (userVerified ? FLAG_UV : 0));
authData.write(ByteBuffer.allocate(4).putInt((int) signCount).array());
authData.write(new byte[16]);
authData.write(ByteBuffer.allocate(2).putShort((short) credentialId.length).array());
authData.write(credentialId);
authData.write(coseKey());
byte[] authenticatorData = authData.toByteArray();
Cbor statement = new Cbor();
if ("packed".equals(format)) {
byte[] signed = concat(authenticatorData, Digests.sha256(clientData));
if (corruptAttestation) {
signed[0] ^= 0x01;
}
statement.map(2).text("alg").integer(algorithm).text("sig").bytes(sign(signed));
} else {
statement.map(0);
}
byte[] attestationObject = new Cbor().map(3)
.text("fmt").text(format)
.text("attStmt").raw(statement.toByteArray())
.text("authData").bytes(authenticatorData)
.toByteArray();
ObjectNode credential = JSON.createObjectNode();
credential.put("id", credentialId());
credential.put("rawId", credentialId());
credential.put("type", "public-key");
credential.put("authenticatorAttachment", "platform");
credential.putObject("clientExtensionResults");
ObjectNode response = credential.putObject("response");
response.put("clientDataJSON", Base64Url.encode(clientData));
response.put("attestationObject", Base64Url.encode(attestationObject));
response.putArray("transports").add("internal").add("hybrid");
return credential;
}
String authenticate(String requestOptionsJson) throws Exception {
JsonNode options = JSON.readTree(requestOptionsJson);
String relyingPartyId = relyingPartyIdOverride != null ? relyingPartyIdOverride : options.path("rpId").asText();
byte[] clientData = clientData("webauthn.get", options.path("challenge").asText());
signCount++;
byte[] authenticatorData = concat(Digests.sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)),
new byte[] {(byte) (FLAG_UP | (userVerified ? FLAG_UV : 0))},
ByteBuffer.allocate(4).putInt((int) signCount).array());
ObjectNode credential = JSON.createObjectNode();
credential.put("id", credentialId());
credential.put("rawId", credentialId());
credential.put("type", "public-key");
credential.put("authenticatorAttachment", "platform");
credential.putObject("clientExtensionResults");
ObjectNode response = credential.putObject("response");
response.put("authenticatorData", Base64Url.encode(authenticatorData));
response.put("clientDataJSON", Base64Url.encode(clientData));
response.put("signature", Base64Url.encode(sign(concat(authenticatorData, Digests.sha256(clientData)))));
return JSON.writeValueAsString(credential);
}
private byte[] clientData(String type, String challenge) throws Exception {
ObjectNode clientData = JSON.createObjectNode();
clientData.put("type", type);
clientData.put("challenge", challenge);
clientData.put("origin", origin);
clientData.put("crossOrigin", false);
return JSON.writeValueAsBytes(clientData);
}
private byte[] coseKey() {
if (keyPair.getPublic() instanceof RSAPublicKey rsa) {
return new Cbor().map(4)
.integer(1).integer(3)
.integer(3).integer(algorithm)
.integer(-1).bytes(unsigned(rsa.getModulus()))
.integer(-2).bytes(unsigned(rsa.getPublicExponent()))
.toByteArray();
}
ECPublicKey ec = (ECPublicKey) keyPair.getPublic();
int size = algorithm == -35 ? 48 : 32;
return new Cbor().map(5)
.integer(1).integer(2)
.integer(3).integer(algorithm)
.integer(-1).integer(algorithm == -35 ? 2 : 1)
.integer(-2).bytes(fixed(ec.getW().getAffineX(), size))
.integer(-3).bytes(fixed(ec.getW().getAffineY(), size))
.toByteArray();
}
private byte[] sign(byte[] data) throws Exception {
Signature signature = Signature.getInstance(signatureAlgorithm);
signature.initSign(keyPair.getPrivate());
signature.update(data);
return signature.sign();
}
private static byte[] concat(byte[]... parts) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (byte[] part : parts) {
out.writeBytes(part);
}
return out.toByteArray();
}
private static byte[] unsigned(BigInteger value) {
byte[] bytes = value.toByteArray();
return bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes;
}
private static byte[] fixed(BigInteger value, int size) {
byte[] bytes = unsigned(value);
byte[] padded = new byte[size];
System.arraycopy(bytes, 0, padded, size - bytes.length, bytes.length);
return padded;
}
/** The few CBOR items an attestation object and a COSE key need. */
private static final class Cbor {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
Cbor map(int entries) {
head(5, entries);
return this;
}
Cbor text(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
head(3, bytes.length);
out.writeBytes(bytes);
return this;
}
Cbor bytes(byte[] value) {
head(2, value.length);
out.writeBytes(value);
return this;
}
Cbor integer(long value) {
if (value >= 0) {
head(0, value);
} else {
head(1, -1 - value);
}
return this;
}
Cbor raw(byte[] encoded) {
out.writeBytes(encoded);
return this;
}
byte[] toByteArray() {
return out.toByteArray();
}
private void head(int majorType, long value) {
int major = majorType << 5;
if (value < 24) {
out.write(major | (int) value);
} else if (value < 0x100) {
out.write(major | 24);
out.write((int) value);
} else if (value < 0x10000) {
out.write(major | 25);
out.writeBytes(ByteBuffer.allocate(2).putShort((short) value).array());
} else {
out.write(major | 26);
out.writeBytes(ByteBuffer.allocate(4).putInt((int) value).array());
}
}
}
}
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
@@ -237,10 +238,10 @@ class DynamoDbLocalClientTest {
+ "x-amz-date:" + amzDate + "\n"
+ "x-amz-target:" + headers.getFirst("X-Amz-Target") + "\n\n"
+ "content-type;host;x-amz-date;x-amz-target\n"
+ SigV4RequestValidator.sha256Hex(request.body());
+ Digests.sha256Hex(request.body());
String credentialScope = date + "/eu-west-1/dynamodb/aws4_request";
String toSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
+ SigV4RequestValidator.sha256Hex(canonical);
+ Digests.sha256Hex(canonical);
byte[] key = SigV4RequestValidator.deriveSigningKey("floci", date, "eu-west-1", "dynamodb");
return SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(key, toSign));
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.RegisterTaskDefinitionRequest;
@@ -14,11 +15,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -463,8 +461,7 @@ class EcsJsonHandlerVolumesTest {
private static void writeContextFixture(Path dockerConfigDir, String contextName, String host) throws Exception {
Files.createDirectories(dockerConfigDir);
Files.writeString(dockerConfigDir.resolve("config.json"), "{\"currentContext\":\"" + contextName + "\"}");
byte[] nameHash = MessageDigest.getInstance("SHA-256").digest(contextName.getBytes(StandardCharsets.UTF_8));
Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(HexFormat.of().formatHex(nameHash));
Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(Digests.sha256Hex(contextName));
Files.createDirectories(metaDir);
Files.writeString(metaDir.resolve("meta.json"),
"{\"Name\":\"" + contextName + "\",\"Metadata\":{},"
@@ -1,10 +1,10 @@
package io.github.hectorvent.floci.services.ecs.exec;
import io.github.hectorvent.floci.core.common.Digests;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@@ -45,7 +45,7 @@ class AgentMessageTest {
assertEquals(messageId.getMostSignificantBits(), buffer.getLong());
byte[] digest = new byte[32];
buffer.get(digest);
assertArrayEquals(MessageDigest.getInstance("SHA-256").digest(payload), digest,
assertArrayEquals(Digests.sha256(payload), digest,
"the digest covers the payload");
assertEquals(AgentMessage.PAYLOAD_OUTPUT, buffer.getInt(), "payload type");
assertEquals(payload.length, buffer.getInt(), "payload length");
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
@@ -117,8 +118,7 @@ class EksIrsaEndToEndIntegrationTest {
}
private static String base64Url(String value) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(value.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(value);
}
private Response assumeRole(String token) {
@@ -236,7 +236,7 @@ class EksIrsaEndToEndIntegrationTest {
signature.initSign(clusterSigningKey());
signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
String token = header + "." + payload + "."
+ Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
+ Base64Url.encode(signature.sign());
assumeRole(token)
.then()
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
@@ -22,7 +23,6 @@ import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.util.Base64;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -105,13 +105,12 @@ class EksPodIdentityCredentialsControllerTest {
}
private static String signRs256(PrivateKey key, String claims) throws GeneralSecurityException {
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
String header = enc.encodeToString("{\"alg\":\"RS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8));
String payload = enc.encodeToString(claims.getBytes(StandardCharsets.UTF_8));
String header = Base64Url.encode("{\"alg\":\"RS256\",\"typ\":\"JWT\"}");
String payload = Base64Url.encode(claims);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(key);
sig.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
return header + "." + payload + "." + enc.encodeToString(sig.sign());
return header + "." + payload + "." + Base64Url.encode(sig.sign());
}
private String buildToken(PrivateKey key, String iss, String aud, String sub, long expOffset) throws GeneralSecurityException {
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
@@ -29,9 +30,7 @@ import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -289,13 +288,13 @@ class EksRegistryHostsDockerIntegrationTest {
gzip.write(tarBytes);
}
byte[] layerBytes = gzOut.toByteArray();
String diffId = "sha256:" + sha256Hex(tarBytes);
String layerDigest = "sha256:" + sha256Hex(layerBytes);
String diffId = "sha256:" + Digests.sha256Hex(tarBytes);
String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes);
byte[] configBytes = ("{\"architecture\":\"" + arch + "\",\"os\":\"linux\",\"config\":{},"
+ "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"" + diffId + "\"]}}")
.getBytes(StandardCharsets.UTF_8);
String configDigest = "sha256:" + sha256Hex(configBytes);
String configDigest = "sha256:" + Digests.sha256Hex(configBytes);
uploadBlob(host, repo, layerDigest, layerBytes);
uploadBlob(host, repo, configDigest, configBytes);
@@ -405,10 +404,6 @@ class EksRegistryHostsDockerIntegrationTest {
.then().statusCode(201);
}
private static String sha256Hex(byte[] data) throws Exception {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data));
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
@@ -245,7 +246,6 @@ class EksTokenValidatorTest {
String encodedRequest = token.substring(prefix.length());
String request = new String(Base64.getUrlDecoder().decode(encodedRequest), StandardCharsets.UTF_8);
String tamperedRequest = request.replace(target, replacement);
return prefix + Base64.getUrlEncoder().withoutPadding()
.encodeToString(tamperedRequest.getBytes(StandardCharsets.UTF_8));
return prefix + Base64Url.encode(tamperedRequest);
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
@@ -22,11 +23,8 @@ class StsWebIdentityEnforcementIntegrationTest {
@Test
void rejectsUnknownIssuerWhenIamEnforcementIsEnabled() {
String header = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
"{\"alg\":\"none\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
String payload = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
"{\"iss\":\"https://untrusted.example\",\"aud\":\"sts.amazonaws.com\"}"
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String header = Base64Url.encode("{\"alg\":\"none\"}");
String payload = Base64Url.encode("{\"iss\":\"https://untrusted.example\",\"aud\":\"sts.amazonaws.com\"}");
assumeRole(header + "." + payload + ".")
.then()
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.quarkus.test.junit.QuarkusTest;
@@ -16,13 +17,11 @@ import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
@@ -77,7 +76,7 @@ class IotDeviceCertificateIntegrationTest {
"AWS IoT-issued certificates all expire at the end of 2049, never past the CA");
assertTrue(!cert.getNotBefore().toInstant().isAfter(java.time.Instant.now()), "valid from issue time");
String expectedId = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()));
String expectedId = Digests.sha256Hex(cert.getEncoded());
assertEquals(expectedId, body.getString("certificateId"), "AWS certificateId is sha256(DER), lowercase hex");
assertTrue(body.getString("certificateArn").endsWith(":cert/" + expectedId));
@@ -146,7 +145,7 @@ class IotDeviceCertificateIntegrationTest {
assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage(), "clientAuth");
assertEquals(-1, cert.getBasicConstraints());
assertEquals(expectedNotAfter(ca), cert.getNotAfter().toInstant());
String expectedId = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(cert.getEncoded()));
String expectedId = Digests.sha256Hex(cert.getEncoded());
assertEquals(expectedId, body.getString("certificateId"));
assertNull(body.get("keyPair"), "AWS never returns a private key for a CSR: the device holds it");
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration;
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.Field;
@@ -1212,8 +1213,7 @@ class IotFleetIndexingServiceTest {
@Test
void aTokenThisOperationCouldNotHaveIssuedIsInvalid() {
fleet();
String bareThingName = Base64.getUrlEncoder().withoutPadding()
.encodeToString("alpha-1".getBytes(StandardCharsets.UTF_8));
String bareThingName = Base64Url.encode("alpha-1");
for (String token : List.of("YQ", "", "AAAA", bareThingName)) {
assertSearchFails(query("*").put("nextToken", token), "InvalidRequestException", 400,
@@ -1222,10 +1222,8 @@ class IotFleetIndexingServiceTest {
String issued = search(query("thingName:alpha*").put("maxResults", 1)).nextToken();
String decoded = new String(Base64.getUrlDecoder().decode(issued), StandardCharsets.UTF_8);
String edited = Base64.getUrlEncoder().withoutPadding()
.encodeToString((decoded.substring(0, decoded.length() - 1) + "0").getBytes(StandardCharsets.UTF_8));
String shortened = Base64.getUrlEncoder().withoutPadding()
.encodeToString(decoded.substring(0, decoded.length() - 1).getBytes(StandardCharsets.UTF_8));
String edited = Base64Url.encode(decoded.substring(0, decoded.length() - 1) + "0");
String shortened = Base64Url.encode(decoded.substring(0, decoded.length() - 1));
String truncated = issued.substring(0, issued.length() - 2);
for (String token : List.of(edited, shortened, truncated)) {
assertSearchFails(query("thingName:alpha*").put("nextToken", token), "InvalidRequestException", 400,
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
@@ -1846,12 +1847,7 @@ class KmsServiceTest {
void signWithDigestMessageTypeMatchesRawSignature() {
KmsKey key = kmsService.createKey("rsa digest key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
byte[] message = "deterministic pkcs1".getBytes(StandardCharsets.UTF_8);
byte[] digest;
try {
digest = MessageDigest.getInstance("SHA-256").digest(message);
} catch (Exception e) {
throw new RuntimeException(e);
}
byte[] digest = Digests.sha256(message);
// PKCS#1 v1.5 is deterministic, so signing the digest (DIGEST) and signing the
// message (RAW) with the same algorithm must produce identical signatures.
@@ -1866,7 +1862,7 @@ class KmsServiceTest {
void signWithDigestMessageTypePssVerifiesWithExternalVerifier() throws Exception {
KmsKey key = kmsService.createKey("rsa pss digest key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
byte[] message = "floci kms pss round-trip".getBytes(StandardCharsets.UTF_8);
byte[] digest = MessageDigest.getInstance("SHA-256").digest(message);
byte[] digest = Digests.sha256(message);
byte[] sig = kmsService.sign(key.getKeyId(), digest,
"RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.core.common.Digests;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -602,8 +603,7 @@ class LambdaIntegrationTest {
org.junit.jupiter.api.Assertions.assertEquals('K', pkg[1]);
// Byte-exact: downloaded package hashes to the stored CodeSha256.
byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(pkg);
String downloadedSha256 = Base64.getEncoder().encodeToString(digest);
String downloadedSha256 = Base64.getEncoder().encodeToString(Digests.sha256(pkg));
org.junit.jupiter.api.Assertions.assertEquals(expectedSha256, downloadedSha256,
"downloaded package must be byte-identical to the uploaded zip");
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -235,8 +236,7 @@ class LambdaListLayersParametersIntegrationTest {
// as a cursor, which would silently skip or empty the page.
for (String forged : new String[] {"lp-alpha.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"lp-alpha.", ".signature", "lp-alpha"}) {
String encoded = Base64.getUrlEncoder().withoutPadding()
.encodeToString(forged.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String encoded = Base64Url.encode(forged);
given()
.queryParam("CompatibleRuntime", PAGE_RUNTIME)
.queryParam("Marker", encoded)
@@ -268,8 +268,7 @@ class LambdaListLayersParametersIntegrationTest {
String spliced = LAYER_B + decoded.substring(decoded.lastIndexOf('.'));
given()
.queryParam("CompatibleRuntime", PAGE_RUNTIME)
.queryParam("Marker", Base64.getUrlEncoder().withoutPadding()
.encodeToString(spliced.getBytes(java.nio.charset.StandardCharsets.UTF_8)))
.queryParam("Marker", Base64Url.encode(spliced))
.when()
.get("/2018-10-31/layers")
.then()
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
@@ -20,7 +21,6 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -585,7 +585,7 @@ class S3AuthEnforcementIntegrationTest {
@Order(22)
void presignedRequestWithExplicitContentSha256IsAccepted() throws Exception {
String path = "/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY;
String contentHash = sha256Hex("private body");
String contentHash = Digests.sha256Hex("private body");
String sig = presignedSignature("GET", path, "test", "test", "3600", contentHash);
given()
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
@@ -629,8 +629,8 @@ class S3AuthEnforcementIntegrationTest {
@Order(24)
void presignedRequestWithMismatchedContentSha256IsRejected() throws Exception {
String path = "/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY;
String contentHash = sha256Hex("private body");
String wrongHash = sha256Hex("wrong body");
String contentHash = Digests.sha256Hex("private body");
String wrongHash = Digests.sha256Hex("wrong body");
String sig = presignedSignature("GET", path, "test", "test", "3600", contentHash);
given()
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
@@ -1873,7 +1873,7 @@ class S3AuthEnforcementIntegrationTest {
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=deadbeef")
.header("x-amz-date", SIGNING_TIMESTAMP)
.header("x-amz-content-sha256", sha256Hex("forged"))
.header("x-amz-content-sha256", Digests.sha256Hex("forged"))
.body("forged")
.when()
.put("/" + WRITE_BUCKET + "/" + key)
@@ -1904,7 +1904,7 @@ class S3AuthEnforcementIntegrationTest {
.body(containsString("SignatureDoesNotMatch"));
given()
.filter(LOCAL_SIGNER.withContentSha256(sha256Hex("the body that was signed")))
.filter(LOCAL_SIGNER.withContentSha256(Digests.sha256Hex("the body that was signed")))
.body("a different body")
.when()
.put("/" + WRITE_BUCKET + "/" + key)
@@ -1935,7 +1935,7 @@ class S3AuthEnforcementIntegrationTest {
assertThat(putWithoutContentType(WRITE_BUCKET + "?versioning", suspend, LOCAL_SIGNER).statusCode(),
equalTo(200));
HttpResponse<String> mismatch = putWithoutContentType(WRITE_BUCKET + "?versioning", suspend,
LOCAL_SIGNER.withContentSha256(sha256Hex("something else")));
LOCAL_SIGNER.withContentSha256(Digests.sha256Hex("something else")));
assertThat(mismatch.statusCode(), equalTo(400));
assertThat(mismatch.body(), containsString("XAmzContentSHA256Mismatch"));
@@ -1975,7 +1975,7 @@ class S3AuthEnforcementIntegrationTest {
given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=abc")
.header("x-amz-content-sha256", sha256Hex(""))
.header("x-amz-content-sha256", Digests.sha256Hex(""))
.when()
.get(path)
.then()
@@ -1987,7 +1987,7 @@ class S3AuthEnforcementIntegrationTest {
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/s3/aws4_request")
.header("x-amz-date", SIGNING_TIMESTAMP)
.header("x-amz-content-sha256", sha256Hex(""))
.header("x-amz-content-sha256", Digests.sha256Hex(""))
.when()
.get(path)
.then()
@@ -1998,7 +1998,7 @@ class S3AuthEnforcementIntegrationTest {
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/" + SIGNING_DATE
+ "/us-east-1/sqs/aws4_request, SignedHeaders=host;x-amz-date, Signature=abc")
.header("x-amz-date", SIGNING_TIMESTAMP)
.header("x-amz-content-sha256", sha256Hex(""))
.header("x-amz-content-sha256", Digests.sha256Hex(""))
.when()
.get(path)
.then()
@@ -2214,7 +2214,7 @@ class S3AuthEnforcementIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ SIGNING_TIMESTAMP + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest);
+ Digests.sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(secretKey, SIGNING_DATE, "us-east-1", "s3");
return hexEncode(hmacSha256(signingKey, stringToSign));
@@ -2238,11 +2238,6 @@ class S3AuthEnforcementIntegrationTest {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
@@ -22,7 +23,6 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -240,7 +240,7 @@ class S3LeadingSlashKeyAuthEnforcementIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ timestamp + "\n"
+ credentialScope + "\n"
+ hex(MessageDigest.getInstance("SHA-256").digest(canonicalRequest.getBytes(StandardCharsets.UTF_8)));
+ Digests.sha256Hex(canonicalRequest);
byte[] kDate = hmac(("AWS4test").getBytes(StandardCharsets.UTF_8), date);
byte[] kRegion = hmac(kDate, "us-east-1");
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.s3.model.S3Checksum;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
@@ -11,7 +12,6 @@ import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -382,7 +382,7 @@ class S3PresignedChecksumIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest);
+ Digests.sha256Hex(canonicalRequest);
byte[] kDate = hmacSha256(("AWS4" + SECRET_KEY).getBytes(StandardCharsets.UTF_8), date);
byte[] kRegion = hmacSha256(kDate, "us-east-1");
@@ -413,11 +413,6 @@ class S3PresignedChecksumIntegrationTest {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
@@ -10,7 +11,6 @@ import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -215,7 +215,7 @@ class S3PresignedTaggingSigV4EnforcementIntegrationTest {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest);
+ Digests.sha256Hex(canonicalRequest);
byte[] kDate = hmacSha256(("AWS4" + SECRET_KEY).getBytes(StandardCharsets.UTF_8), date);
byte[] kRegion = hmacSha256(kDate, "us-east-1");
@@ -247,11 +247,6 @@ class S3PresignedTaggingSigV4EnforcementIntegrationTest {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.testing.MutableClock;
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
@@ -20,7 +22,6 @@ import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -424,12 +425,11 @@ class S3ValidateSignaturesIntegrationTest {
/** Runs the AWS Sign-In authorization-code flow through its consent page and returns the token response. */
private static Response signIn() throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(SIGNIN_VERIFIER.getBytes(StandardCharsets.US_ASCII));
byte[] digest = Digests.sha256(SIGNIN_VERIFIER.getBytes(StandardCharsets.US_ASCII));
String consent = given()
.redirects().follow(false)
.queryParam("client_id", SIGNIN_CLIENT_ID)
.queryParam("code_challenge", Base64.getUrlEncoder().withoutPadding().encodeToString(digest))
.queryParam("code_challenge", Base64Url.encode(digest))
.queryParam("code_challenge_method", "SHA-256")
.queryParam("redirect_uri", SIGNIN_REDIRECT_URI)
.queryParam("response_type", "code")
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.signin;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
@@ -8,8 +10,6 @@ import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
@@ -528,9 +528,7 @@ class SigninIntegrationTest {
}
private static String challenge(String verifier) throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(verifier.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
return Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
}
private static Map<String, String> queryParams(String query) {
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.signin;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.signin.model.TokenResult;
@@ -10,10 +12,8 @@ import org.junit.jupiter.api.Test;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@@ -464,9 +464,7 @@ class SigninServiceTest {
}
private static String challenge(String verifier) throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(verifier.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
return Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
}
private static Map<String, String> query(String redirect) {
@@ -2,12 +2,16 @@ package io.github.hectorvent.floci.services.ssooidc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
@@ -179,7 +183,7 @@ class SsoOidcIntegrationTest {
ssoAdminService.putApplicationGrant(grant);
String verifier = "01234567890123456789012345678901234567890123456789";
String challenge = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(sha256(verifier));
String challenge = Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
String code = ssoOidcService.createIamAuthorizationCode(applicationArn, redirectUri, challenge,
java.util.List.of(redirectUri)).code();
String body = "{\"clientId\":\"" + applicationArn + "\",\"grantType\":\"authorization_code\","
@@ -200,15 +204,6 @@ class SsoOidcIntegrationTest {
.body("awsAdditionalDetails.identityContext", org.hamcrest.Matchers.not(org.hamcrest.Matchers.blankOrNullString()));
}
private static byte[] sha256(String value) {
try {
return java.security.MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
} catch (java.security.NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
@Test
void registerClientReturnsOidcErrorShape() {
given()
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.ssooidc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ssooidc.model.AuthorizationCode;
import io.github.hectorvent.floci.services.ssooidc.model.DeviceAuthorization;
@@ -10,6 +12,7 @@ import io.github.hectorvent.floci.services.ssooidc.model.TokenSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -125,8 +128,7 @@ class SsoOidcServiceTest {
register.putArray("redirectUris").add("http://127.0.0.1:8400/callback");
RegisteredClient client = service.registerClient(register);
String verifier = "01234567890123456789012345678901234567890123456789";
String challenge = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
sha256(verifier));
String challenge = Base64Url.encode(Digests.sha256(verifier.getBytes(StandardCharsets.US_ASCII)));
AuthorizationCode code = service.createAuthorizationCode(client.clientId(),
"http://127.0.0.1:8400/callback", challenge);
@@ -173,14 +175,6 @@ class SsoOidcServiceTest {
assertOidcError("invalid_grant",
() -> service.createIamToken(exchange, sourceApplication, java.util.List.of("openid")));
}
private static byte[] sha256(String value) {
try {
return java.security.MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
} catch (java.security.NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
@Test
void registerClientValidatesPublicClientAndGrantType() {
@@ -1,9 +1,10 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.Digests;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -50,12 +51,12 @@ public final class AppSyncRequestSigner {
+ "x-amz-date:" + amzDate + "\n"
+ "\n"
+ signedHeaderNames + "\n"
+ sha256Hex(body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8));
+ Digests.sha256Hex(body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8));
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = deriveSigningKey(secretKey, scopeDate, region);
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
@@ -83,10 +84,6 @@ public final class AppSyncRequestSigner {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(byte[] input) throws Exception {
return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
@@ -124,10 +125,10 @@ public final class AwsRequestSigner implements Filter {
+ S3RequestSigner.canonicalQueryString(uri.getRawQuery()) + "\n"
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
+ SigV4RequestValidator.sha256Hex(body);
+ Digests.sha256Hex(body);
String credentialScope = scopeDate + "/us-east-1/" + service + "/aws4_request";
String stringToSign = ALGORITHM + "\n" + amzDate + "\n" + credentialScope + "\n"
+ SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scopeDate, "us-east-1", service);
String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
@@ -1,9 +1,10 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.Digests;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -68,7 +69,7 @@ public final class ExecuteApiRequestSigner {
+ "x-amz-date:" + amzDate + "\n"
+ "\n"
+ signedHeaderNames + "\n"
+ sha256Hex(body == null ? new byte[0] : body);
+ Digests.sha256Hex(body == null ? new byte[0] : body);
String signature = sign(secretKey, scopeDate, region, credentialScope, amzDate, canonicalRequest);
@@ -134,7 +135,7 @@ public final class ExecuteApiRequestSigner {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = deriveSigningKey(secretKey, scopeDate, region);
return hexEncode(hmacSha256(signingKey, stringToSign));
}
@@ -178,10 +179,6 @@ public final class ExecuteApiRequestSigner {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(byte[] input) throws Exception {
return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.Digests;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
@@ -11,7 +12,6 @@ import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -132,7 +132,7 @@ public final class S3RequestSigner implements Filter {
String scopeDate = amzDate.substring(0, 8);
String contentSha256 = contentSha256Override != null
? contentSha256Override
: sha256Hex(body);
: Digests.sha256Hex(body);
List<String[]> headers = new ArrayList<>();
if (signHost) {
@@ -159,7 +159,7 @@ public final class S3RequestSigner implements Filter {
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String signature = signatureOverride != null
? signatureOverride
: hexEncode(hmacSha256(signingKey(scopeDate), stringToSign));
@@ -213,7 +213,7 @@ public final class S3RequestSigner implements Filter {
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String signature = signatureOverride != null
? signatureOverride
: hexEncode(hmacSha256(signingKey(scopeDate), stringToSign));
@@ -284,10 +284,6 @@ public final class S3RequestSigner implements Filter {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(byte[] input) throws Exception {
return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,14 +1,15 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.Digests;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -156,7 +157,7 @@ public final class SigV4TokenTestHelper {
+ "host\n"
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
String stringToSign = "AWS4-HMAC-SHA256\n" + dateTime + "\n" + credentialScope + "\n"
+ sha256Hex(canonicalRequest);
+ Digests.sha256Hex(canonicalRequest);
String signature = hexEncode(hmacSha256(
deriveSigningKey(secretKey, date, "us-east-1", "rds-db"), stringToSign));
@@ -196,8 +197,7 @@ public final class SigV4TokenTestHelper {
String url = "https://" + signToken(host, null, accessKeyId, secretKey, "us-east-1", "sts",
timestamp, expiresSeconds, params,
Map.of("host", host, "x-k8s-aws-id", clusterName));
return "k8s-aws-v1." + Base64.getUrlEncoder().withoutPadding()
.encodeToString(url.getBytes(StandardCharsets.UTF_8));
return "k8s-aws-v1." + Base64Url.encode(url);
}
private static String signToken(
@@ -250,7 +250,7 @@ public final class SigV4TokenTestHelper {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ dateTime + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest);
+ Digests.sha256Hex(canonicalRequest);
byte[] signingKey = deriveSigningKey(secretKey, date, region, service);
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
@@ -299,11 +299,6 @@ public final class SigV4TokenTestHelper {
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,13 +1,12 @@
package io.github.hectorvent.floci.tools.ami;
import io.github.hectorvent.floci.core.common.Digests;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -159,8 +158,6 @@ class AmiImageToolTest {
}
private static String sha256(Path path) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(Files.readAllBytes(path));
return HexFormat.of().formatHex(digest.digest());
return Digests.sha256Hex(Files.readAllBytes(path));
}
}