Files
floci/compatibility-tests/sdk-test-node/tests/cognito-srp.test.ts
T
Ricardo Medina c426289879 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.
2026-05-18 23:02:49 -05:00

110 lines
3.5 KiB
TypeScript

/**
* 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);
});
});