From Amazon Cognito
For: an operator and a developer who move an app from Amazon Cognito to authtempo.
What it does: you import the users of a Cognito user pool. Cognito exports no hash, so core asks Cognito once, at each user’s first password sign-in, and then keeps its own hash.
Before you start
Section titled “Before you start”- An API with authtempo. Do a getting started tutorial first.
- The AWS CLI, with read access to the user pool.
- An app client of the pool that lists
ALLOW_USER_PASSWORD_AUTHin its auth flows.password.legacyVerifyof Passwords calls it. - A pool that accepts the address as a user name or as an alias.
password.legacyVerifyof Passwords sends the address. @authtempo/cliand@authtempo/legacy-hashesin the app’s workspace. authtempo import is a command of the first.
Export
Section titled “Export”- Export the users, and keep the whole output with its
Usersarray.
aws cognito-idp list-users --user-pool-id "$POOL" --output json > users.jsonCarry the passwords
Section titled “Carry the passwords”Cognito exports no hash. Core checks each password against Cognito once, at the user’s first password sign-in.
- Set
password.legacyVerifyin the API with the region and the app client of the pool.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";import { createCognitoLegacyVerify } from "@authtempo/legacy-hashes/cognito";
/** * The API after an import from Amazon Cognito. Cognito exports no hash, so * core asks Cognito once per user, at the first password sign-in, and then * writes its own hash. Remove `legacyVerify` when the migration ends. */export function createCognitoAuth( deps: { storage: StorageAdapter; mail: MailPort; secret: string }, // The global fetch in the app. The test passes a fake Cognito. fetchImpl: typeof fetch = globalThis.fetch,) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, password: { legacyVerify: { verify: createCognitoLegacyVerify({ region: "eu-west-1", // The app client must allow ALLOW_USER_PASSWORD_AUTH. clientId: "example-app-client-id", fetch: fetchImpl, }), // Every failed password sign-in answers no earlier than this, so a // migrated and an unmigrated address look the same. timeoutMs: 2000, }, }, });}- Pass
clientSecrettoo, when the app client has a secret. - On Workers, pass
waitUntil, so the failure line outlives the response.
Dry run
Section titled “Dry run”- Run the import as a dry run, and read the report.
- Cognito exports no hash, so the
hashes:line countslegacy-verifymarkers andnoneonly.
The @authtempo packages are on npm. Add the CLI to your app with pnpm add -D @authtempo/cli, and run each command as pnpm exec authtempo ….
authtempo import cognito --users users.json --legacy-verify --target postgres --url-env DATABASE_URL --dry-runRun the real import on a copy of the database only. The one real import into the real database runs at step 9 of The cutover, after the old sign-ins stop. If it runs earlier, a password, an address, or a delete that changes in the old system after it is lost. One real import tells why.
- Make the copy. On Postgres, create an empty database, set
COPY_URLto its URL, and load the real one into it withpg_dump --no-owner "$DATABASE_URL" | psql "$COPY_URL". - On D1, load the real database into the empty local copy of the import Worker with
wrangler d1 export <database> --remote --output copy.sqlandwrangler d1 execute <database> --local --file copy.sql. - Run both in the folder of the import Worker. Delete its
.wrangler/statefirst, or the load stops on a table that exists. - Run the same command without
--dry-run, with--url-env COPY_URL. On D1, run the import Worker without"remote": true, so it writes the local copy.
authtempo import cognito --users users.json --legacy-verify --target postgres --url-env COPY_URLVerify
Section titled “Verify”- Run
authtempo import verifywith the same files on the copy. It exits 0 only when the copy holds the whole export. - Run
authtempo check <base url>against the API. - Sign in once with a known user. Sign in once more with a user whose Cognito address has capital letters. Do it at step 13 of The cutover: before that step, the real database holds no user.
- Drop the copy, and on D1 delete
copy.sql, whenimport verifyexits 0. The copy holds every user of the export.
authtempo import verify cognito --users users.json --legacy-verify --target postgres --url-env COPY_URLauthtempo check https://api.example.comThe test below imports one Cognito user against a fake Cognito.
import { LEGACY_VERIFY_HASH } from "@authtempo/core";import { importUsers, readSource } from "@authtempo/import";import { FIXTURE_EXPORTS } from "@authtempo/import/testing";import { describe, expect, it } from "vitest";import { call, type Harness, harness } from "../support/harness.ts";import { createCognitoAuth } from "./cognito.ts";
// The fixture export of the Cognito reader holds Cara, one CONFIRMED user, with no hash.const f = FIXTURE_EXPORTS.cognito;
/** A fake Cognito: InitiateAuth passes for one password and refuses every other. */function fakeCognito(password: string) { const calls: string[] = []; const impl = (async (_url: RequestInfo | URL, init?: RequestInit) => { const body = JSON.parse(String(init?.body)) as { AuthParameters: { USERNAME: string; PASSWORD: string }; }; calls.push(body.AuthParameters.USERNAME); return body.AuthParameters.PASSWORD === password ? Response.json({ AuthenticationResult: { AccessToken: "cognito-access-token" } }) : Response.json({ __type: "NotAuthorizedException" }, { status: 400 }); }) as typeof fetch; return { impl, calls };}
/** Reads the hash of the one password row in the database. */async function onlyHash(h: Harness): Promise<string> { const rows = await h.storage.findMany("password", []); expect(rows.length).toBe(1); return rows[0]?.hash ?? "";}
describe("move users from Amazon Cognito", () => { it("imports the fixture export with the marker", async () => { const h = harness(); const report = await importUsers(h.storage, await readSource(f.bundle), { formats: [], legacyVerify: true, }); expect(report.created.password).toBe(1); // Core reads this marker as "ask the old system". expect(await onlyHash(h)).toBe(LEGACY_VERIFY_HASH);
const cognito = fakeCognito("right horse battery"); const auth = createCognitoAuth(h, cognito.impl); const res = await call(auth, "POST", "/auth/password/sign-in", { email: "cara@example.com", password: "right horse battery", }); expect(res.status).toBe(200); expect(cognito.calls).toEqual(["cara@example.com"]); expect((await onlyHash(h)).startsWith("pbkdf2-sha256$")).toBe(true); });
it("asks Cognito once at the first sign-in, then signs in with core's own hash", async () => { const h = harness(); const report = await importUsers(h.storage, await readSource(f.bundle), { formats: [], legacyVerify: true, }); expect(report.created.password).toBe(1);
const cognito = fakeCognito("right horse battery"); const auth = createCognitoAuth(h, cognito.impl); const signIn = (password: string) => call(auth, "POST", "/auth/password/sign-in", { email: "cara@example.com", password }); expect((await signIn("right horse battery")).status).toBe(200); expect((await signIn("right horse battery")).status).toBe(200); expect(cognito.calls).toEqual(["cara@example.com"]); });
it("answers invalid_credentials when Cognito refuses the password", async () => { const h = harness(); await importUsers(h.storage, await readSource(f.bundle), { formats: [], legacyVerify: true, }); const auth = createCognitoAuth(h, fakeCognito("right horse battery").impl); const res = await call(auth, "POST", "/auth/password/sign-in", { email: "cara@example.com", password: "wrong", }); expect(res.status).toBe(401); expect(await res.json()).toEqual({ error: "invalid_credentials" }); });});Change the calls
Section titled “Change the calls”- Change each auth call of the app with the table of The calls.
Cut over
Section titled “Cut over”- Do the steps of The cutover.
- Remove
legacyVerifyfrom the API when the migration ends.
The calls
Section titled “The calls”| Amplify | authtempo |
|---|---|
signIn({ username, password }) |
client.password.signIn({ email, password }) |
signUp({ username, password }) |
client.password.signUp({ email, password }) |
signInWithRedirect({ provider: "Google" }) |
Send the browser to /auth/social/google/start?next=/ on the API. |
resetPassword({ username }) |
client.password.requestReset({ email }) |
confirmResetPassword(input) |
client.password.reset({ token, password }), with the token of the reset link |
signOut() |
client.signOut() |
getCurrentUser(), fetchAuthSession() |
client.session() |
The ID token of fetchAuthSession() |
client.jwt.token() |
How it behaves
Section titled “How it behaves”- Only a
CONFIRMEDuser gets the marker. Every other status skips the user, and the reason names the status. - Only the built-in providers
GoogleandSignInWithApplemap to an identity. - Core calls Cognito only for a user whose password row holds the marker. A right answer writes core’s own hash over it.
- Every failed password sign-in answers no earlier than
timeoutMs. So the response time does not show an address that is not yet migrated. - A claim of the address deletes the marker, and a reset overwrites it.
- Each Cognito challenge answers false, the second factor and
NEW_PASSWORD_REQUIREDamong them. Such a user resets the password.
If it fails
Section titled “If it fails”invalid_credentialsfor every user: the app client does not allowUSER_PASSWORD_AUTH, or the pool does not take the address as a user name. The log line names the Cognito error.- The command exits 1 with
legacy-verifyrefusals: the run has no--legacy-verify. - The command stops at start:
users.jsonholds a bare array. Save the wholelist-usersoutput.