fix(cognito): correct USER_SRP_AUTH PASSWORD_VERIFIER signature (#912)

* fix(cognito): correct USER_SRP_AUTH PASSWORD_VERIFIER signature

Server-side SRP-6a produced HMAC signatures that never matched what
AWS Amplify / SDKs compute, so USER_SRP_AUTH always failed with
NotAuthorizedException. Five independent bugs in the byte layout and
key-derivation chain:

1. SRP multiplier k: hashed N and g left-padded to N_BYTES (384 bytes).
   Cognito/Amplify hash the minimal two's-complement representation
   (385 bytes for N — sign byte prepended because MSB is set — and
   1 byte for g = 2). k participates in both server B = k*v + g^b and
   client S = (B - k*g^x)^(a+ux), so a divergent k breaks the protocol.
   Use N.toByteArray() and G.toByteArray() directly.

2. Session key derivation: previously ran an undocumented "Caldera
   interleaved hash" over S, then fed that into HKDF with a zero salt.
   Cognito applies HKDF-Expand directly over S with the scrambling
   parameter U as salt:
     PRK  = HMAC-SHA256(U_bytes, S_bytes)
     T(1) = HMAC-SHA256(PRK, "Caldera Derived Key" || 0x01)
     key  = T(1)[0..16]
   Inline that HKDF in computeSessionKey; drop interleaved hash + the
   auxiliary hkdf() helper.

3. HKDF output length: helper returned 32 bytes; Amplify uses the first
   16. Return Arrays.copyOf(t1, 16).

4. computeSignature double-HKDF: when sessionKey was already the final
   HMAC key, computeSignature ran HKDF on it again. Use it as-is.

5. computeU / computeX byte layout: U was hashed with A and B
   left-padded to N_BYTES; salt was decoded as raw hex bytes. Amplify
   feeds the minimal two's-complement representation (with sign byte
   for positive MSB-set values). Use BigInteger.toByteArray() for A/B
   and round-trip the hex salt through BigInteger so a sign byte is
   prepended when needed.

Verified by reproducing floci's exact server-side computation in
JavaScript using Amplify's byte conventions: the JS replay reproduces
floci's expected HMAC byte-for-byte (proving the server is internally
consistent) and the divergence from the client's claimed HMAC traces
entirely to k differing. After the fix, USER_SRP_AUTH end-to-end signin
from Amplify v6 (React Native) against floci succeeds.

Compat note: users whose verifier was stored under the previous
computeX with a salt whose first byte has the MSB set (~50% of
generate-salt outputs) will produce a different x and must reset their
password. New signups against this fix are interoperable with Amplify.

Also drops the now-unused padTo() helper.

* test(compatibility): add USER_SRP_AUTH round-trip tests for Node + Java SDKs

The existing CognitoSrpTest only validated that PASSWORD_VERIFIER was
returned by InitiateAuth; nothing exercised the full handshake. With the
server-side SRP math now spec-compliant, add end-to-end tests that prove
real AWS SDK clients authenticate against floci.

Java (sdk-test-java/CognitoSrpTest):
 - Add step 4: compute PASSWORD_CLAIM_SIGNATURE from the challenge using
   the AWS "Caldera" SRP variant, send RespondToAuthChallenge, assert
   AuthenticationResult contains valid JWT id/access/refresh tokens.
 - Helper math (computeX / computeU / computeK / calderaHkdf /
   hmacSha256 / formatCognitoTimestamp) inlined since the AWS Java SDK
   v2 does not expose a public SRP client.

Node (sdk-test-node/tests/cognito-srp.test.ts):
 - New round-trip test using amazon-cognito-identity-js 6.3.16 — the
   canonical JS SRP impl that @aws-amplify/auth wraps internally.
 - Pool is provisioned via AdminCreateUser + AdminSetUserPassword so the
   test doesn't depend on an email-delivered verification code.
 - Validates tokens come back as well-formed JWTs.

Both tests pass against floci with the fix from the previous commit and
fail (CodeMismatchException / NotAuthorizedException) without it.
This commit is contained in:
Ricardo Medina authored and GitHub committed 2026-05-18 23:02:49 -05:00
1 parent 5dedeff9e4
commit c426289879
4 files changed
+295 -85

No files matched your search

@@ -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<String, String> 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<String, String> 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);
}
}