Skip to content
Draft

wip #20533

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 67 additions & 74 deletions packages/fxa-auth-client/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -732,9 +732,13 @@ export default class AuthClient {
);
}
} catch (err) {
Sentry.captureMessage(
'Failure to complete v2 key stretch upgrade.'
);
Sentry.captureException(err, {
tags: {
errno: err?.errno,
endpoint: 'passwordChange',
source: 'v2-upgrade',
},
});
}
} else if (credentials.v2) {
// Already using V2! Just sign in.
Expand Down Expand Up @@ -1484,40 +1488,25 @@ export default class AuthClient {
options: SessionReauthOptions = {},
headers?: Headers
): Promise<SessionReauthedAccountData> {
const credentials = await crypto.getCredentials(email, password);
try {
const accountData = await this.sessionReauthWithAuthPW(
sessionToken,
email,
credentials.authPW,
options,
headers
);
if (options.keys) {
accountData.unwrapBKey = credentials.unwrapBKey;
}
return accountData;
} catch (error: any) {
if (
error &&
error.email &&
error.errno === ERRORS.INCORRECT_EMAIL_CASE &&
!options.skipCaseError
) {
options.skipCaseError = true;
options.originalLoginEmail = email;

return this.sessionReauth(
sessionToken,
error.email,
password,
options,
headers
);
} else {
throw error;
}
// v1 stretching salts using the accounts initial singup email, which
// can differ from the user's current primary email. Fetch the original
// account email up-front so we derive the correct authPW the first time.
const { email: derivationEmail } = await this.fetchVerifierEmail(
sessionToken,
headers
);
const credentials = await crypto.getCredentials(derivationEmail, password);
const accountData = await this.sessionReauthWithAuthPW(
sessionToken,
derivationEmail,
credentials.authPW,
options,
headers
);
if (options.keys) {
accountData.unwrapBKey = credentials.unwrapBKey;
}
return accountData;
}

async sessionReauthWithAuthPW(
Expand Down Expand Up @@ -1552,8 +1541,15 @@ export default class AuthClient {
} = {},
headers?: Headers
): Promise<SignedInAccountData> {
// v1 stretching salts using the accounts initial singup email, which
// can differ from the user's current primary email. Fetch the original
// account email up-front so we derive the correct authPW the first time.
const { email: derivationEmail } = await this.fetchVerifierEmail(
sessionToken,
headers
);
const oldCredentials = await this.passwordChangeStart(
email,
derivationEmail,
oldPassword,
sessionToken,
undefined,
Expand Down Expand Up @@ -1586,7 +1582,7 @@ export default class AuthClient {
let unwrapBKeyVersion2: string | undefined;
if (this.keyStretchVersion === 2) {
const v2Payload = await this.createPasswordChangeV2Payload(
email,
derivationEmail,
newPassword,
keys,
newCredentials,
Expand Down Expand Up @@ -1817,16 +1813,27 @@ export default class AuthClient {
} = {},
headers?: Headers
): Promise<SignedInAccountData> {
// Both the old v1 credentials and the new v1 credentials are salted by
// the account's original signup email, which can differ from the
// user's current primary. Fetch the original account email up-front so
// every derivation below matches the stored verifier on the first try.
const { email: derivationEmail } = await this.fetchVerifierEmail(
sessionToken,
headers
);
const oldCredentials = await this.sessionReauth(
sessionToken,
options.reauthEmail || email,
derivationEmail,
oldPassword,
{
keys: true,
},
headers
);
const oldCredentialsAuth = await crypto.getCredentials(email, oldPassword);
const oldCredentialsAuth = await crypto.getCredentials(
derivationEmail,
oldPassword
);
const oldAuthPW = oldCredentialsAuth.authPW;

const keys = await this.accountKeys(
Expand All @@ -1835,7 +1842,10 @@ export default class AuthClient {
headers
);

const newCredentials = await crypto.getCredentials(email, newPassword);
const newCredentials = await crypto.getCredentials(
derivationEmail,
newPassword
);

const wrapKb = crypto.unwrapKB(keys.kB, newCredentials.unwrapBKey);
const authPW = newCredentials.authPW;
Expand All @@ -1849,15 +1859,15 @@ export default class AuthClient {
wrapKbVersion2?: string;
clientSalt?: string;
} = {
email,
email: derivationEmail,
oldAuthPW,
authPW,
wrapKb,
};

if (this.keyStretchVersion === 2) {
const v2Payload = await this.createPasswordChangeV2Payload(
email,
derivationEmail,
newPassword,
keys,
newCredentials,
Expand All @@ -1872,37 +1882,7 @@ export default class AuthClient {
};
}

try {
const accountData = await this.jwtPost(
'/mfa/password/change',
jwt,
payload,
headers
);

return accountData;
} catch (error: any) {
if (
error &&
error.email &&
error.errno === ERRORS.INCORRECT_EMAIL_CASE &&
!options.skipCaseError
) {
options.skipCaseError = true;
options.reauthEmail = email;
return await this.passwordChangeWithJWT(
jwt,
error.email,
oldPassword,
newPassword,
sessionToken,
options,
headers
);
} else {
throw error;
}
}
return this.jwtPost('/mfa/password/change', jwt, payload, headers);
}

async createPassword(
Expand Down Expand Up @@ -3651,4 +3631,17 @@ export default class AuthClient {
throw error;
}
}

// Returns the account's signup email — the immutable PBKDF2 salt for v1
// password derivation. Callers must use this email (not the user's current
// primary) when deriving v1 credentials so the resulting authPW matches
// the stored verifier on accounts whose primary email has been swapped.
// v2 accounts derive from `clientSalt` and don't need this — callers can
// short-circuit when verifierVersion === 2.
public async fetchVerifierEmail(
sessionToken: hexstring,
headers?: Headers
): Promise<{ email: string; }> {
return this.sessionGet('/session/verifier-email', sessionToken, headers);
}
}
83 changes: 83 additions & 0 deletions packages/fxa-auth-client/test/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,87 @@ describe('lib/client', () => {
assert.notEqual(lastInit?.credentials, 'include');
});
});

describe('use original account email for derivation for v1 password flows', () => {
let testClient: AuthClient;
let originalFetch: typeof globalThis.fetch;
const SESSION_TOKEN = '00'.repeat(32);
const SIGNUP_EMAIL = 'signup@example.com';
const TYPED_EMAIL = 'primary-now@example.com';

let requests: Array<{ url: string; init: RequestInit | undefined }>;
let respondWith: (
url: string,
init: RequestInit | undefined
) => Response | Promise<Response>;

before(() => {
testClient = new AuthClient('http://localhost:9000');
});

beforeEach(() => {
originalFetch = globalThis.fetch;
requests = [];
// Default: respond with empty JSON for any path the test doesn't
// explicitly handle. Tests override `respondWith` to assert paths.
respondWith = () =>
new Response('{}', {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
globalThis.fetch = (async (url: string, init?: RequestInit) => {
requests.push({ url, init });
return respondWith(url, init);
}) as typeof globalThis.fetch;
});

afterEach(() => {
globalThis.fetch = originalFetch;
});

it('fetchVerifierEmail GETs /session/verifier-email', async () => {
respondWith = () =>
new Response(
JSON.stringify({ email: SIGNUP_EMAIL }),
{
status: 200,
headers: { 'Content-Type': 'application/json' },
}
);
const result = await testClient.fetchVerifierEmail(SESSION_TOKEN);
assert.deepEqual(result, { email: SIGNUP_EMAIL });
assert.equal(requests.length, 1);
assert.ok(requests[0].url.endsWith('/session/verifier-email'));
assert.equal(requests[0].init?.method, 'GET');
});

it('sessionReauth derives authPW from the original account email', async () => {
// First request must be /session/verifier-email returning the signup
// email; subsequent /session/reauth call should carry that email.
respondWith = (url) => {
if (url.includes('/session/verifier-email')) {
return new Response(
JSON.stringify({ email: SIGNUP_EMAIL }),
{
status: 200,
headers: { 'Content-Type': 'application/json' },
}
);
}
return new Response('{}', {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
};
// Caller passes the user's CURRENT primary; auth-client should
// ignore it and use the signup email server-side returns.
await testClient.sessionReauth(SESSION_TOKEN, TYPED_EMAIL, 'pw');
assert.equal(requests[0].init?.method, 'GET');
assert.ok(requests[0].url.includes('/session/verifier-email'));
const reauthReq = requests.find((r) => r.url.includes('/session/reauth'));
assert.ok(reauthReq, '/session/reauth should be called');
const body = JSON.parse(reauthReq!.init?.body as string);
assert.equal(body.email, SIGNUP_EMAIL);
});
});
});
16 changes: 16 additions & 0 deletions packages/fxa-auth-server/docs/swagger/session-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,21 @@ const SESSION_VERIFY_PUSH_POST = {
],
};

const SESSION_VERIFIER_EMAIL_GET = {
...TAGS_SESSION,
description: '/session/verifier-email',
notes: [
dedent`
🔒 Authenticated with session token

Returns the account's signup email — the value used as the salt for v1 password derivation. Clients deriving v1 credentials must use this email (not the user's current primary email) so that the resulting authPW matches the stored verifier. Self-deprecating: v2 accounts derive from \`clientSalt\` and don't need this call; the endpoint can be removed once v1 is fully phased out.

**Response object:**
- \`email\`: The account's signup email (\`accounts.email\`).
`,
],
};

const API_DOCS = {
SESSION_DESTROY_POST,
SESSION_DUPLICATE_POST,
Expand All @@ -163,6 +178,7 @@ const API_DOCS = {
SESSION_VERIFY_CODE_POST,
SESSION_SEND_PUSH_POST,
SESSION_VERIFY_PUSH_POST,
SESSION_VERIFIER_EMAIL_GET,
};

export default API_DOCS;
Loading
Loading