diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSrpTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSrpTest.java index 8c179ded29..e2e5bf5f5f 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSrpTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSrpTest.java @@ -4,9 +4,20 @@ import org.junit.jupiter.api.*; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.*; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.security.SecureRandom; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Locale; import java.util.Map; +import java.util.TimeZone; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -108,4 +119,140 @@ class CognitoSrpTest { assertThat(params).containsKey("SALT"); assertThat(params).containsKey("SECRET_BLOCK"); } + + @Test + @Order(4) + @DisplayName("Full USER_SRP_AUTH round-trip yields valid tokens") + void srpAuthCompletesAndReturnsTokens() throws Exception { + // 1. Generate client ephemeral a, public A = g^a mod N. + BigInteger a = new BigInteger(256, new SecureRandom()); + BigInteger A = G.modPow(a, N); + + // 2. Kick off SRP — server returns SRP_B, SALT, SECRET_BLOCK, USER_ID_FOR_SRP. + InitiateAuthResponse init = cognito.initiateAuth(b -> b + .authFlow(AuthFlowType.USER_SRP_AUTH) + .clientId(clientId) + .authParameters(Map.of( + "USERNAME", USERNAME, + "SRP_A", A.toString(16) + ))); + assertThat(init.challengeName()).isEqualTo(ChallengeNameType.PASSWORD_VERIFIER); + + Map challenge = init.challengeParameters(); + BigInteger B = new BigInteger(challenge.get("SRP_B"), 16); + BigInteger salt = new BigInteger(challenge.get("SALT"), 16); + String secretBlockB64 = challenge.get("SECRET_BLOCK"); + String userIdForSrp = challenge.get("USER_ID_FOR_SRP"); + String poolName = poolId.split("_", 2)[1]; + + // 3. Compute the PASSWORD_CLAIM_SIGNATURE per the AWS "Caldera" SRP variant. + BigInteger x = computeX(poolName, userIdForSrp, PASSWORD, salt); + BigInteger u = computeU(A, B); + BigInteger k = computeK(); + // S = (B - k * g^x)^(a + u*x) mod N + BigInteger S = B.subtract(k.multiply(G.modPow(x, N))).mod(N) + .modPow(a.add(u.multiply(x)), N); + byte[] hkdfKey = calderaHkdf(S, u); + String timestamp = formatCognitoTimestamp(new Date()); + byte[] secretBlock = Base64.getDecoder().decode(secretBlockB64); + byte[] signature = hmacSha256(hkdfKey, + concat(poolName.getBytes(StandardCharsets.UTF_8), + userIdForSrp.getBytes(StandardCharsets.UTF_8), + secretBlock, + timestamp.getBytes(StandardCharsets.UTF_8))); + + // 4. Respond to the challenge — Floci must return real tokens if its + // server-side k, U, S, HKDF and HMAC layouts all match the spec. + Map responses = new HashMap<>(); + responses.put("USERNAME", userIdForSrp); + responses.put("PASSWORD_CLAIM_SECRET_BLOCK", secretBlockB64); + responses.put("TIMESTAMP", timestamp); + responses.put("PASSWORD_CLAIM_SIGNATURE", Base64.getEncoder().encodeToString(signature)); + + RespondToAuthChallengeResponse resp = cognito.respondToAuthChallenge(b -> b + .clientId(clientId) + .challengeName(ChallengeNameType.PASSWORD_VERIFIER) + .session(init.session()) + .challengeResponses(responses)); + + AuthenticationResultType auth = resp.authenticationResult(); + assertThat(auth).as("AuthenticationResult populated").isNotNull(); + // JWTs have three base64 segments separated by dots. + assertThat(auth.idToken()).matches("[^.]+\\.[^.]+\\.[^.]+"); + assertThat(auth.accessToken()).matches("[^.]+\\.[^.]+\\.[^.]+"); + assertThat(auth.refreshToken()).isNotBlank(); + } + + // ────────────────────────── Caldera SRP helpers ────────────────────────── + // The AWS Java SDK v2 doesn't expose a public SRP helper — clients writing + // server-side SRP normally pull amazon-cognito-identity-provider's mobile + // SDK or AWSCognitoAuthHelper from aws-android-sdk-cognitoidentityprovider. + // For test isolation we inline the math here, matching the spec floci's + // CognitoSrpHelper implements (the canonical AWS "Caldera" variant). + + private static BigInteger computeK() throws Exception { + // k = SHA-256(N || g) over 2's-complement byte representations + // (minimal length with sign byte where needed). + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + sha.update(N.toByteArray()); + sha.update(G.toByteArray()); + return new BigInteger(1, sha.digest()); + } + + private static BigInteger computeU(BigInteger A, BigInteger B) throws Exception { + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + sha.update(A.toByteArray()); + sha.update(B.toByteArray()); + return new BigInteger(1, sha.digest()); + } + + private static BigInteger computeX(String poolName, String username, String password, BigInteger salt) throws Exception { + // inner = SHA-256(poolName + username + ":" + password) + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + sha.update(poolName.getBytes(StandardCharsets.UTF_8)); + sha.update(username.getBytes(StandardCharsets.UTF_8)); + sha.update(":".getBytes(StandardCharsets.UTF_8)); + sha.update(password.getBytes(StandardCharsets.UTF_8)); + byte[] inner = sha.digest(); + // x = SHA-256(saltBytes || inner) — salt as 2's-complement bytes. + sha.reset(); + sha.update(salt.toByteArray()); + sha.update(inner); + return new BigInteger(1, sha.digest()); + } + + private static byte[] calderaHkdf(BigInteger S, BigInteger U) throws Exception { + // HKDF-Expand over (S, U as salt, "Caldera Derived Key" || 0x01) → 16 bytes + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(U.toByteArray(), "HmacSHA256")); + byte[] prk = mac.doFinal(S.toByteArray()); + + mac.init(new SecretKeySpec(prk, "HmacSHA256")); + mac.update("Caldera Derived Key".getBytes(StandardCharsets.UTF_8)); + mac.update((byte) 1); + return Arrays.copyOf(mac.doFinal(), 16); + } + + private static byte[] hmacSha256(byte[] key, byte[] data) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + return mac.doFinal(data); + } + + private static byte[] concat(byte[]... parts) { + int total = 0; + for (byte[] p : parts) total += p.length; + byte[] out = new byte[total]; + int off = 0; + for (byte[] p : parts) { System.arraycopy(p, 0, out, off, p.length); off += p.length; } + return out; + } + + private static String formatCognitoTimestamp(Date date) { + // Cognito expects "EEE MMM d HH:mm:ss z yyyy" in US locale, UTC, day NOT + // zero-padded — see amazon-cognito-identity-js/getNowString.ts. + SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US); + fmt.setTimeZone(TimeZone.getTimeZone("UTC")); + return fmt.format(date); + } } diff --git a/compatibility-tests/sdk-test-node/package.json b/compatibility-tests/sdk-test-node/package.json index 132258d9d7..2af4f30cab 100644 --- a/compatibility-tests/sdk-test-node/package.json +++ b/compatibility-tests/sdk-test-node/package.json @@ -8,24 +8,24 @@ }, "dependencies": { "@aws-sdk/client-acm": "^3.500.0", + "@aws-sdk/client-apigatewaymanagementapi": "^3.500.0", "@aws-sdk/client-apigatewayv2": "^3.500.0", - "@aws-sdk/client-eventbridge": "^3.500.0", "@aws-sdk/client-cloudformation": "^3.500.0", "@aws-sdk/client-cloudwatch": "^3.500.0", "@aws-sdk/client-cognito-identity-provider": "^3.500.0", "@aws-sdk/client-dynamodb": "^3.500.0", "@aws-sdk/client-ecr": "^3.500.0", - "@aws-sdk/client-pipes": "^3.500.0", + "@aws-sdk/client-eventbridge": "^3.500.0", "@aws-sdk/client-iam": "^3.500.0", "@aws-sdk/client-kinesis": "^3.500.0", "@aws-sdk/client-kms": "^3.500.0", "@aws-sdk/client-lambda": "^3.500.0", + "@aws-sdk/client-pipes": "^3.500.0", "@aws-sdk/client-s3": "^3.500.0", "@aws-sdk/client-secrets-manager": "^3.500.0", "@aws-sdk/client-sns": "^3.500.0", "@aws-sdk/client-sqs": "^3.500.0", "@aws-sdk/client-ssm": "^3.500.0", - "@aws-sdk/client-apigatewaymanagementapi": "^3.500.0", "@aws-sdk/client-sts": "^3.500.0", "selfsigned": "^5.5.0", "ws": "^8.0.0" @@ -33,6 +33,7 @@ "devDependencies": { "@types/node": "^20.0.0", "@types/ws": "^8.0.0", + "amazon-cognito-identity-js": "^6.3.16", "esbuild": "^0.21.0", "typescript": "^5.4.0", "vitest": "^2.0.0" diff --git a/compatibility-tests/sdk-test-node/tests/cognito-srp.test.ts b/compatibility-tests/sdk-test-node/tests/cognito-srp.test.ts new file mode 100644 index 0000000000..9ebdc13c36 --- /dev/null +++ b/compatibility-tests/sdk-test-node/tests/cognito-srp.test.ts @@ -0,0 +1,109 @@ +/** + * Cognito USER_SRP_AUTH round-trip via amazon-cognito-identity-js. + * + * The existing CognitoSrpTest (Java) only validates that the PASSWORD_VERIFIER + * challenge is *returned*. This test goes further and exercises the full + * round-trip — the client computes the PASSWORD_CLAIM_SIGNATURE from SRP_B + * + SALT + SECRET_BLOCK and sends RespondToAuthChallenge — using the + * canonical JS SRP impl (`amazon-cognito-identity-js`, which is what AWS + * Amplify v6 wraps internally). + * + * Validates that Floci's server-side SRP-6a math (k, U, S, HKDF, HMAC byte + * layouts) matches AWS's "Caldera" SRP spec well enough for a real SDK + * client to authenticate end-to-end. + */ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { + CognitoIdentityProviderClient, + CreateUserPoolCommand, + CreateUserPoolClientCommand, + AdminCreateUserCommand, + AdminSetUserPasswordCommand, + DeleteUserPoolCommand, + MessageActionType, + ExplicitAuthFlowsType, +} from '@aws-sdk/client-cognito-identity-provider'; +import { + CognitoUserPool, + CognitoUser, + AuthenticationDetails, +} from 'amazon-cognito-identity-js'; +import { makeClient, ENDPOINT } from './setup'; + +describe('Cognito USER_SRP_AUTH end-to-end (amazon-cognito-identity-js)', () => { + let cognito: CognitoIdentityProviderClient; + let poolId: string; + let clientId: string; + const username = `srp-roundtrip-${Date.now()}`; + const password = 'SrpRoundTrip1!'; + + beforeAll(async () => { + cognito = makeClient(CognitoIdentityProviderClient); + + const pool = await cognito.send(new CreateUserPoolCommand({ PoolName: 'srp-roundtrip-pool' })); + poolId = pool.UserPool!.Id!; + + const client = await cognito.send( + new CreateUserPoolClientCommand({ + UserPoolId: poolId, + ClientName: 'srp-roundtrip-client', + ExplicitAuthFlows: [ExplicitAuthFlowsType.ALLOW_USER_SRP_AUTH], + }), + ); + clientId = client.UserPoolClient!.ClientId!; + + await cognito.send( + new AdminCreateUserCommand({ + UserPoolId: poolId, + Username: username, + MessageAction: MessageActionType.SUPPRESS, + }), + ); + await cognito.send( + new AdminSetUserPasswordCommand({ + UserPoolId: poolId, + Username: username, + Password: password, + Permanent: true, + }), + ); + }); + + afterAll(async () => { + if (poolId) { + try { await cognito.send(new DeleteUserPoolCommand({ UserPoolId: poolId })); } catch {} + } + cognito.destroy(); + }); + + it('authenticates via SRP and returns valid tokens', async () => { + const userPool = new CognitoUserPool({ + UserPoolId: poolId, + ClientId: clientId, + endpoint: ENDPOINT, + }); + const cognitoUser = new CognitoUser({ Username: username, Pool: userPool }); + const authDetails = new AuthenticationDetails({ Username: username, Password: password }); + + const session = await new Promise<{ + idToken: string; + accessToken: string; + refreshToken: string; + }>((resolve, reject) => { + cognitoUser.authenticateUser(authDetails, { + onSuccess: (s) => + resolve({ + idToken: s.getIdToken().getJwtToken(), + accessToken: s.getAccessToken().getJwtToken(), + refreshToken: s.getRefreshToken().getToken(), + }), + onFailure: (err) => reject(err), + }); + }); + + // JWT tokens have three base64 segments separated by dots. + expect(session.idToken.split('.')).toHaveLength(3); + expect(session.accessToken.split('.')).toHaveLength(3); + expect(session.refreshToken.length).toBeGreaterThan(0); + }); +}); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java index 86411560b3..fde9d02133 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java @@ -63,11 +63,15 @@ final class CognitoSrpHelper { static { try { - byte[] nBytes = padTo(N.toByteArray(), N_BYTES); - byte[] gBytes = padTo(G.toByteArray(), N_BYTES); + // Amplify computes k as SHA-256(getBytesFromHex(getPaddedHex(N) + getPaddedHex(g))) + // which is equivalent to SHA-256(N.toByteArray() || G.toByteArray()) — i.e., minimal + // two's-complement representation (sign byte for positive MSB-set N, no left-padding + // of g to N_BYTES). Match that byte layout exactly so server-computed k equals the + // client's, otherwise client S = (B - k_client·g^x)^… diverges from server S and the + // PASSWORD_VERIFIER signature never matches. MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - sha256.update(nBytes); - sha256.update(gBytes); + sha256.update(N.toByteArray()); + sha256.update(G.toByteArray()); K = new BigInteger(1, sha256.digest()); } catch (Exception e) { throw new ExceptionInInitializerError(e); @@ -144,8 +148,23 @@ final class CognitoSrpHelper { BigInteger base = A.multiply(v.modPow(u, N)).mod(N); BigInteger S = base.modPow(b, N); - // Derive key using Caldera interleaved hash - return deriveCalderaKey(S); + // Cognito's Caldera derivation: HKDF-Expand over 2's-complement(S) with + // salt=2's-complement(U), info="Caldera Derived Key"||0x01, output truncated to + // 16 bytes (128-bit HMAC key). Byte representations must match Amplify's + // getBytesFromHex(getPaddedHex(bi)) — i.e., minimal length with sign byte. + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(u.toByteArray(), "HmacSHA256")); + byte[] prk = mac.doFinal(S.toByteArray()); + + mac.init(new SecretKeySpec(prk, "HmacSHA256")); + mac.update(INFO_BITS); + mac.update((byte) 1); + byte[] t1 = mac.doFinal(); + return Arrays.copyOf(t1, 16); + } catch (Exception e) { + throw new RuntimeException("SRP session key derivation failed", e); + } } // ──────────────────────────── HMAC signature ──────────────────────────── @@ -163,9 +182,8 @@ final class CognitoSrpHelper { static byte[] computeSignature(byte[] sessionKey, String userPoolId, String username, byte[] secretBlock, String timestamp) { try { - byte[] hkdfKey = hkdf(sessionKey, INFO_BITS); Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(hkdfKey, "HmacSHA256")); + mac.init(new SecretKeySpec(sessionKey, "HmacSHA256")); mac.update(extractPoolName(userPoolId).getBytes(StandardCharsets.UTF_8)); mac.update(username.getBytes(StandardCharsets.UTF_8)); mac.update(secretBlock); @@ -217,8 +235,11 @@ final class CognitoSrpHelper { sha256.update(password.getBytes(StandardCharsets.UTF_8)); byte[] innerHash = sha256.digest(); - // x = SHA-256(pad(salt) || innerHash) - byte[] saltBytes = HexFormat.of().parseHex(saltHex); + // x = SHA-256(saltBytes || innerHash) + // Amplify treats salt as a BigInteger and emits its 2's-complement byte + // representation (sign byte prepended when MSB is set). Mirror that by + // round-tripping the hex through BigInteger. + byte[] saltBytes = new BigInteger(saltHex, 16).toByteArray(); sha256.reset(); sha256.update(saltBytes); sha256.update(innerHash); @@ -231,82 +252,14 @@ final class CognitoSrpHelper { private static BigInteger computeU(BigInteger A, BigInteger B) { try { MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - sha256.update(padTo(A.toByteArray(), N_BYTES)); - sha256.update(padTo(B.toByteArray(), N_BYTES)); + // Use BigInteger.toByteArray() (2's complement, minimal length with sign byte) + // — matches Amplify's getBytesFromHex(getPaddedHex(bi)). + sha256.update(A.toByteArray()); + sha256.update(B.toByteArray()); return new BigInteger(1, sha256.digest()); } catch (Exception e) { throw new RuntimeException("SRP u computation failed", e); } } - /** - * Caldera interleaved hash to derive session key from S. - * SHA-256 is applied to even-indexed and odd-indexed bytes of S separately, - * then interleaved. - */ - private static byte[] deriveCalderaKey(BigInteger S) { - try { - byte[] sBytes = padTo(S.toByteArray(), N_BYTES); - - // Split into even/odd positions - byte[] even = new byte[N_BYTES / 2]; - byte[] odd = new byte[N_BYTES / 2]; - for (int i = 0; i < N_BYTES / 2; i++) { - even[i] = sBytes[i * 2]; - odd[i] = sBytes[i * 2 + 1]; - } - - MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - byte[] hashEven = sha256.digest(even); - sha256.reset(); - byte[] hashOdd = sha256.digest(odd); - - // Interleave the two hashes - byte[] result = new byte[64]; - for (int i = 0; i < 32; i++) { - result[i * 2] = hashEven[i]; - result[i * 2 + 1] = hashOdd[i]; - } - return result; - } catch (Exception e) { - throw new RuntimeException("Caldera key derivation failed", e); - } - } - - /** - * HKDF extract-and-expand using SHA-256 (salt = zeroes, no extract step). - * Compatible with Cognito's "Caldera Derived Key" derivation. - */ - private static byte[] hkdf(byte[] ikm, byte[] info) throws Exception { - // Extract: PRK = HMAC-SHA256(salt=zeroes_32, IKM) - byte[] salt = new byte[32]; - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(salt, "HmacSHA256")); - byte[] prk = mac.doFinal(ikm); - - // Expand: T(1) = HMAC-SHA256(PRK, info || 0x01) - mac.init(new SecretKeySpec(prk, "HmacSHA256")); - mac.update(info); - mac.update((byte) 1); - byte[] t1 = mac.doFinal(); - return Arrays.copyOf(t1, 32); - } - - /** - * Left-pads a byte array to the given length. - * If the array has a leading 0x00 sign byte, it is stripped before padding. - */ - static byte[] padTo(byte[] bytes, int length) { - // Strip sign byte if present - if (bytes.length > length && bytes[0] == 0) { - bytes = Arrays.copyOfRange(bytes, 1, bytes.length); - } - if (bytes.length == length) { - return bytes; - } - byte[] padded = new byte[length]; - int offset = length - bytes.length; - System.arraycopy(bytes, 0, padded, offset, bytes.length); - return padded; - } }