From 5ede3667587cc928ab13959cf16a3f8555c7cc27 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 03:57:52 +0000 Subject: [PATCH] fix: give emailed-link pages their own limit, publish only missing migrations and rename the email code step --- docs/configuration.md | 4 +- docs/events.md | 2 +- docs/extending.md | 4 +- docs/factors.md | 6 +-- docs/installation.md | 2 +- docs/owasp-asvs.md | 8 ++-- docs/policies.md | 2 +- docs/quick-start.md | 2 +- docs/security-log-and-emails.md | 2 +- docs/security.md | 2 +- routes/keyring.php | 28 ++++++------- src/Changes/AuthenticatorChanges.php | 2 +- src/Console/InstallCommand.php | 40 ++++++++++++++++--- src/Events/RateLimited.php | 6 +-- src/Factors/EmailCode.php | 8 ++-- .../Controllers/EmailChangeController.php | 5 ++- src/KeyringServiceProvider.php | 12 +++++- src/Support/PasswordRules.php | 2 +- src/UserKeyring.php | 2 +- .../app/Providers/KeyringServiceProvider.php | 2 +- tests/Feature/AuthenticatorManagementTest.php | 4 +- tests/Feature/CommandsTest.php | 28 ++++++++++++- tests/Feature/ConformanceTest.php | 2 +- tests/Feature/CustomFactorTest.php | 4 +- tests/Feature/DevicesAndSessionsTest.php | 2 +- tests/Feature/EmailChangeHardeningTest.php | 2 +- tests/Feature/EmailCodeTest.php | 18 ++++----- tests/Feature/EmailedLinksTest.php | 25 +++++++++++- tests/Feature/ExtendingTest.php | 2 +- tests/Feature/RateLimitKeysTest.php | 2 +- tests/Feature/SecurityLogLimitsTest.php | 8 ++++ tests/Feature/ServiceProviderTest.php | 3 +- tests/Feature/TweakableDefaultsTest.php | 2 +- tests/Unit/KeyedHashTest.php | 2 +- 34 files changed, 171 insertions(+), 74 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 5a6b3090..87a9ff26 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -378,7 +378,9 @@ RateLimiter::for('keyring', fn (Request $request) => Limit::perMinute(10) `GET /login/{factor}/options` uses its own limiter, `keyring-login-options`, which allows 60 requests a minute per IP address. Login pages fetch the options on every load for passkey autofill, and when the limit is hit autofill stops offering passkeys until the next minute. Define the same limiter to change it. -`TooManyAttempts` is what Keyring's own two limiters answer with: Laravel's usual `429`, after dispatching `Keyring\Events\RateLimited`, which the security log records as [`rate_limited`](security-log-and-emails.md#entry-types). Laravel has no event of its own for a refused request, so a limiter you define without that `response()` still limits and writes nothing to the log. +The pages that emailed links open (confirming or undoing an email change, verifying an address, reporting a device) only show a button, so they use a third limiter, `keyring-pages`, at 60 requests a minute per IP address. Pressing the button is held to the `keyring` limit. Opening both ends of an email change, or reloading a page, doesn't use up the attempts the buttons get. Define the same limiter to change it. + +`TooManyAttempts` is what Keyring's own three limiters answer with: Laravel's usual `429`, after dispatching `Keyring\Events\RateLimited`, which the security log records as [`rate_limited`](security-log-and-emails.md#entry-types). Laravel has no event of its own for a refused request, so a limiter you define without that `response()` still limits and writes nothing to the log. ## Messages and Translations diff --git a/docs/events.md b/docs/events.md index 2b1d6b51..e8a7811a 100644 --- a/docs/events.md +++ b/docs/events.md @@ -93,7 +93,7 @@ An assessment that ends in `Action::allow()` dispatches nothing. See [Risk](risk | Event | When | Properties | |---|---|---| | `AccessRefused` | A signed-in user asked for an authenticator, device or session that isn't theirs, or that doesn't exist (both get the same 404, so the event doesn't tell them apart), or opened an email verification link made for another account. | `user`, `resource` (`authenticator`, `device`, `session` or `email_verification`), `id` (what was asked for, as it was sent; for a session, its handle) | -| `RateLimited` | The form limiter refused a request to one of Keyring's routes outside the sign-in limits: registration, a reset, a change, an emailed link, or passkey options. | `user` (whoever is signed in, otherwise null), `limiter` (`keyring` or `keyring-login-options`), `route` (its name), `retryAfter` (seconds) | +| `RateLimited` | The form limiter refused a request to one of Keyring's routes outside the sign-in limits: registration, a reset, a change, an emailed link or the page it opens, or passkey options. | `user` (whoever is signed in, otherwise null), `limiter` (`keyring`, `keyring-pages` or `keyring-login-options`), `route` (its name), `retryAfter` (seconds) | | `EnrollmentRefused` | A sign-in method wasn't added. | `user`, `factor`, `reason`: `invalid` (the factor turned the confirmation down: a wrong code, a key it won't take) or `not_allowed` (the account may not add one yet) | | `AuthenticatorRemovalRefused` | A sign-in method was kept, because removing it would have left the user unable to sign in the way their policy requires. | `user`, `authenticator` | | `LinkRefused` | An emailed link was refused: a change that doesn't exist, a wrong or ended token, or a signature that didn't match or had expired. | `link`, `reason` (see [Refused Links](security-log-and-emails.md#refused-links)), `user` (whose email change it was, otherwise null) | diff --git a/docs/extending.md b/docs/extending.md index 61e5b7a4..2a864004 100644 --- a/docs/extending.md +++ b/docs/extending.md @@ -31,7 +31,7 @@ This page lists them all, with where each is explained. [Recipes](recipes.md) ha | Validation and status messages | The `keyring-lang` translation files | [Messages and Translations](configuration.md#messages-and-translations) | | The route prefix, domain and middleware | `prefix`, `domain` and `middleware` | [Routes](configuration.md#routes) | | The middleware on account changes | `changes_middleware` | [Account Changes and Enrollment](configuration.md#account-changes-and-enrollment) | -| The form rate limits | The `keyring` and `keyring-login-options` rate limiters | [Rate Limits](configuration.md#pending-logins-timebox-and-rate-limits) | +| The form rate limits | The `keyring`, `keyring-pages` and `keyring-login-options` rate limiters | [Rate Limits](configuration.md#pending-logins-timebox-and-rate-limits) | | Who may sign in at all | `Keyring::allowSignInWhen()` | [Who May Sign In](sign-in-flow.md#who-may-sign-in) | | Who may add a sign-in method | `Keyring::allowEnrollmentWhen()` | [Who May Enroll](authenticators.md#who-may-enroll) | | Whether registration says when an address is taken | `registration.reveal_taken` | [Registration](sign-in-flow.md#registration) | @@ -72,7 +72,7 @@ Set `routes` to `false` and call `Keyring::routes()` inside your own group to ch A few things have no switch, because turning them off would quietly remove a protection: -- Plain `EmailCode::class` is refused. `EmailCode::asSecondFactor()` is the switch, and it says what you're accepting. +- Plain `EmailCode::class` is refused. `EmailCode::asExtraStep()` is the switch, and it says what you're accepting. - A user can't remove their last way to sign in, and removing the last second factor takes the password, typed again and long enough to stand alone. - An email change is confirmed from the new address, announced to the old one, and can be undone from there. - Trusting a device takes a real second factor, and a confirm page opened without a step-up behind it never accepts recovery codes. diff --git a/docs/factors.md b/docs/factors.md index bdd6a638..1bc84451 100644 --- a/docs/factors.md +++ b/docs/factors.md @@ -70,7 +70,7 @@ Removing a factor from the list doesn't delete anyone's authenticators. A user w |---|---|---|---|---|---| | `password` | `Password` | knowledge | yes | no | 40 | | `totp` | `Totp` | possession | no | yes | 60 | -| `email-code` | `EmailCode::asSecondFactor()` | address (not a factor) | no | yes, one | 30 | +| `email-code` | `EmailCode::asExtraStep()` | address (not a factor) | no | yes, one | 30 | | `recovery` | `RecoveryCodes` | possession | no | yes, one set | 0 | | `passkey` | `WebAuthn::passkeys()` | possession, plus inherence when the user was verified | yes | yes | 100 | | `security-key` | `WebAuthn::securityKeys()` | possession, plus inherence when the user was verified | no | yes | 90 | @@ -122,13 +122,13 @@ The `otpauth://` URL and the QR code then say `algorithm=SHA256`, and enrolling An eight digit code sent to the user's current email address. It's opt-in, because NIST SP 800-63B-4 doesn't accept email as an authenticator at any level (Sec. 3.1.3.1): whoever controls the inbox can also reset the password, so for a user with nothing else beside their password, the inbox is the whole account. Registering plain `EmailCode::class` throws an exception that says so. To accept that risk: ```php -Keyring::factors([Password::class, Totp::class, EmailCode::asSecondFactor()]); +Keyring::factors([Password::class, Totp::class, EmailCode::asExtraStep()]); ``` Codes are eight digits, last ten minutes and allow five wrong guesses. To change that: ```php -EmailCode::asSecondFactor(length: 6, expireAfter: '5m', maxGuesses: 3) +EmailCode::asExtraStep(length: 6, expireAfter: '5m', maxGuesses: 3) ``` Six digits is the shortest a code can be and ten minutes the longest it can last, the bounds OWASP ASVS 5.0.0 sets for codes sent out of band (requirements 6.5.4 and 6.5.5). Asking for less or for longer throws a `LogicException` on that line. diff --git a/docs/installation.md b/docs/installation.md index e8c02ff8..bdcc0b45 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -50,7 +50,7 @@ php artisan keyring:install --factor=totp --factor=passkeys --feature=registrati `--factor` takes `totp`, `passkeys`, `security-keys` or `email-codes`. `--feature` takes `registration`, `reset-passwords`, `email-verification`, `update-passwords`, `manage-authenticators`, `devices`, `email-changes` or `security-log`, and replaces the defaults (`registration`, `reset-passwords`, `email-verification`, `update-passwords` and `security-log`), so list those too if you want them. An unknown value stops the command before it writes anything, and an unknown feature in `config/keyring.php` stops the app booting, rather than leaving that feature off. `--require-second-factor` and `--optional-second-factor` answer the second question; requiring one without a sign-in method that counts stops the command too. `--emails` and `--no-emails` say whether the provider registers the security notices about changes; the classes are published either way. -Pass `--force` to overwrite files that already exist; without it, existing files are skipped, and with `config/keyring.php` already there it doesn't ask which features to turn on. It's safe to run again: the migrations are only published once, so they're never added twice under new timestamps. Running it again on an older install adds any new actions, but leaves your provider alone, so register them there yourself. Until you do, the routes that need them fail with an exception that says which `Keyring::*Using()` call is missing. +Pass `--force` to overwrite files that already exist; without it, existing files are skipped, and with `config/keyring.php` already there it doesn't ask which features to turn on. It's safe to run again: a migration you already have is never added a second time under a new timestamp, and one a later version brought is added on its own. Running it again on an older install adds any new actions and notifications too, but leaves your provider alone, so register them there yourself. A new action's routes fail until you do, with an exception that says which `Keyring::*Using()` call is missing. A new notification is simply never sent: add its line to `Keyring::notifications()`, using the [list of emails](security-log-and-emails.md#security-emails) for the key. If you're moving from Fortify, read [Upgrading From Fortify](upgrading-from-fortify.md) before migrating. diff --git a/docs/owasp-asvs.md b/docs/owasp-asvs.md index bacd8e6f..700d2eec 100644 --- a/docs/owasp-asvs.md +++ b/docs/owasp-asvs.md @@ -123,7 +123,7 @@ Everything in Level 1, and: 7. **Write down** your list of words a password must not be made up of and put it in `passwords.context` ([6.1.2, 6.2.11](#v62-password-security)), your session timeouts and why you chose them ([7.1.1](#v71-session-management-documentation)), and how many sessions an account may have (100 unless you change `sessions.max`, the oldest ended first) ([7.1.2](#v71-session-management-documentation)). 8. **Decide who may run `php artisan keyring:sign-out`** ([7.4.5](#v74-session-termination)), and a process for someone who has lost their second factor and their recovery codes ([6.4.4](#v64-authentication-factor-lifecycle-and-recovery)). -Email codes count toward no assurance level: a password and an emailed code is an AAL1 session, in Keyring's levels as in NIST's, and doesn't pass `keyring:aal2` or `keyring.enrolled`. Level 3 rules them out altogether. Leave `EmailCode::asSecondFactor()` out unless you need it. +Email codes count toward no assurance level: a password and an emailed code is an AAL1 session, in Keyring's levels as in NIST's, and doesn't pass `keyring:aal2` or `keyring.enrolled`. Level 3 rules them out altogether. Leave `EmailCode::asExtraStep()` out unless you need it. ## Level 3 @@ -152,7 +152,7 @@ Everything in Level 2, and: With `ifEnrolled()` a new user signs in with their password, and `keyring.enrolled:aal3` keeps them on your enrollment page until they've added a key; from then on they need it every time. Drop `ifEnrolled()` if you hand out keys before an account first signs in. See [Requiring Attestation](passkeys.md#requiring-attestation). Without attestation, "hardware" is only what the key says about itself. -2. **No email codes, and no SMS** ([6.3.6](#v63-general-authentication-security), [6.6.1](#v66-out-of-band-authentication-mechanisms)). Don't register `EmailCode::asSecondFactor()` or an SMS factor of your own. Recovery codes can't meet `aal3` either, so a lost key goes to your support process. +2. **No email codes, and no SMS** ([6.3.6](#v63-general-authentication-security), [6.6.1](#v66-out-of-band-authentication-mechanisms)). Don't register `EmailCode::asExtraStep()` or an SMS factor of your own. Recovery codes can't meet `aal3` either, so a lost key goes to your support process. 3. **Tell users about suspicious sign ins** ([6.3.5](#v63-general-authentication-security)). Turn on `Features::devices()`, which brings the `new_device` notice and the `NewDevice` and `InactiveAccount` signals in a new install; in an existing one, uncomment them in your `KeyringServiceProvider`. Keep the security log on. Then have your risk response notify for a sign in after a long quiet period or after several failures, as [Telling the User](risk.md#telling-the-user) shows: by itself each of those only asks for a second factor. For a sign in from an unusual place, bind a [locator](devices-and-sessions.md#locations) and add `NewCountry` or `ImpossibleTravel`. 4. **Keep the default registration** ([6.3.8](#v63-general-authentication-security)): `registration.reveal_taken` stays `false`. 5. **Ask again before your most sensitive operations** ([7.5.3](#v75-defenses-against-session-abuse)): `keyring:aal3` or `keyring.fresh:5m` on those routes. AAL3 lapses after 15 minutes idle or 12 hours. @@ -198,7 +198,7 @@ Everything in Level 2, and: | 6.3.3 Multi-factor authentication is required; a hardware factor at Level 3 | 2 | Needs setup | A default install has no second factor to require. Level 2: a second factor registered and `keyring.enrolled`, which the installer sets up when you pick one and answer yes to requiring it. Level 3: `Requirement::aal3()`, `keyring.enrolled:aal3` and `requireAttestation()`. See [Level 2](#level-2) and [Level 3](#level-3). Until a user enrolls they are signed in, and held at your enrollment page. `keyring.enrolled` checks the account, not the session: see "remember me" in [Level 2](#level-2). | | 6.3.4 No undocumented pathways, and consistent strength across them | 2 | Met | Every proof runs one pipeline. Three things don't go through it: "remember me", which carries a session on at no level; registration with `registration.reveal_taken`, which signs the new user in on their password without asking the policy; and your own `Auth::login()`, registered at no level. Start a social login with [`Keyring::attempt()`](sign-in-flow.md#starting-a-sign-in-yourself) instead. | | 6.3.5 Users are notified of suspicious authentication attempts | 3 | Partly | A default install emails `account_locked`, when the password or a passkey is refused until a reset (at the cap on failures in a row, or sooner with `limits.lock_after`; an ordinary lockout that lifts by itself emails nobody), and `suspicious_activity`, when what the risk signals find adds up to a level that notifies. It adds `second_factor_failed` once you pick a sign-in method besides the password, and `new_device` with `Features::devices()`. Left to you: a sign in after a long quiet period or after several failures is found (`InactiveAccount`, `SuccessAfterFailures`) but each alone only asks for a second factor, so have your response notify for them ([Telling the User](risk.md#telling-the-user)); and a sign in from an unusual place needs a [locator](devices-and-sessions.md#locations) and a location signal. See [Level 3](#level-3). Each kind is capped at five an hour per account. | -| 6.3.6 Email isn't an authentication factor | 3 | Met by default | Don't register `EmailCode::asSecondFactor()`. The factor throws without that explicit opt-in, and an emailed code never counts toward a level. | +| 6.3.6 Email isn't an authentication factor | 3 | Met by default | Don't register `EmailCode::asExtraStep()`. The factor throws without that explicit opt-in, and an emailed code never counts toward a level. | | 6.3.7 Users are notified when authentication details change | 3 | Met by default | A default install mails a changed or reset password, a sign-in method added or removed, new recovery codes, a recovery code used and a changed email address, and an undone email change once `Features::emailChanges()` is on. Renaming a sign-in method or changing the default one sends nothing. An account whose address isn't verified is sent none of these, except the notice of the reset that proves it. A password your own code sets with `Keyring::withoutProtection()` is logged, not announced: dispatch `Keyring\Events\PasswordChanged` yourself if users should hear of it. Installing with `--no-emails`, or without the published provider, sends none, and nothing warns. | | 6.3.8 Valid users can't be deduced from sign in, registration or forgot password | 3 | Met by default | All three answer the same for every address, in the same time. Keep `registration.reveal_taken` off: with it on, registration says when an address is taken, and the conformance check is skipped, not failed. A username of your own that must be unique will still say when it's taken, and mail that bounces is outside the request. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). | @@ -309,7 +309,7 @@ ASVS's other chapters are about your whole application. These are the requiremen | | | What it means for your app | |---|---|---| | 1.2.2 URLs are built with untrusted data encoded | Met | Server side, links are built from named routes. The browser package encodes every factor key and ID it puts in a path. A route you override with `configureRoutes()` is used as written, so [encode in yours](frontend.md#changing-routes). | -| 2.4.1 Anti-automation controls | Met by default | The [rate limits](security.md#rate-limiting), and the `keyring` and `keyring-login-options` limiters on the other forms. All are options, and you can redefine the limiters: only a password minimum under 8, a sent code under six digits or over ten minutes, a TOTP window over one step and an RSA floor under 2048 bits are refused. | +| 2.4.1 Anti-automation controls | Met by default | The [rate limits](security.md#rate-limiting), and the `keyring`, `keyring-pages` and `keyring-login-options` limiters on the other forms. All are options, and you can redefine the limiters: only a password minimum under 8, a sent code under six digits or over ten minutes, a TOTP window over one step and an RSA floor under 2048 bits are refused. | | 2.4.2 Flows require realistic human timing (Level 3) | Yours | Keyring has no bot check and no minimum time on a form. Where a CAPTCHA or a challenge goes is in [Bot Checks](security.md#bot-checks). | | 3.3.1, 3.3.3 `Secure` cookies with a `__Host-` or `__Secure-` prefix | Met by default | Keyring's two cookies, over HTTPS. A name you set yourself (`devices.cookie`, `sessions.remember_cookie`) is used as written, so the prefix is yours to add. Laravel's session cookie is yours to name and secure: see [Secure Cookies](security.md#secure-cookies). | | 3.4.1 `Strict-Transport-Security` on every response | Yours | Keyring sends none: it would only cover its own routes. See [HTTPS and HSTS](security.md#https-and-hsts). | diff --git a/docs/policies.md b/docs/policies.md index 037585cd..febd2d4c 100644 --- a/docs/policies.md +++ b/docs/policies.md @@ -55,7 +55,7 @@ Keyring works out an assurance level from what a user has proved in their sessio | Proved | Level | |---|---| | A password | AAL1 | -| A password and an email code, with [`EmailCode::asSecondFactor()`](factors.md#email-codes) | AAL1: NIST doesn't accept email as an authenticator | +| A password and an email code, with [`EmailCode::asExtraStep()`](factors.md#email-codes) | AAL1: NIST doesn't accept email as an authenticator | | A password and a TOTP or recovery code | AAL2 | | A passkey that syncs (iCloud Keychain, Google Password Manager...) | AAL2 | | A passkey or security key that stays on its device, added without attestation, alone or with a password | AAL2 | diff --git a/docs/quick-start.md b/docs/quick-start.md index aab68663..21d195ba 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -124,7 +124,7 @@ class SecurityController | `devices` | Where the user is signed in, with `Features::devices()`. The same list as [`GET /user/devices`](devices-and-sessions.md#listing-and-revoking-devices). | | `activity` | Recent [security log](security-log-and-emails.md#showing-recent-activity) entries, with `Features::securityLog()`. | -From there the page uses Keyring's routes: [`/user/authenticators`](authenticators.md#routes) to add, rename and remove sign-in methods, [`/user/devices`](devices-and-sessions.md#routes) to sign devices out, [`PUT /user/password`](protected-changes.md#changing-the-password) and [`POST /user/email`](protected-changes.md#changing-the-email-address). The [browser package](frontend.md#managing-authenticators) wraps the authenticator routes, including the passkey ceremony. +From there the page uses Keyring's routes: [`/user/authenticators`](authenticators.md#routes) to add, rename and remove sign-in methods, [`/user/devices`](devices-and-sessions.md#routes) to sign devices out, [`/user/sessions`](devices-and-sessions.md#listing-and-ending-sessions) to list sessions and end one, [`PUT /user/password`](protected-changes.md#changing-the-password) and [`POST /user/email`](protected-changes.md#changing-the-email-address). The [browser package](frontend.md#managing-authenticators) wraps the authenticator routes, including the passkey ceremony. Those routes need a [fresh verification](step-up.md#fresh-verification), 15 minutes by default. Put the same middleware on the page, after `auth`, so users confirm once when they open it rather than halfway through adding a passkey: diff --git a/docs/security-log-and-emails.md b/docs/security-log-and-emails.md index bf545ec6..13a09e23 100644 --- a/docs/security-log-and-emails.md +++ b/docs/security-log-and-emails.md @@ -68,7 +68,7 @@ How long those lines are kept, and who can read them, is then up to that channel | `factor_failed` | warning | A factor failed. | | | `second_factor_failed` | warning | A factor failed during a login after a correct password. | | | `locked_out` | warning | A rate limit started refusing an IP address for a factor, whether the answer said so or was that of a wrong password. [Logged once](#refusals-that-repeat), not for each request it refuses. Not linked to a user. | `retry_after` | -| `rate_limited` | warning | The [form limiter](configuration.md#pending-logins-timebox-and-rate-limits) started refusing requests to one of Keyring's other routes: registration, a reset, a change, an emailed link, or passkey options. [Logged once](#refusals-that-repeat) for each wait, per route. Linked to the signed-in user when there is one. | `limiter` (`keyring` or `keyring-login-options`), `route` (its name), `retry_after` | +| `rate_limited` | warning | The [form limiter](configuration.md#pending-logins-timebox-and-rate-limits) started refusing requests to one of Keyring's other routes: registration, a reset, a change, an emailed link or the page it opens, or passkey options. [Logged once](#refusals-that-repeat) for each wait, per route. Linked to the signed-in user when there is one. | `limiter` (`keyring`, `keyring-pages` or `keyring-login-options`), `route` (its name), `retry_after` | | `account_locked` | warning | Failed attempts got the password or a passkey refused until a password reset: the cap on failures in a row, or `limits.lock_after`. | | | `signed_out` | info | The user signed out. | | | `authenticator_added`, `authenticator_removed` | notice | | `name` | diff --git a/docs/security.md b/docs/security.md index ed2438a4..eba7b2db 100644 --- a/docs/security.md +++ b/docs/security.md @@ -154,7 +154,7 @@ The failures in a row and the locks held until a reset are in your database eith - Policies count distinct categories, so two factors of the same kind are never treated as multi-factor. AAL2 further needs one of the two to be something the user has (NIST SP 800-63B-4, Sec. 2.2.1): a password beside a factor that is only a biometric is an AAL1 session. - Assurance levels follow NIST SP 800-63B-4 as far as a library can check. A passkey that syncs reaches AAL2. AAL3 needs a phishing-resistant key that reports on every sign in that it can't leave its device, that was added with a verified attestation, and that either verified the user itself or was used with a password: another authenticator's user verification is never counted beside it. A key nothing vouches for stays at AAL2, though a policy or route can still ask for one with `deviceBound()`. - NIST AAL3 further needs authenticators and verifier cryptography validated to FIPS 140. Keyring can't supply or check either, so a session it calls AAL3 has met NIST's rules for the authentication and nothing more. -- Email codes are opt-in (`EmailCode::asSecondFactor()`), since NIST doesn't accept email as an authenticator and the inbox can also reset the password. A code is a step at sign in and never a factor: a password and an emailed code is an AAL1 session, doesn't pass `keyring:aal2` or `keyring.enrolled`, doesn't earn a trusted device, and can't stand in for a possession factor the account has. +- Email codes are opt-in (`EmailCode::asExtraStep()`), since NIST doesn't accept email as an authenticator and the inbox can also reset the password. A code is a step at sign in and never a factor: a password and an emailed code is an AAL1 session, doesn't pass `keyring:aal2` or `keyring.enrolled`, doesn't earn a trusted device, and can't stand in for a possession factor the account has. - A passkey or security key only counts as inherence when it actually verified the user that time. - The first recovery codes are shown to a session that has proved two factors: confirming a new sign-in method takes proving it, and the session counts that proof from the same response (NIST SP 800-63B-4, Sec. 3.1.2.1). Later sets need a fresh verification of both. - With `noDowngrade()`, users with a passkey or security key can't be offered a weaker way in. Recovery codes stay on offer as the way back in, unless you pass `except: []`. diff --git a/routes/keyring.php b/routes/keyring.php index c9218713..cbb682a1 100644 --- a/routes/keyring.php +++ b/routes/keyring.php @@ -120,24 +120,24 @@ // isn't signed in is sent to sign in by the controller, which remembers the // link first where an unverified account can only sign in after following it. if (Features::enabled(Features::emailVerification())) { - Route::get('/email/verify/{id}/{hash}', [EmailVerificationController::class, 'page'])->middleware(['keyring.signed:relative', 'throttle:keyring'])->name('verification.verify'); + Route::get('/email/verify/{id}/{hash}', [EmailVerificationController::class, 'page'])->middleware(['keyring.signed:relative', 'throttle:keyring-pages'])->name('verification.verify'); } // Emailed links. GET only shows a page with a button and the POST acts, so a // mail scanner that opens a link changes nothing. The link's token or // signature is in its URL, and the page posts it in the body, so the request // that acts doesn't put it in a URL a second time. keyring.signed is -// Laravel's signed middleware, which also logs the links it refuses. -Route::middleware('throttle:keyring')->group(function () { - if (Features::enabled(Features::emailChanges())) { - Route::get('/email-changes/{change}/confirm/{token}', [EmailChangeController::class, 'page'])->name('keyring.email.confirm'); - Route::post('/email-changes/{change}/confirm', [EmailChangeController::class, 'confirm'])->name('keyring.email.confirm.store'); - Route::get('/email-changes/{change}/revert/{token}', [EmailChangeController::class, 'page'])->name('keyring.email.revert'); - Route::post('/email-changes/{change}/revert', [EmailChangeController::class, 'revert'])->name('keyring.email.revert.store'); - } +// Laravel's signed middleware, which also logs the links it refuses. The +// pages have a looser limit of their own, so opening them doesn't use up +// the few tries their buttons get. +if (Features::enabled(Features::emailChanges())) { + Route::get('/email-changes/{change}/confirm/{token}', [EmailChangeController::class, 'page'])->middleware('throttle:keyring-pages')->name('keyring.email.confirm'); + Route::post('/email-changes/{change}/confirm', [EmailChangeController::class, 'confirm'])->middleware('throttle:keyring')->name('keyring.email.confirm.store'); + Route::get('/email-changes/{change}/revert/{token}', [EmailChangeController::class, 'page'])->middleware('throttle:keyring-pages')->name('keyring.email.revert'); + Route::post('/email-changes/{change}/revert', [EmailChangeController::class, 'revert'])->middleware('throttle:keyring')->name('keyring.email.revert.store'); +} - if (Features::enabled(Features::devices())) { - Route::get('/devices/{device}/report', [DeviceController::class, 'page'])->middleware('keyring.signed:relative')->name('keyring.devices.report'); - Route::post('/devices/{device}/report', [DeviceController::class, 'report'])->middleware(ValidatePostedSignature::class)->name('keyring.devices.report.store'); - } -}); +if (Features::enabled(Features::devices())) { + Route::get('/devices/{device}/report', [DeviceController::class, 'page'])->middleware(['keyring.signed:relative', 'throttle:keyring-pages'])->name('keyring.devices.report'); + Route::post('/devices/{device}/report', [DeviceController::class, 'report'])->middleware([ValidatePostedSignature::class, 'throttle:keyring'])->name('keyring.devices.report.store'); +} diff --git a/src/Changes/AuthenticatorChanges.php b/src/Changes/AuthenticatorChanges.php index 6609f50a..9f51a0a4 100644 --- a/src/Changes/AuthenticatorChanges.php +++ b/src/Changes/AuthenticatorChanges.php @@ -137,7 +137,7 @@ public function remove(Authenticatable&Model $user, string $id, #[\SensitivePara return [$authenticator, false]; } - if ($keyring->hasSecondFactor() && ! $left->hasSecondFactor()) { + if ($keyring->hasExtraStep() && ! $left->hasExtraStep()) { $this->ensurePasswordStandsAlone($user, $password); } diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php index d483ea74..e4cec7d2 100644 --- a/src/Console/InstallCommand.php +++ b/src/Console/InstallCommand.php @@ -52,7 +52,7 @@ class InstallCommand extends Command 'totp' => ['Authenticator app', 'Totp::class,'], 'passkeys' => ['Passkeys', 'WebAuthn::passkeys(),'], 'security-keys' => ['Security keys, as a second factor', 'WebAuthn::securityKeys(),'], - 'email-codes' => ['Email codes, as an extra step at sign in (not a second factor)', 'EmailCode::asSecondFactor(),', 'a password and an emailed code is AAL1.'], + 'email-codes' => ['Email codes, as an extra step at sign in (not a second factor)', 'EmailCode::asExtraStep(),', 'a password and an emailed code is AAL1.'], ]; /** @@ -106,6 +106,8 @@ class InstallCommand extends Command protected const string STUBS = __DIR__.'/../../stubs'; + protected const string MIGRATIONS = __DIR__.'/../../database/migrations'; + public function handle(Filesystem $files): int { $unknown = array_filter([ @@ -148,10 +150,7 @@ public function handle(Filesystem $files): int $features = config('keyring.features'); } - // Publishing again would add the migrations twice, under new timestamps. - if ($files->glob(database_path('migrations/*_create_keyring_authenticators_table.php')) === []) { - $this->callSilently('vendor:publish', ['--tag' => 'keyring-migrations']); - } + $migrations = $this->publishMigrations($files); if ($writesProvider) { $files->ensureDirectoryExists(dirname($provider)); @@ -172,7 +171,7 @@ public function handle(Filesystem $files): int $this->components->bulletList(array_filter([ $this->userModelHasKeyring() ? null : 'Add use Keyring\Concerns\HasKeyring; to your User model', in_array(Features::emailVerification(), $features, true) ? 'Make your User model implement MustVerifyEmail' : null, - $this->migrated() ? null : 'Run php artisan migrate', + $migrations === 0 && $this->migrated() ? null : 'Run php artisan migrate', 'Build the auth/* pages Keyring renders, see the "Quick Start" docs', $writesConfig ? 'Set support_contact in config/keyring.php to a page or an address users can reach you at: the emails then say who to contact if something wasn\'t them' : null, match (true) { @@ -463,6 +462,35 @@ protected function withoutUnusedImports(string $code): string return (string) preg_replace_callback('/^use [\w\\\\]+\\\\(\w+);\n/m', fn (array $import) => preg_match_all('/\b'.$import[1].'\b/', $code) > 1 ? $import[0] : '', $code); } + /** + * Publish the migrations this app doesn't have yet, and return how many + * that was. Publishing the whole tag again would add the ones it has a + * second time under new timestamps, so each is matched by its name. One + * added by a later version follows the app's own, in Keyring's order. + */ + protected function publishMigrations(Filesystem $files): int + { + $missing = array_values(array_filter( + $files->glob(self::MIGRATIONS.'/*.php'), + fn (string $path) => $files->glob(database_path('migrations/*_'.self::migrationName($path))) === [], + )); + + foreach ($missing as $index => $path) { + $files->ensureDirectoryExists(database_path('migrations')); + $files->copy($path, database_path('migrations/'.now()->addSeconds($index)->format('Y_m_d_His').'_'.self::migrationName($path))); + } + + return count($missing); + } + + /** + * A migration's file name without the date it starts with. + */ + protected static function migrationName(string $path): string + { + return (string) preg_replace('/^\d{4}_\d{2}_\d{2}_\d{6}_/', '', basename($path)); + } + /** * Write a file the app owns, leaving anything already there unless --force. */ diff --git a/src/Events/RateLimited.php b/src/Events/RateLimited.php index 8c6f18b9..36060ca3 100644 --- a/src/Events/RateLimited.php +++ b/src/Events/RateLimited.php @@ -10,9 +10,9 @@ /** * A rate limiter on Keyring's form routes refused a request: "keyring" on - * registration, resets, changes and the emailed links, or - * "keyring-login-options" on passkey options. The sign-in limits have their - * own event (Lockout). + * registration, resets, changes and the buttons on emailed links, + * "keyring-pages" on the pages those links open, or "keyring-login-options" + * on passkey options. The sign-in limits have their own event (Lockout). */ class RateLimited { diff --git a/src/Factors/EmailCode.php b/src/Factors/EmailCode.php index 48fa7b75..b71c5519 100644 --- a/src/Factors/EmailCode.php +++ b/src/Factors/EmailCode.php @@ -18,7 +18,7 @@ * A code emailed to the user's current address. Opt-in only: whoever controls * the inbox can reset the password too, so for a user with nothing else * beside their password, the inbox is the whole account. Register - * EmailCode::asSecondFactor() to accept that. + * EmailCode::asExtraStep() to accept that. * * NIST SP 800-63B-4 doesn't take email as an authenticator at any level * (Sec. 3.1.3.1), so a code is a step at sign in and never a factor: it @@ -34,7 +34,7 @@ final public function __construct(bool $acceptRisk = false, ?int $length = null, if (! $acceptRisk) { throw new InvalidArgumentException( 'Email codes are not a second factor: whoever controls the inbox can also reset the password. ' - .'Register EmailCode::asSecondFactor() to ask for them at sign in anyway.', + .'Register EmailCode::asExtraStep() to ask for them at sign in anyway.', ); } @@ -51,10 +51,10 @@ final public function __construct(bool $acceptRisk = false, ?int $length = null, * Accept email codes as a second step at sign in, knowing a password and * a code is still AAL1. * Eight digits, good for ten minutes and five wrong guesses, unless you - * say otherwise: EmailCode::asSecondFactor(length: 6, expireAfter: '5m'). + * say otherwise: EmailCode::asExtraStep(length: 6, expireAfter: '5m'). * Six digits is the fewest and ten minutes the longest Keyring allows. */ - public static function asSecondFactor(?int $length = null, ?string $expireAfter = null, ?int $maxGuesses = null): static + public static function asExtraStep(?int $length = null, ?string $expireAfter = null, ?int $maxGuesses = null): static { return new static(true, $length, $expireAfter, $maxGuesses); } diff --git a/src/Http/Controllers/EmailChangeController.php b/src/Http/Controllers/EmailChangeController.php index 6eff1347..2ec5a11d 100644 --- a/src/Http/Controllers/EmailChangeController.php +++ b/src/Http/Controllers/EmailChangeController.php @@ -17,7 +17,6 @@ use Keyring\KeyringManager; use Keyring\Support\Input; use Keyring\Support\Throttle; -use Keyring\Support\Url; class EmailChangeController { @@ -88,7 +87,9 @@ public function page(Request $request, string $change, #[\SensitiveParameter] st return $this->keyring->render('email-change', [ 'action' => $action, - 'url' => Url::route("keyring.email.{$action}.store", ['change' => $change]), + // A path, like the other pages: the form posts back to wherever + // the page was opened, not to another host the link root names. + 'url' => route("keyring.email.{$action}.store", ['change' => $change], absolute: false), 'token' => $token, ]); } diff --git a/src/KeyringServiceProvider.php b/src/KeyringServiceProvider.php index 068602be..d903832d 100644 --- a/src/KeyringServiceProvider.php +++ b/src/KeyringServiceProvider.php @@ -224,8 +224,9 @@ protected function configureEmailLinks(): void /** * The limit on Keyring's form routes (registration, resets, enrollment), - * and on usernameless login options. Define your own "keyring" or - * "keyring-login-options" limiter to change them. Each answers a refused + * on the pages emailed links open, and on usernameless login options. + * Define your own "keyring", "keyring-pages" or "keyring-login-options" + * limiter to change them. Each answers a refused * request with TooManyAttempts, which is Laravel's 429 and what gets the * refusal into the security log. */ @@ -239,6 +240,13 @@ protected function configureRateLimiting(): void ->by($this->app->make(KeyringManager::class)->guard()->id() ?: $request->ip()) ->response(new TooManyAttempts('keyring'))); + // The pages emailed links open. They only show a button, and one + // person can open several at once (both ends of an email change), + // so they don't draw on the six a minute their buttons are held to. + $limiter->for('keyring-pages', fn (Request $request) => Limit::perMinute(60) + ->by($request->ip()) + ->response(new TooManyAttempts('keyring-pages'))); + // The login page asks for these on every load, for passkey autofill, // and an office shares one address, so six a minute would be too few. // One a second still limits how many challenges a script can make. diff --git a/src/Support/PasswordRules.php b/src/Support/PasswordRules.php index 6fce0d72..d16ca099 100644 --- a/src/Support/PasswordRules.php +++ b/src/Support/PasswordRules.php @@ -68,7 +68,7 @@ final class PasswordRules */ public static function for((Authenticatable&Model)|null $user = null, ?Closure $adjust = null, array $context = []): array { - $min = self::min($user !== null && Keyring::for($user)->hasSecondFactor()); + $min = self::min($user !== null && Keyring::for($user)->hasExtraStep()); $rule = Password::min($min)->max(config('keyring.passwords.max')); diff --git a/src/UserKeyring.php b/src/UserKeyring.php index 6ac7a471..cfdeef2a 100644 --- a/src/UserKeyring.php +++ b/src/UserKeyring.php @@ -103,7 +103,7 @@ public function has(Category $category): bool * may be shorter. Recovery codes aren't one to rely on, and an emailed * code isn't a factor at all (Category::Address). */ - public function hasSecondFactor(): bool + public function hasExtraStep(): bool { return $this->withoutFallbacks()->canMeet(Requirement::aal2()); } diff --git a/stubs/app/Providers/KeyringServiceProvider.php b/stubs/app/Providers/KeyringServiceProvider.php index 95958fad..bb1c08e3 100644 --- a/stubs/app/Providers/KeyringServiceProvider.php +++ b/stubs/app/Providers/KeyringServiceProvider.php @@ -32,7 +32,7 @@ public function boot(): void WebAuthn::passkeys(), WebAuthn::securityKeys(), // A step at sign in, not a second factor: a password and an emailed code is AAL1. - EmailCode::asSecondFactor(), + EmailCode::asExtraStep(), ]); // What they must prove: a second factor once they've set one up, and diff --git a/tests/Feature/AuthenticatorManagementTest.php b/tests/Feature/AuthenticatorManagementTest.php index 259ce551..ebb34726 100644 --- a/tests/Feature/AuthenticatorManagementTest.php +++ b/tests/Feature/AuthenticatorManagementTest.php @@ -280,12 +280,12 @@ it('only allows the shorter password with a real second factor, not recovery codes alone', function () { $codes = Authenticator::factory()->recoveryCodes()->for($this->user, 'authenticatable')->create(); - expect($this->user->keyring->hasSecondFactor())->toBeFalse(); + expect($this->user->keyring->hasExtraStep())->toBeFalse(); expect(Validator::make(['password' => 'short pass', 'password_confirmation' => 'short pass'], ['password' => PasswordRules::for($this->user)])->fails())->toBeTrue(); Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); - expect($this->user->keyring->refresh()->hasSecondFactor())->toBeTrue(); + expect($this->user->keyring->refresh()->hasExtraStep())->toBeTrue(); expect(Validator::make(['password' => 'short pass', 'password_confirmation' => 'short pass'], ['password' => PasswordRules::for($this->user->fresh())])->fails())->toBeFalse(); }); diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index 589bff73..f2f66a9d 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -222,7 +222,7 @@ ->assertSuccessful(); expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) - ->toContain(" // A step at sign in, not a second factor: a password and an emailed code is AAL1.\n EmailCode::asSecondFactor(),\n ]);"); + ->toContain(" // A step at sign in, not a second factor: a password and an emailed code is AAL1.\n EmailCode::asExtraStep(),\n ]);"); expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); }); @@ -331,8 +331,34 @@ ->assertSuccessful(); expect(glob(database_path('migrations/*_create_keyring_authenticators_table.php')))->toHaveCount(1) + ->and(glob(database_path('migrations/*_create_keyring_*')))->toHaveCount(7) ->and(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'))->toBe('artisan('keyring:install', ['--no-interaction' => true])->assertSuccessful(); + + $kept = glob(database_path('migrations/*_create_keyring_sessions_table.php')); + new Filesystem()->delete([ + ...glob(database_path('migrations/*_create_keyring_failure_counts_table.php')), + ...glob(database_path('migrations/*_create_keyring_password_holds_table.php')), + ]); + + // An upgrade comes some time after the install. + $this->travel(1)->days(); + + $this->artisan('keyring:install', ['--no-interaction' => true]) + ->expectsOutputToContain('php artisan migrate') + ->assertSuccessful(); + + $published = array_map(basename(...), glob(database_path('migrations/*_create_keyring_*'))); + + expect($published)->toHaveCount(7) + ->and(glob(database_path('migrations/*_create_keyring_sessions_table.php')))->toBe($kept) + // In Keyring's order, after the ones the app already had. + ->and(array_map(fn (string $name) => Str::after($name, '_create_'), array_slice($published, -2))) + ->toBe(['keyring_failure_counts_table.php', 'keyring_password_holds_table.php']); + }); })->skip(fn () => getenv('TEST_TOKEN') !== false, 'Publishes into the testbench app every parallel worker shares.'); it('lists a security notice in the provider only while its notification is published, whatever the provider stub lists', function (bool $emails) { diff --git a/tests/Feature/ConformanceTest.php b/tests/Feature/ConformanceTest.php index 7217de10..ff8f2b12 100644 --- a/tests/Feature/ConformanceTest.php +++ b/tests/Feature/ConformanceTest.php @@ -46,7 +46,7 @@ protected function setUp(): void parent::setUp(); Notification::fake(); - Keyring::factors([Password::class, WebAuthn::passkeys(), WebAuthn::securityKeys(), Totp::class, EmailCode::asSecondFactor(), RecoveryCodes::class]); + Keyring::factors([Password::class, WebAuthn::passkeys(), WebAuthn::securityKeys(), Totp::class, EmailCode::asExtraStep(), RecoveryCodes::class]); } protected function keyringUser(): User diff --git a/tests/Feature/CustomFactorTest.php b/tests/Feature/CustomFactorTest.php index b6fef42a..fec26e1c 100644 --- a/tests/Feature/CustomFactorTest.php +++ b/tests/Feature/CustomFactorTest.php @@ -56,7 +56,7 @@ public function verify(Attempt $attempt, Authenticator $authenticator, Request $ beforeEach(function () { SmsCode::$sent = []; - Keyring::factors([Password::class, Totp::class, EmailCode::asSecondFactor(), SmsCode::class]); + Keyring::factors([Password::class, Totp::class, EmailCode::asExtraStep(), SmsCode::class]); $this->user = taylor(); }); @@ -174,7 +174,7 @@ public function verify(Attempt $attempt, Authenticator $authenticator, Request $ it('doesn\'t count as the account\'s second factor', function () { $keyring = $this->user->keyring; - expect($keyring->hasSecondFactor())->toBeFalse() + expect($keyring->hasExtraStep())->toBeFalse() ->and($keyring->canMeet(Requirement::aal2()))->toBeFalse() ->and($keyring->canMeet(Requirement::factors(2)))->toBeTrue(); }); diff --git a/tests/Feature/DevicesAndSessionsTest.php b/tests/Feature/DevicesAndSessionsTest.php index 75f30217..dad1fbab 100644 --- a/tests/Feature/DevicesAndSessionsTest.php +++ b/tests/Feature/DevicesAndSessionsTest.php @@ -953,7 +953,7 @@ function expectNoTrustedDevices(): void }); it('stops trusting every device when a one-per-user factor is replaced', function () { - Keyring::factors([Password::class, Totp::class, EmailCode::asSecondFactor(), RecoveryCodes::class]); + Keyring::factors([Password::class, Totp::class, EmailCode::asExtraStep(), RecoveryCodes::class]); Authenticator::factory()->for($this->user, 'authenticatable')->create(['factor' => 'email-code', 'name' => 'Email', 'secret' => null]); app(AuthenticatorChanges::class)->add($this->user->fresh(), Keyring::factor('email-code'), new Authenticator(['factor' => 'email-code', 'name' => 'New email', 'secret' => null])); diff --git a/tests/Feature/EmailChangeHardeningTest.php b/tests/Feature/EmailChangeHardeningTest.php index 3a196fd1..a9b4db57 100644 --- a/tests/Feature/EmailChangeHardeningTest.php +++ b/tests/Feature/EmailChangeHardeningTest.php @@ -419,7 +419,7 @@ function confirmBoth(PendingChange $change, array $tokens): EmailConfirmation }); it('ends a sign in that was waiting for a code sent to the address the undo takes away', function () { - Keyring::factors([PasswordFactor::class, EmailCode::asSecondFactor()]); + Keyring::factors([PasswordFactor::class, EmailCode::asExtraStep()]); $this->travelTo(now()->subMonth(), fn () => Authenticator::factory()->for($this->user, 'authenticatable')->create(['factor' => 'email-code', 'name' => 'Email', 'secret' => null])); $change = requestChange($this->user, 'attacker@example.com', Assurance::AAL2); diff --git a/tests/Feature/EmailCodeTest.php b/tests/Feature/EmailCodeTest.php index 332f0d8e..bd1c916b 100644 --- a/tests/Feature/EmailCodeTest.php +++ b/tests/Feature/EmailCodeTest.php @@ -29,7 +29,7 @@ beforeEach(function () { Notification::fake(); - Keyring::factors([Password::class, Totp::class, EmailCode::asSecondFactor(), RecoveryCodes::class]); + Keyring::factors([Password::class, Totp::class, EmailCode::asExtraStep(), RecoveryCodes::class]); $this->user = taylor(); }); @@ -443,23 +443,23 @@ function sentCode(User $user): string it('only takes email codes as a second factor when the app accepts the risk', function () { Keyring::factors([Password::class, EmailCode::class]); - expect(fn () => Keyring::registered())->toThrow(InvalidArgumentException::class, 'EmailCode::asSecondFactor()'); + expect(fn () => Keyring::registered())->toThrow(InvalidArgumentException::class, 'EmailCode::asExtraStep()'); }); it('refuses a code shorter than six digits, the least that resists guessing', function (int $length) { - EmailCode::asSecondFactor(length: $length); + EmailCode::asExtraStep(length: $length); })->with([1, 5])->throws(LogicException::class, 'Keyring refuses codes shorter than 6 digits'); it('refuses a code that lasts longer than ten minutes', function (string $expireAfter) { - EmailCode::asSecondFactor(expireAfter: $expireAfter); + EmailCode::asExtraStep(expireAfter: $expireAfter); })->with(['601', '11m', '30d'])->throws(LogicException::class, 'Keyring refuses a code that lasts longer than 600 seconds'); it('refuses a code that lasts no time at all', function () { - EmailCode::asSecondFactor(expireAfter: '0s'); + EmailCode::asExtraStep(expireAfter: '0s'); })->throws(LogicException::class, 'or no time at all'); it('takes six digits and ten minutes, the edges of what it allows', function () { - Keyring::factors([Password::class, EmailCode::asSecondFactor(length: 6, expireAfter: '10m')]); + Keyring::factors([Password::class, EmailCode::asExtraStep(length: 6, expireAfter: '10m')]); expect(Keyring::registered()->keys()->all())->toBe(['password', 'email-code']); }); @@ -664,7 +664,7 @@ function signInWithEmailedCode(array $extra = []): TestResponse emailAuthenticator($this->user); $keyring = $this->user->keyring; - expect($keyring->hasSecondFactor())->toBeFalse() + expect($keyring->hasExtraStep())->toBeFalse() ->and($keyring->has(Category::Possession))->toBeFalse() ->and($keyring->has(Category::Address))->toBeTrue() ->and($keyring->canMeet(Requirement::aal2()))->toBeFalse() @@ -759,7 +759,7 @@ function signInWithEmailedCode(array $extra = []): TestResponse $response = $this->postJson(route('keyring.authenticators.confirm', 'totp'), ['code' => totpCode($secret)])->assertOk(); expect($response->json('recoveryCodes'))->toHaveCount(8) - ->and($this->user->keyring->refresh()->hasSecondFactor())->toBeTrue(); + ->and($this->user->keyring->refresh()->hasExtraStep())->toBeTrue(); }); it('doesn\'t stand in for the possession factor a fresh verification asks of an account that has one', function () { @@ -814,7 +814,7 @@ function signInWithEmailedCode(array $extra = []): TestResponse $this->post(route('keyring.login.verify', 'magic-word'), ['code' => 'please'])->assertRedirect('/dashboard'); expect(app(SessionAssurance::class)->level())->toBe(Assurance::AAL1) - ->and($this->user->keyring->hasSecondFactor())->toBeFalse(); + ->and($this->user->keyring->hasExtraStep())->toBeFalse(); }); }); diff --git a/tests/Feature/EmailedLinksTest.php b/tests/Feature/EmailedLinksTest.php index f6fd6a81..c65ec162 100644 --- a/tests/Feature/EmailedLinksTest.php +++ b/tests/Feature/EmailedLinksTest.php @@ -84,7 +84,7 @@ function emailedReportLink(): string expect($props['action'])->toBe($action) ->and($props['token'])->toBe($token) - ->and($props['url'])->toBe(url("/email-changes/{$this->change->id}/{$action}")) + ->and($props['url'])->toBe("/email-changes/{$this->change->id}/{$action}") ->and($props['url'])->not->toContain($token); })->with([ 'to confirm from the new address' => ['confirm', 'confirm'], @@ -321,6 +321,29 @@ function emailedReportLink(): string ->and(app('router')->getMiddlewareGroups()['web'])->toContain(PreventRequestForgery::class); })->with(['keyring.email.confirm.store', 'keyring.email.revert.store', 'keyring.devices.report.store', 'verification.verify.store']); +it('holds the pages the links open to their own, looser limit', function (string $name) { + expect(Route::getRoutes()->getByName($name)->gatherMiddleware()) + ->toContain('throttle:keyring-pages') + ->not->toContain('throttle:keyring'); +})->with(['keyring.email.confirm', 'keyring.email.revert', 'keyring.devices.report', 'verification.verify']); + +it('leaves the six a minute for the buttons, however often the pages are opened', function () { + $links = emailedChangeLinks(); + $change = PendingChange::sole(); + + foreach (range(1, 12) as $view) { + $this->inertia()->get($links[$view % 2 ? 'confirm' : 'current'])->assertOk(); + } + + $this->flushHeaders(); + + foreach (['current', 'confirm'] as $link) { + $this->post(route('keyring.email.confirm.store', $change), ['token' => Str::afterLast($links[$link], '/')])->assertRedirect(route('login')); + } + + expect($this->user->fresh()->email)->toBe('new@example.com'); +}); + it('checks the signature on both the link and the form it posts', function (string $link) { expect(Route::getRoutes()->getByName($link)->gatherMiddleware())->toContain('keyring.signed:relative') ->and(Route::getRoutes()->getByName($link.'.store')->gatherMiddleware())->toContain(ValidatePostedSignature::class); diff --git a/tests/Feature/ExtendingTest.php b/tests/Feature/ExtendingTest.php index 166e2c0c..e46e34dc 100644 --- a/tests/Feature/ExtendingTest.php +++ b/tests/Feature/ExtendingTest.php @@ -155,7 +155,7 @@ public function toResponse($request) })->throws(MissingNotification::class, 'No notification is registered for [email_change_notice]'); it('says so when an email code has no notification to go out in', function () { - Keyring::factors([PasswordFactor::class, EmailCode::asSecondFactor()]); + Keyring::factors([PasswordFactor::class, EmailCode::asExtraStep()]); Keyring::notifications(['verification_code' => null]); $this->withoutExceptionHandling()->actingAs($this->user)->withAssurance(Assurance::AAL1) diff --git a/tests/Feature/RateLimitKeysTest.php b/tests/Feature/RateLimitKeysTest.php index 07455cf5..f5d8cd20 100644 --- a/tests/Feature/RateLimitKeysTest.php +++ b/tests/Feature/RateLimitKeysTest.php @@ -90,7 +90,7 @@ public function put($key, $value, $seconds) it('keeps a sent code, its guesses and an enrollment\'s confirmation under keys a Swoole table can hold', function () { Notification::fake(); - Keyring::factors([Password::class, EmailCode::asSecondFactor()]); + Keyring::factors([Password::class, EmailCode::asExtraStep()]); Authenticator::factory()->emailCode()->for($this->user, 'authenticatable')->create(); $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); diff --git a/tests/Feature/SecurityLogLimitsTest.php b/tests/Feature/SecurityLogLimitsTest.php index 9835e1c8..a2837328 100644 --- a/tests/Feature/SecurityLogLimitsTest.php +++ b/tests/Feature/SecurityLogLimitsTest.php @@ -164,6 +164,14 @@ expect(logEntry('rate_limited')->meta)->toMatchArray(['limiter' => 'keyring-login-options', 'route' => 'keyring.login.options']); }); + it('logs the limit on the pages emailed links open too', function () { + foreach (range(1, 63) as $request) { + $this->get(route('keyring.email.revert', ['change' => 'missing', 'token' => 'wrong'])); + } + + expect(logEntry('rate_limited')->meta)->toMatchArray(['limiter' => 'keyring-pages', 'route' => 'keyring.email.revert']); + }); + it('logs again once the wait is over, and for each address it turns away', function () { $fill = fn (string $ip = '127.0.0.1') => array_map(fn () => $this->withServerVariables(['REMOTE_ADDR' => $ip])->post('/forgot-password'), range(1, 8)); diff --git a/tests/Feature/ServiceProviderTest.php b/tests/Feature/ServiceProviderTest.php index fcfd0dd6..9c2daebb 100644 --- a/tests/Feature/ServiceProviderTest.php +++ b/tests/Feature/ServiceProviderTest.php @@ -165,6 +165,7 @@ function withALateCacheStoreForRateLimits(): void Cache::extend('late', fn () => Cache::repository(new ArrayStore)); expect(RateLimiter::limiter('keyring')(request())->maxAttempts)->toBe(6) + ->and(RateLimiter::limiter('keyring-pages')(request())->maxAttempts)->toBe(60) ->and(RateLimiter::limiter('keyring-login-options')(request())->maxAttempts)->toBe(60); }); @@ -182,7 +183,7 @@ function withALateCacheStoreForRateLimits(): void it('registers a factor that sends codes before the cache store its codes are kept in exists', function () { withALateCacheStoreForRateLimits(); - Keyring::factors([Password::class, EmailCode::asSecondFactor()]); + Keyring::factors([Password::class, EmailCode::asExtraStep()]); expect(Keyring::registered()->keys()->all())->toBe(['password', 'email-code']); }); diff --git a/tests/Feature/TweakableDefaultsTest.php b/tests/Feature/TweakableDefaultsTest.php index c389977b..1966d80d 100644 --- a/tests/Feature/TweakableDefaultsTest.php +++ b/tests/Feature/TweakableDefaultsTest.php @@ -146,7 +146,7 @@ public function toResponse($request) it('sends email codes of the length the app picks, for as long as it picks', function () { Notification::fake(); - Keyring::factors([Password::class, EmailCode::asSecondFactor(length: 6, expireAfter: '5m')]); + Keyring::factors([Password::class, EmailCode::asExtraStep(length: 6, expireAfter: '5m')]); $this->actingAs(taylor())->withAssurance(Assurance::AAL1) ->postJson(route('keyring.authenticators.store', 'email-code')) diff --git a/tests/Unit/KeyedHashTest.php b/tests/Unit/KeyedHashTest.php index ced142f2..282b0d5c 100644 --- a/tests/Unit/KeyedHashTest.php +++ b/tests/Unit/KeyedHashTest.php @@ -73,7 +73,7 @@ function keyedHashPurposes(): array $recovery = Keyring::factor('recovery')->secretFor(['abcd-efgh-ijkl-mnop-qrst-uvwx-yz']); - $factor = EmailCode::asSecondFactor(); + $factor = EmailCode::asExtraStep(); $code = (fn () => $this->hash('12345678'))->call($factor); expect(json_decode($recovery))->toBe([KeyedHash::make(KeyedHash::RECOVERY_CODES, 'abcdefghijklmnopqrstuvwxyz')])