Skip to content

feat: passkeys - #13983

Merged
ChiragAgg5k merged 47 commits into
mainfrom
feat/passkeys
Oct 7, 2026
Merged

ChiragAgg5k merged 47 commits into
mainfrom
feat/passkeys

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Adds passkeys (WebAuthn) as a usernameless sign-in method for existing accounts. Tracks appwrite-labs/cloud#5805. Console: appwrite/vibes#489.

Design

 Register (signed in <10m, verified email/phone)    Sign in (guest, no email)
 ───────────────────────────────────────────────    ─────────────────────────
 POST /account/passkeys ──► pending passkey          POST /account/tokens/passkey ──► challenge
        │                    + challenge (5m)                │
 navigator.credentials.create()                      navigator.credentials.get()
        │                                                    │
 PUT /account/passkeys/:id/verification              PUT /account/tokens/passkey ──► token (secret, 60s)
        │  verify attestation, consume challenge             │  verify assertion, consume challenge
        ▼                                                    ▼
 authenticators{type=passkey, identifier=sha256(id)}   POST /account/sessions/token (existing createSession)
                                                         └─► session{provider=passkey,
                                                                     factors=[passkey, userVerification]}
  • Login ends in a token that goes through the existing account.createSession (per the Linear thread). Cookies, limits, alerts, events and audits are reused with no session-issuance refactor.
  • RP config lives in the policies API (PATCH /v1/project/policies/passkey: rpId, origins). It's toggled with project.updateAuthMethod('passkey'), off by default, and fails closed until configured.
  • The generic WebAuthn code lives in utopia-php/auth (packages/auth/src/Passkeys: Ceremony, RelyingParty, Origin, Counter, plus docs and unit tests). It wraps web-auth/webauthn-lib ^5.3, which the package lists as a suggested dependency so it keeps no hard Composer dependencies. Appwrite keeps a thin Ceremony subclass (fromProject() and storage types) and the RP ID validator, which needs utopia-php/domains. User deletion now cleans up authenticators and challenges.
  • updatePasskeyToken returns the TokenSecret model, a Token whose secret is not sensitive, since the caller has just proven possession (as MFAChallengeSecret does for challenge codes). The guest-supplied credential is reduced to the members of PublicKeyCredential.toJSON() before the ceremony.
  • Also: PATCH /account/passkeys/:id (rename), GET/PATCH/DELETE /users/:userId/passkeys[/:id] (admin, PATCH renames).
  • Sign-in verifies and stores the credential record inside a transaction, under a row lock on the authenticator. Concurrent assertions for one device-bound credential therefore see each other's counters: exactly one of 5 same-counter sign-ins succeeds, and the stored counter can't go backwards. Before, all 5 were accepted, [201,201,201,201,201]. It passes on PostgreSQL, MariaDB and MongoDB (replica set).
  • Fixes an inherited race in createSession: the token was deleted after the session was created, so concurrent exchanges of one token could each create a session. The token is now claimed with an atomic delete before any session is issued. A regression test fires 5 concurrent exchanges and expects exactly one 201 and one stored session; it failed before the fix, [201,201,401,401,401]. This covers every token login (magic URL, OTP, phone, OAuth2, custom), not only passkeys.

Schema

No new collections. Two existing project collections get new columns, added to existing projects by the V25 migration:

Collection Change Why
authenticators identifier string(64), nullable, unique index _key_identifier SHA-256 of the credential ID. Sign-in starts without knowing the user, so the credential is looked up by this. The unique index also stops one authenticator from being registered twice in a project.
authenticators name string(128), nullable The passkey's label. A column, not part of the encrypted data, so renames are plain updates and listPasskeys can query it.
authenticators accessedAt datetime, nullable, index _key_accessedAt Last sign-in with the passkey, null until first use. Queryable and indexed for listing by last use or finding stale passkeys.
challenges passkey string(16384), encrypted JSON Ceremony state kept between the two requests of a registration or sign-in: the WebAuthn challenge, a fingerprint of the RP config, what the finishing request must match (session and passkey IDs) and a version.
  • A passkey is an authenticators document with type=passkey, reusing the existing columns: verified, userId/userInternalId, and data (encrypted) for the WebAuthn credential record (public key, sign counter, backup flags) and, while a registration is pending, the ID of its challenge, which verification consumes. That is the same role data already plays for TOTP secrets. name and accessedAt are their own columns, so listPasskeys and users.listPasskeys accept queries on both. TOTP rows leave them null.
  • Existing TOTP authenticators keep identifier null. PostgreSQL and MariaDB allow repeated nulls under a unique index, and the Mongo adapter builds unique indexes with a partial filter, so they don't collide.
  • challenges.passkey stays JSON on purpose: it's read once by ID, then deleted, and never queried. Expired leftovers go through the existing challenge cleanup in the deletes worker. MFA challenges keep using token/code and leave it null.
  • RP config needs no schema change: rpId and origins are stored in the project's existing auths JSON as passkeyRpId and passkeyOrigins.

Decisions, based on how other providers do it

Decision Choice Aligned with
Does a passkey satisfy MFA? Yes: UV is required, so the session gets 2 factors and a fresh mfaUpdatedAt WorkOS, Clerk, Cognito, GitHub, Keycloak (Auth0 is the exception)
Step-up before add/remove Must have signed in or passed MFA within 10 min, else user_reauthentication_required Clerk (10m), Keycloak, Stytch, passkeys.dev
Who can enroll Any signed-in account, including anonymous or unverified ones, so passkey-only accounts are possible (anonymous session + passkey) Pocket ID; a single way in is the developer's and end user's call, as with email-OTP-only accounts
Registration options Discoverable, UV required, attestation none, ES256/RS256, excludeCredentials Keycloak passwordless, Cognito, Google
RP config Explicit RP ID + exact origins; HTTP only for localhost; RP ID locked once passkeys exist Supabase, Cognito, Pocket ID
Limits / lifetime 10 per user, 5-minute challenges, single use Supabase, Clerk; W3C default
Counter / backup Counter relaxed only for backup-eligible credentials; backup eligibility immutable; backup state kept in the record but not exposed, since it is self-reported and only current as of the passkey's last use W3C L3

Follow-ups: conditional UI (autofill) helpers in the SDKs, AAGUID-based default names, passkey signup.

E2E

PasskeysCustomClientTest has 24 tests: ownership, wrong origin/RP/project/challenge, forged and malformed credentials, replay, concurrency (exactly one of 5 parallel verifications wins), cap, toggle-off, RP lock, unverified/anonymous/blocked/deleted/recreated users, MFA, rename, and admin rename and delete. A software authenticator (packages/auth/tests/Passkeys/Authenticator.php) builds real CBOR/ES256 credentials and is shared with the package's 35 unit tests. Existing AuthMethods, Policies, Projects, MFA and token-session suites pass. The stale-session rejection has no e2e yet because it needs a 10-minute wait.

Browser run: Chrome virtual authenticator against a demo app on http://localhost:5173.

Signed up Passkey added
Signed in with passkey (no email, MFA satisfied) Removed passkey rejected

The passkey suite passes on PostgreSQL, MariaDB and MongoDB. Upgrade path: I dropped the new column, index and metadata from a project that already had TOTP authenticators, ran migrate, confirmed the unique index was recreated with null identifiers allowed, and re-ran the browser flow.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat/passkeys (after).

Metric Before After Change
🚀 Requests/sec 183.42 180.94 ⚪ -1.4%
⏱️ Latency P50 93.94 ms 95.41 ms ⚪ +1.6%
⏱️ Latency P95 227.47 ms 226.19 ms ⚪ -0.6%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 95.41 226.19 11,400 180.94 -1.28
Account 189.05 351.76 600 10.14 +13.09
TablesDB 91.26 175.97 6,200 100.97 -1.59
Storage 89.16 191.3 3,000 50.25 -7.18
Functions 135.25 266.19 1,600 27.48 -4.03

Top API waits (after)

API request Max wait (ms)
account.name.update 620.98
tablesdb.rows.create 433.79
account.prefs.update 429.54
functions.create 406.37
storage.buckets.create 403.93

@ChiragAgg5k
ChiragAgg5k marked this pull request as ready for review September 30, 2026 08:27
@ghost

ghost commented Sep 30, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Adds WebAuthn passkey enrollment, account and administrative management, and usernameless sign-in through the existing token-to-session flow. Introduces relying-party policies, encrypted ceremony storage, schema migrations, MFA integration, and concurrency coverage, and makes login-token exchanges single-use. Also updates OAuth2 state handling, migration cleanup, and deletion-worker iteration; the latest changes introduce an explicit secret-bearing token response model and filter sign-in credential fields.

Latest changes: The newest commits register a TokenSecret response model, use it for completed passkey sign-in instead of temporarily exposing sensitive fields, and allowlist top-level WebAuthn credential fields before verification.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 33
File Change
app/config/auth.php, app/config/errors.php, src/Appwrite/Extend/Exception.php Define passkey authentication and API errors.
app/config/collections/common.php, src/Appwrite/Migration/Version/V25.php Add authenticator lookup and listing fields, encrypted ceremony storage, photo attributes, indexes, and retired-scope migration.
app/controllers/api/account.php Integrate passkey MFA factors, atomic login-token consumption, OAuth2 application state, and unbound-token guest handling.
app/controllers/general.php, app/controllers/shared/api/auth.php Add recent-session and authentication-method checks and tighten preview redirects.
app/init/constants.php, app/init/models.php Register passkey constants and response models, including the new TokenSecret model.
composer.json, composer.lock, packages/auth/composer.json Wire package autoloading and WebAuthn dependencies.
packages/auth/AGENTS.md, packages/auth/README.md, packages/auth/docs/passkeys.md Document package conventions and reusable passkey ceremonies.
packages/auth/src/Passkeys/* Implement ceremonies, challenges, credential records, relying-party and origin validation, and counters.
packages/auth/tests/Passkeys/* Add a software authenticator and ceremony and origin unit coverage.
packages/domains/src/Validator/RegistrableDomain.php, packages/domains/tests/Validator/RegistrableDomainTest.php Add and test registrable-domain validation rejecting IP addresses and public suffixes.
src/Appwrite/Auth/MFA/Type.php, src/Appwrite/Auth/Passkey/* Connect passkey ceremonies and MFA factors to Appwrite and persist bound, single-use challenges.
src/Appwrite/Platform/Modules/Account/Http/Account/Passkeys/* Add enrollment, verification, listing, retrieval, rename, and deletion with recent-session protection.
src/Appwrite/Platform/Modules/Account/Http/Account/Tokens/Passkey/* Add sign-in challenges and token issuance with locked counter updates, credential-field filtering, and explicit secret-bearing responses.
src/Appwrite/Platform/Modules/Account/Services/Http.php Register account passkey endpoints.
src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php, src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php Initialize passkey authentication as disabled for new projects.
src/Appwrite/Platform/Modules/Project/Http/Project/Policies/*, src/Appwrite/Platform/Modules/Project/Services/Http.php Expose relying-party policies and lock RP IDs while credentials or active registrations exist.
src/Appwrite/Platform/Modules/Users/Http/Users/Passkeys/*, src/Appwrite/Platform/Modules/Users/Services/Http.php Add administrative passkey retrieval, listing, rename, and deletion.
src/Appwrite/Platform/Workers/Deletes.php Clean up authenticators, challenges, and photo files and use database iteration for grouped cleanup.
src/Appwrite/Utopia/Database/Validator/Queries/Passkeys.php Allow queries on passkey names, last-use timestamps, and system fields.
src/Appwrite/Utopia/Response.php, src/Appwrite/Utopia/Response/Filters/V26.php, src/Appwrite/Utopia/Response/Filters/V29.php, src/Appwrite/Utopia/Response/Model/* Expose passkey, policy, and TokenSecret response contracts with compatibility defaults.
tests/e2e/Services/Account/PasskeysCustomClientTest.php Cover passkey lifecycle, validation, ownership, MFA, concurrency, and administration.
tests/e2e/Services/Project/PoliciesBase.php, tests/e2e/Services/Projects/ProjectsConsoleClientTest.php, tests/unit/Utopia/ResponseTest.php Update policy, project-default, and response-contract coverage.
src/Appwrite/Auth/Passkey/Challenges.php Persist and consume bound, single-use ceremonies using caller-supplied challenge IDs.
packages/auth/tests/Passkeys/CeremonyTest.php Test ceremony validation and stored-record round trips; the latest change removes the obsolete Credential constructor argument.
src/Appwrite/Platform/Modules/Project/Services/Http.php Register the passkey policy endpoint.
src/Appwrite/Platform/Modules/Account/Http/Account/Passkeys/Create.php Start enrollment for signed-in accounts, supporting custom IDs and replacement of owned pending registrations.
src/Appwrite/Platform/Modules/Account/Http/Account/Passkeys/Verification/Update.php Added to the recentSession group, so verifying a registration needs a recent session.
src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Passkey/Update.php The RP ID lock also counts passkey registrations still inside the ceremony window.
src/Appwrite/Extend/Exception.php Removes USER_PASSKEY_UNAVAILABLE.
app/config/errors.php Removes the user_passkey_unavailable error entry.
src/Appwrite/Migration/Version/V25.php Adds the authenticators identifier and challenges data schema changes.
app/config/collections/common.php Adds photoId and photoSize user attributes.
app/init/constants.php Adds role length, photo storage folder and avatar storage metric constants.

Reviewed the commits since a07d70b · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Critical risk] Adds passkey authentication with database schema changes and new API endpoints.

The PR does not appear safe to merge until existing in-progress uploads can still be resumed by their creators.

Summary

The PR adds passkey registration and sign-in, including RP policies, storage, migration, and tests. Since the previous review, it also changes OAuth browser binding, storage upload authorization, webhook credential responses, and several other security-sensitive flows.

  • Existing in-progress uploads can become impossible for their creators to resume after deployment.
  • Webhook read-then-update clients can fail validation when they send back the newly masked password.

Reviews (8) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

Comment thread packages/auth/src/Passkeys/Counter.php Resolved
Comment thread app/controllers/api/account.php Resolved
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@greptile review

… holds

The column only carries passkey ceremony state, so `data` told a reader of the challenges table nothing. It stays JSON because it is read once by ID and deleted, never queried.
The passkey name is metadata the owner can already change; server keys get the same through PATCH /users/:userId/passkeys/:passkeyId, mirroring the account rename.
…dator

The RP ID rule (lowercase, not an IP, below a public suffix) is a domain rule, not a passkey one, so it moves to utopia-php/domains as RegistrableDomain next to PublicDomain and ApexDomain. The passkey-only part, allowing localhost, stays at the call site.
Sign-in methods are switched through auth methods and no other policy mirrors one, so the passkey policy keeps only the relying party: rpId and origins. The method's state reads from project.authMethods, which shows passkey from the 2.4.0 response format.
updatePasskeyVerification took both the passkey ID and its challenge ID, though the pending passkey already identifies its ceremony. It now stores the challenge ID it was issued with and verification consumes that one, so clients pass only the passkey ID and credential, as with MFA authenticators. The stored ID also replaces the registration nonce: a restarted registration points to its own challenge.
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

32 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (17)
  • php.appwrite.permissive-write-permission (8)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

…list the credential

showSensitive() is reserved for event payloads, so updatePasskeyToken returns the new TokenSecret model, which exposes the secret the caller has just proven it may hold (as MFAChallengeSecret does for challenge codes). The guest-supplied credential is reduced to the members of PublicKeyCredential.toJSON() before it reaches the ceremony.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants