diff --git a/CHANGELOG.md b/CHANGELOG.md index c0a80ba0..20dc1c52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,7 +58,7 @@ The first release. Nothing is tagged yet. ### Tooling -- `keyring:install`, which asks which sign-in methods and features you want and publishes a config, a provider and your actions. Its defaults give an authenticator app that every user must set up, and `--factor=none` the password alone. Also `keyring:import fortify`, and `keyring:prune`, scheduled daily. +- `keyring:install`, which asks which sign-in methods and features you want and publishes a config, a provider and your actions. Its defaults give the password alone, and every other sign-in method is in the provider, commented out, to turn on later. Also `keyring:import fortify`, and `keyring:prune`, scheduled daily. - Security headers on Keyring's responses: `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Cross-Origin-Opener-Policy: same-origin-allow-popups` and a referrer policy. - Test helpers, a fake, factories, a virtual WebAuthn authenticator and a conformance suite that checks your setup still keeps Keyring's guarantees. - `@entity/keyring`, a browser package for WebAuthn, enrollment, sessions and the challenge page, with Vue and React bindings. diff --git a/README.md b/README.md index fd207637..b9828a33 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Fortify keeps 2FA in three columns on `users`. That gives one TOTP per user, and - **Built on OWASP ASVS 5.0.0 and NIST SP 800-63B-4:** [one page](docs/owasp-asvs.md) goes through both, requirement by requirement. Each is met, partly met, waiting on something you turn on, a deliberate deviation or your app's job, and the page says which and why. - **Headless:** like Fortify, Keyring renders your pages with props and answers JSON, with swappable responses and published actions. A browser package handles WebAuthn and the challenge page for Vue and React. -Every feature and sign-in method beyond the password is opt-in. See [Adding Features](docs/quick-start.md#adding-features). +Every feature and sign-in method beyond the password is opt-in. See [Start Small, Add What You Need](#start-small-add-what-you-need). > Work in progress: not tagged or production-tested yet. @@ -66,6 +66,24 @@ npm install @entity/keyring > It isn't on npm yet either. Until it is, build it from the Composer package: see [Frontend](docs/frontend.md#introduction). +## Start Small, Add What You Need + +A new install is password sign-in, registration, password resets, email verification and password changes. You build five pages: `login`, `register`, `forgot-password`, `reset-password`, and `confirm`, which asks for the password again before it's changed. + +What costs you nothing is on from the start: rate limits, password rules, session timeouts, the security log, security emails and the risk signals that need no setup. + +Everything else is already in your app, commented out. Adding it is uncommenting a line: + +| To add | Uncomment | +|---|---| +| An authenticator app, passkeys, security keys or email codes | Its line in `Keyring::factors([...])` in your provider, and `Features::manageAuthenticators()` in the config | +| A second factor for everyone | The `keyring.enrolled` line in your provider | +| "Trust this device", a list of where users are signed in, new-device emails | `Features::devices()` | +| Email changes confirmed from the new address and undoable from the old one | `Features::emailChanges()` | +| More risk signals: a new device, a breached password, a new country, impossible travel | Their lines in `Keyring::risk()->signals([...])` | + +See [Adding Features](docs/quick-start.md#adding-features) and [Adding Sign-In Methods](docs/quick-start.md#adding-sign-in-methods) for the pages each one needs. + ## Documentation - [Quick Start](docs/quick-start.md) diff --git a/docs/installation.md b/docs/installation.md index f406a267..67b48717 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -37,17 +37,17 @@ php artisan migrate The command asks three things: -1. **Which sign-in methods besides the password?** An authenticator app by default, so a new app starts with a second factor. Untick it for the password alone. Recovery codes come with any of them. Email codes are listed as what they are, an extra step at sign in and not a second factor: a password and an emailed code is still AAL1 (see [Email Codes](factors.md#what-turning-email-codes-on-means)), and the provider says so above their line. +1. **Which sign-in methods besides the password?** None by default: a new app starts with the password, and the others stay in your provider, commented out, to add later. Recovery codes come with any of them. Email codes are listed as what they are, an extra step at sign in and not a second factor: a password and an emailed code is still AAL1 (see [Email Codes](factors.md#what-turning-email-codes-on-means)), and the provider says so above their line. 2. **Require a second factor for everyone?** Asked when you picked an authenticator app, passkeys or security keys, and yes by default. Users still sign in with what they have, then every page sends them to `/settings/security` until they've set one up (see [Requiring a Second Factor](policies.md#requiring-a-second-factor)). It isn't asked with the password alone or with only email codes, where nobody could meet it: then nothing requires a second factor. 3. **Which features?** Registration, password resets, email verification, changing the password and the security log by default, plus managing sign-in methods when you picked one. Registration always brings email verification, because by default [new users sign in once they've verified their address](sign-in-flow.md#without-revealing-who-has-an-account). -Without prompts (`--no-interaction`, or in CI) you get the same defaults: an authenticator app that everyone must set up. You can also answer with options: +Without prompts (`--no-interaction`, or in CI) you get the same defaults: the password alone. You can also answer with options: ```bash php artisan keyring:install --factor=totp --factor=passkeys --feature=registration --feature=manage-authenticators --require-second-factor ``` -`--factor` takes `totp`, `passkeys`, `security-keys` or `email-codes`, or `none` for the password alone. `--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. +`--factor` takes `totp`, `passkeys`, `security-keys` or `email-codes`, or `none` to keep the password alone without being asked. `--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. 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 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 email needs nothing: Keyring's emails are its own, so one a later version brings is sent from the start. @@ -61,7 +61,7 @@ If you're moving from Fortify, read [Upgrading From Fortify](upgrading-from-fort |---|---| | `config/keyring.php` | A short config: the guard, username, home, your features, how registration answers, your enrollment page and your support contact. Every other option keeps Keyring's default; copy any from [Configuration](configuration.md) to change it. | | `database/migrations/*_create_keyring_*_table.php` | Seven tables: `keyring_authenticators`, `keyring_devices`, `keyring_sessions`, `keyring_pending_changes`, `keyring_events`, `keyring_failure_counts` and `keyring_password_holds`. They're all created, so turning a feature on later needs no new migration. Tables for features you don't use stay empty. | -| `app/Providers/KeyringServiceProvider.php` | Where you register sign-in methods, the policy, the risk signals and your actions. It lists the sign-in methods you picked, adds the `keyring.enrolled` middleware when a second factor is required, turns on the [risk signals](risk.md) your features can feed and lists the rest commented out, and it's added to `bootstrap/providers.php` for you. | +| `app/Providers/KeyringServiceProvider.php` | Where you register sign-in methods, the policy, the risk signals and your actions. It has every sign-in method, with the ones you didn't pick commented out, and the same for the `keyring.enrolled` middleware that requires a second factor and for the [risk signals](risk.md) your features can't feed yet. Adding one later is uncommenting its line. It's added to `bootstrap/providers.php` for you. | | `app/Actions/Keyring/*.php` | Your code for the features that need it, all published and registered so a feature works as soon as you turn it on: registration (`CreateNewUser`), password resets (`ResetUserPassword`), password changes (`UpdateUserPassword`), email change requests (`ValidateEmailChange`), and the password rules they share (`PasswordValidationRules`). Keyring does the security work around them. | Keyring's emails aren't published: they're [its own](security-log-and-emails.md#security-emails), sent from the start, and you change one by giving `Keyring::notifications()` your class for it. diff --git a/docs/owasp-asvs.md b/docs/owasp-asvs.md index 2a5d0775..8f0a4248 100644 --- a/docs/owasp-asvs.md +++ b/docs/owasp-asvs.md @@ -37,8 +37,8 @@ Both standards verify an application or a service, not a package. Keyring can me `php artisan keyring:install` with every default accepted, or with `--no-interaction`, sets up: -- the password, with [Keyring's password rules](protected-changes.md#password-rules), and an authenticator app as a second factor that every user must set up before going further, with recovery codes, -- six features: `registration`, `reset-passwords`, `email-verification`, `update-passwords`, `manage-authenticators` and `security-log`, +- the password as the only sign-in method, with [Keyring's password rules](protected-changes.md#password-rules), +- five features: `registration`, `reset-passwords`, `email-verification`, `update-passwords` and `security-log`, - [registration that doesn't reveal who has an account](sign-in-flow.md#without-revealing-who-has-an-account), - eleven [security emails](security-log-and-emails.md#security-emails): new device, password changed, sign-in method added, sign-in method removed, second factor failed, recovery code used, new recovery codes, suspicious activity, account locked, email address changed, and email change undone, - three [risk signals](risk.md): a session turning up in another browser, repeated failed second factors, and a sign in that follows several failures, @@ -46,9 +46,9 @@ Both standards verify an application or a service, not a package. Keyring can me That covers Level 1, apart from what your own pages have to do and two things below: passwords are normalised before they're hashed ([6.2.8](#v62-password-security)), and an account you disable should be signed out everywhere by your own code ([7.4.2](#v74-session-termination)). -It also has the main thing Level 2 adds: everyone signs in with a second factor ([6.3.3](#v63-general-authentication-security)). The rest of [Level 2](#level-2) is yours to set. Installing with `--factor=none`, unticking the authenticator app, or answering no to "Require a second factor for everyone?" gives that up, and leaves Level 1. +It doesn't cover Level 2. Keyring starts with the password and leaves the rest for you to turn on, so nothing in a default install asks for a second factor: there isn't one to set up. That is the one thing you have to choose. Pick a second sign-in method when installing and the installer's next question, "Require a second factor for everyone?", defaults to yes ([6.3.3](#v63-general-authentication-security)). The other sign-in methods are in the published provider, commented out, for an app that adds one later. -Two of those emails have nothing to announce in a default install: new device needs `Features::devices()`, and email change undone needs `Features::emailChanges()`. +Three of those emails have nothing to announce in a default install: new device needs `Features::devices()`, second factor failed needs a sign-in method besides the password, and email change undone needs `Features::emailChanges()`. An app that doesn't use the published `KeyringServiceProvider` gets the config defaults and the security emails, which are Keyring's own, and no risk signals until it registers some. @@ -69,15 +69,15 @@ Don't turn on `registration.reveal_taken`, add composition rules to the password Everything in Level 1, and: -1. **Require a second factor** ([6.3.3](#v63-general-authentication-security)). A default install does. If you installed without one, install again with an authenticator app, passkeys or security keys and answer yes to "Require a second factor for everyone?", or set it up yourself ([Requiring a Second Factor](policies.md#requiring-a-second-factor)): +1. **Require a second factor** ([6.3.3](#v63-general-authentication-security)). Install with an authenticator app, passkeys or security keys and answer yes to "Require a second factor for everyone?". In an app that's already installed, uncomment the sign-in methods and the `keyring.enrolled` line in your provider, and turn on `Features::manageAuthenticators()` ([Requiring a Second Factor](policies.md#requiring-a-second-factor)): ```php // app/Providers/KeyringServiceProvider.php Keyring::factors([ - Password::class, - Totp::class, - RecoveryCodes::class, - WebAuthn::passkeys(), + Factors\Password::class, + Factors\Totp::class, + Factors\RecoveryCodes::class, + Factors\WebAuthn::passkeys(), ]); Keyring::require(Requirement::aal2()->ifEnrolled()->noDowngrade()); @@ -197,9 +197,9 @@ Everything in Level 2, and: |---|---|---|---| | 6.3.1 Credential stuffing and brute force controls | 1 | Met by default | Per account, per typed username, per IP address and in a row, all inside the timebox. Every number is an option with no floor: keep the `limits` options near their defaults (`consecutive => null` removes the cap), and keep the limiter's cache store somewhere that holds its keys and that your deploys don't clear. Removing the pipeline step fails the conformance suite. See [Rate Limiting](security.md#rate-limiting). | | 6.3.2 No default accounts | 1 | Met | Keyring creates no users. Don't seed any in production. | -| 6.3.3 Multi-factor authentication is required; a hardware factor at Level 3 | 2 | Met by default | A default install registers an authenticator app and adds `keyring.enrolled`, so every user must set one up. Installing with `--factor=none`, or answering no to requiring a second factor, undoes it, as does taking the middleware out of your provider. Level 2: a second factor registered and `keyring.enrolled`. 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.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, and which are in the published provider to uncomment otherwise. 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 | As installed, Keyring emails `second_factor_failed`, when the password was right and the next factor wasn't; `suspicious_activity`, when a sign in follows several failures, or what the risk signals find adds up to a level that notifies ([Telling the User](risk.md#telling-the-user)); and `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). Left to you: a new client (`new_device`) and a sign in after a long quiet period (`InactiveAccount`) need `Features::devices()`, and a sign in from an unusual place needs a [locator](devices-and-sessions.md#locations) and a location signal. A responder of your own replaces Keyring's, so have it notify for these too. See [Level 3](#level-3). Each kind is capped at five an hour per account. | +| 6.3.5 Users are notified of suspicious authentication attempts | 3 | Partly | As installed, Keyring emails `suspicious_activity`, when a sign in follows several failures, or what the risk signals find adds up to a level that notifies ([Telling the User](risk.md#telling-the-user)); and `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). `second_factor_failed`, when the password was right and the next factor wasn't, is sent once there's a sign-in method besides the password. Left to you: a new client (`new_device`) and a sign in after a long quiet period (`InactiveAccount`) need `Features::devices()`, and a sign in from an unusual place needs a [locator](devices-and-sessions.md#locations) and a location signal. A responder of your own replaces Keyring's, so have it notify for these too. 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::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 | Keyring 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. Setting one of these to `null` in `Keyring::notifications()` stops it being sent, 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). | @@ -370,7 +370,7 @@ Where Keyring doesn't meet a section whatever you configure. Sections that aren' |---|---|---| | 2.1.3 A definite overall timeout at AAL1, 30 days at most | Met by default | `sessions.absolute` is 30 days. A longer one is accepted. | | 2.2.1 AAL2 takes a physical authenticator | Met | `Requirement::aal2()` needs a possession factor. A factor of your own that reports only inherence leaves a session at AAL1. `Requirement::factors(2)` is any two kinds, and isn't AAL2. | -| 2.2.2 A phishing-resistant option is offered at AAL2 | Yours | Passkeys and security keys ship with Keyring. A default install registers an authenticator app, which a phishing page can relay, so offer one of them beside it. | +| 2.2.2 A phishing-resistant option is offered at AAL2 | Yours | Passkeys and security keys ship with Keyring. A default install registers only the password, so offer one. | | 2.2.3 AAL2 lapses after an hour idle or 24 hours | Met by default | `sessions.levels.aal2`. Longer limits are accepted. | | 2.3.2 AAL3 authenticators and verifier cryptography are validated to FIPS 140 | Yours | Everything a library can check about the key is checked. The validation is yours to buy and to run on. | | 2.3.3 AAL3 lapses after 12 hours at most | Met by default | `sessions.levels.aal3`. A longer `absolute` is accepted, and breaks the rule. | @@ -418,8 +418,8 @@ Keyring follows OWASP's Authentication, Session Management, Multifactor Authenti | Session Management | Idle and absolute timeouts on the server | Met by default | `sessions.idle => null` removes Keyring's idle limit. | | Session Management | `no-store` on sensitive responses, `Clear-Site-Data` at sign out | Met by default | On Keyring's routes, through `keyring.middleware`. | | Session Management | Bind the session to client properties and notice changes | Met by default | The `SessionFingerprintChanged` signal in the published provider. | -| Multifactor Authentication | Offer TOTP, and require MFA where you can | Met by default | A default install registers an authenticator app that everyone must set up. Installing with `--factor=none` gives it up: see [Level 2](#level-2). | -| Multifactor Authentication | Tell the user when a second factor fails after the right password | Met by default | The "was this you?" alert and the `second_factor_failed` email. An install with `--factor=none` has no second factor to fail. | +| Multifactor Authentication | Offer TOTP, and require MFA where you can | Needs setup | A default install has the password alone. Pick a second sign-in method: see [Level 2](#level-2). | +| Multifactor Authentication | Tell the user when a second factor fails after the right password | Met by default | The "was this you?" alert, and the `second_factor_failed` email once there's a second sign-in method. A default install has no second factor to fail. | | Multifactor Authentication | Re-authenticate and notify when a factor changes | Met by default | `changes_middleware`, and the `authenticator_added` and `authenticator_removed` emails. Emptying the first or setting the emails to `null` undoes it. | | Multifactor Authentication | No fallback from a phishing-resistant factor to a weaker one | Met by default | `noDowngrade()`, in the policy the installer writes. A policy of your own has to say it. Recovery codes stay on offer. | | Password Storage | Argon2id, or bcrypt for legacy systems | Yours | Your `hashing.driver`. Laravel's default is bcrypt. | diff --git a/docs/quick-start.md b/docs/quick-start.md index a4909f4a..dd28373d 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -25,7 +25,7 @@ php artisan migrate > composer require entity/keyring:dev-main > ``` -`keyring:install` asks which sign-in methods you want besides the password, whether everyone must set up a second factor (when you picked one they can), and which features to turn on. Recovery codes come with any second sign-in method, so losing it isn't the end of an account. Accepting every default, or running with `--no-interaction`, gives you the password, an authenticator app that everyone must set up, registration, password resets, email verification, password changes, managing sign-in methods and the security log. Pass `--factor=none` for the password alone. You can add the rest later: every action is published, so a feature works as soon as it's in the list. +`keyring:install` asks which sign-in methods you want besides the password, whether everyone must set up a second factor (when you picked one they can), and which features to turn on. Recovery codes come with any second sign-in method, so losing it isn't the end of an account. Accepting every default, or running with `--no-interaction`, gives you the password, registration, password resets, email verification, password changes and the security log. You can add the rest later by uncommenting a line: every sign-in method is in your provider, every feature is in the config, and every action is published, so each works as soon as it's on. Add the trait to your user model, and keep Laravel's `hashed` cast on the password. Registration leaves a new user signed out until they've verified their address, so nobody can use the form to find out who has an account. That needs `MustVerifyEmail` (the installer turns on email verification for you): @@ -51,7 +51,7 @@ Keyring renders nine pages. You only need the ones for what you've turned on: |---|---| | `login` | Always. | | `challenge` | When you add a second sign-in method. It asks for the next factor. | -| `confirm` | When you use step-up, which the routes for adding sign-in methods do. It's the challenge page for confirming, and can render the same component. | +| `confirm` | When you use step-up, which changing the password and adding sign-in methods do: a user who signed in more than 15 minutes ago confirms it's them first. It's the challenge page for confirming, and can render the same component. | | `register` | With `Features::registration()`. It posts `name`, `email`, `password` and `password_confirmation` to `/register`. The answer sends the user to your `login` page with a status to show: check your inbox. See [Registration](sign-in-flow.md#registration). | | `forgot-password`, `reset-password` | With `Features::resetPasswords()`. | | `verify-email` | With `Features::emailVerification()`, for a signed-in user who hasn't verified yet. It asks them to click the link they were sent, with a button to send another. With the default registration nobody is signed in before verifying, so you only need it if you set `registration.reveal_taken`. | @@ -192,26 +192,31 @@ A few more things aren't in the features list: ## Adding Sign-In Methods -List them in `app/Providers/KeyringServiceProvider.php`, and turn on `Features::manageAuthenticators()` so users can set them up: +They're all in `app/Providers/KeyringServiceProvider.php`, and the ones you didn't pick when installing are commented out. Uncomment the ones you want, and recovery codes with them: ```php use Keyring\Facades\Keyring; -use Keyring\Factors\Password; -use Keyring\Factors\RecoveryCodes; -use Keyring\Factors\Totp; -use Keyring\Factors\WebAuthn; +use Keyring\Factors; use Keyring\Login\Requirement; Keyring::factors([ - Password::class, - Totp::class, - RecoveryCodes::class, - WebAuthn::passkeys(), + Factors\Password::class, + Factors\Totp::class, + Factors\RecoveryCodes::class, + Factors\WebAuthn::passkeys(), + // Factors\WebAuthn::securityKeys(), + // Factors\EmailCode::asExtraStep(), ]); Keyring::require(Requirement::aal2()->ifEnrolled()->noDowngrade()); ``` +Then: + +1. Turn on `Features::manageAuthenticators()` in `config/keyring.php`, so users can set them up. +2. Build the `challenge` and `confirm` pages, and the part of [your settings page](#your-settings-page) that adds and removes them. +3. To make everyone set one up, uncomment the `keyring.enrolled` line below them and set `enrollment_url` to that page. See [Requiring a Second Factor](policies.md#requiring-a-second-factor). + `Requirement::aal2()->ifEnrolled()` asks for a second factor once a user has set one up, as Fortify does. `noDowngrade()` means a user with a passkey can't be talked into using something weaker. See [Factors](factors.md) and [Policies](policies.md). ## What Keyring Does Without Being Asked diff --git a/docs/security.md b/docs/security.md index e66d7808..2a803dbe 100644 --- a/docs/security.md +++ b/docs/security.md @@ -635,7 +635,8 @@ Keyring's code and config say what each thing does. This is where the choices co Each of these is a choice. The reason is given once, here, and the [requirement-by-requirement page](owasp-asvs.md) says what each means for an app that has to meet the requirement. -- **Not every suspicious sign in is announced as installed.** OWASP ASVS 5.0.0's requirement 6.3.5 lists a sign in from an unusual client or place among them. A new device and a long quiet period are only known with `Features::devices()`, and a place only with a locator you supply, so a default install announces neither. A failed second factor and a sign in after several failures are announced from the start. +- **A default install doesn't require a second factor.** Keyring starts with the password and leaves the rest to turn on, so with the installer's default answers there's nothing to require, and OWASP ASVS 5.0.0's requirement 6.3.3 (Level 2) isn't met. Which second factor your users get is your choice to make: pick one and the installer requires it of everyone unless you say otherwise, and the published provider has each one commented out for an app that adds it later. +- **Not every suspicious sign in is announced as installed.** OWASP ASVS 5.0.0's requirement 6.3.5 lists a sign in from an unusual client or place among them. A new device and a long quiet period are only known with `Features::devices()`, and a place only with a locator you supply, so a default install announces neither. A sign in after several failures is announced from the start, and a failed second factor once there is one. - **Passwords are normalised before they're hashed.** OWASP ASVS 5.0.0 requirement 6.2.8 has a password verified exactly as received. Keyring cuts nothing short and changes no case, but it does put every password in Unicode's NFC form first, as NIST SP 800-63B-4 recommends (Sec. 3.1.1.2). The same "é" is one code point from some keyboards and two from others, and without this a password set on one device could fail on another. - **Bcrypt stops passwords at 72 bytes.** It's Laravel's default hasher, and it ignores everything after the first 72 bytes, so with it Keyring refuses a longer password: 72 plain characters, but as few as 18 emoji, whatever `passwords.max` says. OWASP ASVS 5.0.0 requirement 6.2.9 asks for at least 64 characters, of any kind, to be allowed, and NIST SP 800-63B-4 recommends the same (Sec. 3.1.1.2). Set `HASH_DRIVER=argon2id` for that. Keyring doesn't pre-hash passwords to fit, which would leave hashes Laravel's own hasher can't check. See [Passwords](configuration.md#passwords). - **By default a TOTP code works for longer than OWASP ASVS allows.** ASVS 5.0.0 requirement 6.5.5 gives a time-based one-time password a maximum lifetime of 30 seconds. Keyring accepts a code one time step either side of now unless told otherwise, so one code can work for up to about 90 seconds, and as shipped it does not meet that requirement. The default follows RFC 6238, which recommends accepting one earlier step for the time a code takes to arrive (Section 5.2) and allows a limit on clock drift either way (Section 6): with none, a code typed near the end of its 30 seconds fails, and so does every code from a phone whose clock is half a minute out. A code still works only once. To meet 6.5.5 exactly, register the factor with [a window of zero](factors.md#authenticator-apps-totp). A window wider than one step is refused. diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php index 4da4e791..1e1c8186 100644 --- a/src/Console/InstallCommand.php +++ b/src/Console/InstallCommand.php @@ -24,9 +24,9 @@ #[AsCommand(name: 'keyring:install')] #[Description('Install Keyring: pick sign-in methods and features, then publish the config, migrations, a provider and your actions')] #[Signature('keyring:install - {--factor=* : A sign-in method to add besides the password: totp (the default), passkeys, security-keys or email-codes, or none for the password alone} + {--factor=* : A sign-in method to add besides the password: totp, passkeys, security-keys or email-codes. Without one, or with none, users sign in with the password alone} {--feature=* : A feature to turn on, replacing the defaults (registration, reset-passwords, email-verification, update-passwords and security-log): registration, reset-passwords, email-verification, update-passwords, manage-authenticators, devices, email-changes or security-log} - {--require-second-factor : Make every user set up a second factor (the default with an authenticator app, passkeys or security keys)} + {--require-second-factor : Make every user set up a second factor (the default once you add an authenticator app, passkeys or security keys)} {--optional-second-factor : Leave setting up a second factor to each user} {--force : Overwrite files that already exist}')] class InstallCommand extends Command @@ -38,31 +38,42 @@ class InstallCommand extends Command protected const array FEATURES = ['registration', 'reset-passwords', 'email-verification', 'update-passwords', 'security-log']; /** - * Sign-in methods besides the password, and how the lines each adds to - * the provider's Keyring::factors() call end. Recovery codes come with - * any of them, so losing the only one isn't the end of the account. + * Sign-in methods besides the password, and each one's line in the + * provider's Keyring::factors() call. The ones that aren't picked stay + * there commented out, so adding one later is uncommenting its line. + * None is picked unless asked for: a new app starts with the password. * * An emailed code is named for what it is: a step at sign in. NIST * SP 800-63B-4 takes email as no authenticator, so a password and a * code is still AAL1, and the provider says so above its line. */ protected const array FACTORS = [ - '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::asExtraStep(),', 'a password and an emailed code is AAL1.'], + 'totp' => ['Authenticator app', 'Factors\Totp::class,'], + 'passkeys' => ['Passkeys', 'Factors\WebAuthn::passkeys(),'], + 'security-keys' => ['Security keys, as a second factor', 'Factors\WebAuthn::securityKeys(),'], + 'email-codes' => ['Email codes, as an extra step at sign in (not a second factor)', 'Factors\EmailCode::asExtraStep(),'], ]; /** - * The sign-in method picked unless another is: a second factor anyone - * can set up, with an app they may already have. OWASP ASVS 5.0.0 - * (6.3.3) has every user sign in with more than a password from Level 2. + * The provider's line for recovery codes. They come with any of the + * sign-in methods above, so losing the only one isn't the end of the + * account, and they're no use to an account that has none. */ - protected const array DEFAULT_FACTORS = ['totp']; + protected const string RECOVERY_CODES = 'Factors\RecoveryCodes::class,'; - /** What --factor takes to mean the password alone. */ + /** What --factor takes to mean the password alone, without being asked. */ protected const string NO_FACTORS = 'none'; + /** + * The provider's comment above the line that makes everyone set up a + * second factor, and what replaces it when that line is commented out. + * The line then names the kernel in full, so uncommenting it works in an + * app whose code style has since removed the import. + */ + protected const array ENROLLMENT = [ + " // Everyone needs a second factor: until they've set one up, every page\n // sends them to the \"enrollment_url\" in config/keyring.php.\n \$this->app->make(Kernel::class)" => " // To make everyone set up a second factor, uncomment this and set\n // \"enrollment_url\" in config/keyring.php to your page for adding one.\n // \$this->app->make(\\Illuminate\\Contracts\\Http\\Kernel::class)", + ]; + /** * The sign-in methods that count as a second factor everyone can be made * to set up. An emailed code doesn't: the inbox also resets the password. @@ -162,11 +173,12 @@ public function handle(Filesystem $files): int match (true) { $enrolled && config('keyring.enrollment_url') === null && ! $writesConfig => 'Set enrollment_url in config/keyring.php to your page for adding a sign-in method: users are sent there until they have a second factor', $enrolled => 'Build your page for adding a sign-in method at '.self::ENROLLMENT_URL.', or point enrollment_url in config/keyring.php at yours: users are sent there until they have a second factor', + $writesProvider && $factors === [] => 'Users sign in with a password alone. To add an authenticator app, passkeys or security keys, uncomment its line in your KeyringServiceProvider and Features::manageAuthenticators() in config/keyring.php', $writesProvider => 'Nothing makes users set up a second factor. To require one, see "Requiring a Second Factor" in the "Policies" docs', default => null, }, $writesProvider && in_array('email-codes', $factors, true) ? 'Email codes are an extra step at sign in, not a second factor: a password and an emailed code is still AAL1. See "Email Codes" in the "Factors" docs' : null, - 'Add features later in config/keyring.php, and sign-in methods in your KeyringServiceProvider', + 'Add features later by uncommenting them in config/keyring.php', ])); // What whoever runs the app will want to know before it's live. @@ -222,13 +234,12 @@ protected function factors(): array { $chosen = (array) $this->option('factor'); - if ($chosen === []) { - $chosen = $this->input->isInteractive() ? multiselect( + if ($chosen === [] && $this->input->isInteractive()) { + $chosen = multiselect( label: 'Which sign-in methods besides the password?', options: array_map(fn (array $factor) => $factor[0], self::FACTORS), - default: self::DEFAULT_FACTORS, - hint: 'You can add more later in app/Providers/KeyringServiceProvider.php.', - ) : self::DEFAULT_FACTORS; + hint: 'None is fine. Each one stays in app/Providers/KeyringServiceProvider.php, commented out, to add later.', + ); } // "none" is in no list, so it leaves the password alone. @@ -300,61 +311,53 @@ protected function config(Filesystem $files, array $features, bool $enrolled): s } /** - * The provider with only the chosen sign-in methods, the middleware that - * makes everyone set up a second factor when that was asked for, and the - * risk signals the features can feed. + * The provider with the chosen sign-in methods on and the rest commented + * out, the middleware that makes everyone set up a second factor when + * that was asked for, and the risk signals the features can feed. * * @param list $factors * @param list $features */ protected function provider(Filesystem $files, array $factors, bool $enrolled, array $features = self::FEATURES): string { - $remove = $factors === [] ? ['RecoveryCodes::class,'] : []; + $provider = $files->get(self::STUBS.'/app/Providers/KeyringServiceProvider.php'); - foreach (self::FACTORS as $key => $factor) { - if (! in_array($key, $factors, true)) { - $remove = [...$remove, ...array_slice($factor, 1)]; - } + if (! $enrolled) { + $provider = strtr($provider, self::ENROLLMENT); } - $lines = array_filter( - explode("\n", $files->get(self::STUBS.'/app/Providers/KeyringServiceProvider.php')), - fn (string $line) => match (true) { - str_contains($line, 'Keyring::require(') => $factors !== [], - str_contains($line, "'keyring.enrolled'") => $enrolled, - default => array_all($remove, fn (string $needle) => ! str_ends_with(trim($line), $needle)), - }, - ); + // A signal whose feature is off would find nothing. + $signals = array_keys(array_filter(self::SIGNALS, fn (?string $feature) => $feature !== null && ! in_array($feature, $features, true))); - return $this->withSignals($this->withoutUnusedImports($this->withoutOrphanedComments(implode("\n", $lines))), $features); + return $this->withoutUnusedImports($this->commentedOut($provider, [ + ...array_column(array_diff_key(self::FACTORS, array_flip($factors)), 1), + ...$factors === [] ? [self::RECOVERY_CODES] : [], + ...array_map(fn (string $signal) => "Signals\\{$signal}::class,", $signals), + ])); } /** - * Comment out each risk signal whose feature is off: it would find - * nothing, and it's there to turn on with the feature. + * Comment out the provider's lines that read exactly these, leaving each + * one there to turn on later. * - * @param list $features + * @param list $lines */ - protected function withSignals(string $provider, array $features): string + protected function commentedOut(string $provider, array $lines): string { - $off = array_keys(array_filter(self::SIGNALS, fn (?string $feature) => $feature !== null && ! in_array($feature, $features, true))); - - return $off === [] + return $lines === [] ? $provider - : (string) preg_replace('/^( +)(Signals\\\\(?:'.implode('|', $off).')::class,)$/m', '$1// $2', $provider); + : (string) preg_replace('/^( +)('.implode('|', array_map(fn (string $line) => preg_quote($line, '/'), $lines)).')$/m', '$1// $2', $provider); } /** - * Comments whose code was removed, and the blank line before them. + * Drop the imports only a commented-out line names: the app's code style + * would, and the lines that need one name their class in full. */ - protected function withoutOrphanedComments(string $code): string - { - return (string) preg_replace('/\n(?:\n(?: +\/\/[^\n]*\n)+)+(?=\n| *})/', "\n", $code); - } - 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); + $live = (string) preg_replace('/^ *\/\/.*$/m', '', $code); + + return (string) preg_replace_callback('/^use [\w\\\\]+\\\\(\w+);\n/m', fn (array $import) => preg_match_all('/\b'.$import[1].'\b/', $live) > 1 ? $import[0] : '', $code); } /** diff --git a/stubs/app/Providers/KeyringServiceProvider.php b/stubs/app/Providers/KeyringServiceProvider.php index 5b50324f..657a131f 100644 --- a/stubs/app/Providers/KeyringServiceProvider.php +++ b/stubs/app/Providers/KeyringServiceProvider.php @@ -11,11 +11,7 @@ use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\ServiceProvider; use Keyring\Facades\Keyring; -use Keyring\Factors\EmailCode; -use Keyring\Factors\Password; -use Keyring\Factors\RecoveryCodes; -use Keyring\Factors\Totp; -use Keyring\Factors\WebAuthn; +use Keyring\Factors; use Keyring\Login\Requirement; use Keyring\Risk\Signals; @@ -23,15 +19,18 @@ class KeyringServiceProvider extends ServiceProvider { public function boot(): void { - // How your users can sign in. See "Factors" in the docs for more. + // How your users can sign in. A line that's commented out is one to + // add later: uncomment it, and turn on Features::manageAuthenticators() + // in config/keyring.php so users can set it up. See "Factors". Keyring::factors([ - Password::class, - Totp::class, - RecoveryCodes::class, - WebAuthn::passkeys(), - WebAuthn::securityKeys(), + Factors\Password::class, + Factors\Totp::class, + // These go with any of the others, so losing one isn't the end of an account. + Factors\RecoveryCodes::class, + Factors\WebAuthn::passkeys(), + Factors\WebAuthn::securityKeys(), // A step at sign in, not a second factor: a password and an emailed code is AAL1. - EmailCode::asExtraStep(), + Factors\EmailCode::asExtraStep(), ]); // What they must prove: a second factor once they've set one up, and diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index aea4d0b6..2397a9ab 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -12,6 +12,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Encryption\Encrypter; use Illuminate\Filesystem\Filesystem; +use Illuminate\Routing\Router; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event as Events; @@ -71,30 +72,11 @@ $files->delete($files->glob(database_path('migrations/*_create_keyring_*'))); }); - // OWASP ASVS 5.0.0, 6.3.3: with nothing asked, everyone signs in with - // more than a password. - it('installs an authenticator app everyone must set up, with recovery codes, without asking', function () { - $this->artisan('keyring:install', ['--no-interaction' => true]) - ->expectsOutputToContain('Turned on managing sign-in methods') - ->expectsOutputToContain('Build your page for adding a sign-in method at /settings/security') - ->assertSuccessful(); - - $config = require config_path('keyring.php'); - $provider = file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); - - expect($config['features'])->toBe([Features::registration(), Features::resetPasswords(), Features::emailVerification(), Features::updatePasswords(), Features::manageAuthenticators(), Features::securityLog()]) - ->and($config['enrollment_url'])->toBe('/settings/security') - ->and($provider)->toContain('Password::class,')->toContain('Totp::class,')->toContain('RecoveryCodes::class,') - ->toContain('Keyring::require(Requirement::aal2()->ifEnrolled()->noDowngrade());') - ->toContain("appendMiddlewareToGroup('web', 'keyring.enrolled');") - ->not->toContain('WebAuthn')->not->toContain('EmailCode'); - - expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); - }); - - it('installs the password alone when asked to, with registration, resets, verification, password changes and the security log', function () { - $this->artisan('keyring:install', ['--factor' => ['none'], '--no-interaction' => true]) - ->expectsOutputToContain('Nothing makes users set up a second factor') + // A new app starts small: everything past the password is there to turn on. + it('installs the password alone without being asked for more, with registration, resets, verification, password changes and the security log', function (array $options) { + $this->artisan('keyring:install', [...$options, '--no-interaction' => true]) + ->expectsOutputToContain('Users sign in with a password alone. To add an authenticator app, passkeys or security keys, uncomment its line') + ->doesntExpectOutputToContain('Turned on managing sign-in methods') ->assertSuccessful(); $config = require config_path('keyring.php'); @@ -119,10 +101,17 @@ ->toContain(" Signals\SuccessAfterFailures::class,\n") ->toContain(" // Signals\NewDevice::class,\n") ->toContain(" // Signals\BreachedPassword::class,\n") - ->toContain('Password::class,') - ->not->toContain('Totp')->not->toContain('WebAuthn')->not->toContain('RecoveryCodes::class')->not->toContain('Keyring::require(') - // Nothing a user could set up, so nothing makes them. - ->not->toContain('keyring.enrolled')->not->toContain('Kernel') + // The other sign-in methods are there to uncomment, and the + // policy that asks for one a user has set up is already on. + ->toContain(" Keyring::factors([\n Factors\Password::class,\n // Factors\Totp::class,\n") + ->toContain(" // Factors\RecoveryCodes::class,\n // Factors\WebAuthn::passkeys(),\n // Factors\WebAuthn::securityKeys(),\n") + ->toContain(" // Factors\EmailCode::asExtraStep(),\n ]);") + ->toContain("\n Keyring::require(Requirement::aal2()->ifEnrolled()->noDowngrade());\n") + // Nothing a user could set up, so nothing makes them. The line is + // there to uncomment, naming its class in full: no import to lose. + ->toContain(" // \$this->app->make(\Illuminate\Contracts\Http\Kernel::class)->appendMiddlewareToGroup('web', 'keyring.enrolled');\n") + ->not->toContain('use Illuminate\Contracts\Http\Kernel;') + ->not->toContain('use Keyring\Factors\\') // Every action, so turning a feature on later works. ->toContain('Keyring::updateUserPasswordsUsing(UpdateUserPassword::class);') ->and(array_map(basename(...), glob($this->sandbox.'/app/Actions/Keyring/*.php')))->toEqualCanonicalizing([ @@ -131,7 +120,7 @@ ->and(file_get_contents($this->sandbox.'/bootstrap/providers.php'))->toContain('App\Providers\KeyringServiceProvider::class'); expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); - }); + })->with(['nothing asked for' => [[]], '--factor=none' => [['--factor' => ['none']]]]); it('adds the sign-in methods and features picked, and what they need', function () { $this->artisan('keyring:install', [ @@ -145,8 +134,10 @@ expect($config['features'])->toBe([Features::updatePasswords(), Features::manageAuthenticators(), Features::devices()]) ->and($provider)->toContain(" Signals\NewDevice::class,\n") - ->toContain('Totp::class,')->toContain('RecoveryCodes::class,')->toContain('WebAuthn::passkeys(),')->toContain('Keyring::require(') - ->not->toContain('securityKeys')->not->toContain('EmailCode'); + ->toContain("\n Factors\Totp::class,\n")->toContain("\n Factors\RecoveryCodes::class,\n")->toContain("\n Factors\WebAuthn::passkeys(),\n") + ->toContain("\n Keyring::require(") + // The two that weren't picked are there to turn on later. + ->toContain("\n // Factors\WebAuthn::securityKeys(),\n")->toContain("\n // Factors\EmailCode::asExtraStep(),\n"); expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); expectValidPhp(config_path('keyring.php')); @@ -155,7 +146,7 @@ it('adds recovery codes to any second sign-in method, so losing it isn\'t the end of the account', function (string $factor) { $this->artisan('keyring:install', ['--factor' => [$factor], '--no-interaction' => true])->assertSuccessful(); - expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'))->toContain('RecoveryCodes::class,'); + expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'))->toContain("\n Factors\RecoveryCodes::class,\n"); })->with(['passkeys', 'security-keys', 'email-codes']); it('makes everyone set up a second factor once there is one to set up, without asking', function (string $factor) { @@ -180,8 +171,9 @@ ->assertSuccessful(); expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) - ->not->toContain('keyring.enrolled')->not->toContain('Kernel') - ->toContain('Keyring::require(') + ->toContain(" // \$this->app->make(\Illuminate\Contracts\Http\Kernel::class)->appendMiddlewareToGroup('web', 'keyring.enrolled');\n") + ->not->toContain('use Illuminate\Contracts\Http\Kernel;') + ->toContain("\n Keyring::require(") ->and((require config_path('keyring.php'))['enrollment_url'])->toBeNull(); expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); @@ -197,7 +189,7 @@ expect(file_exists(config_path('keyring.php')))->toBeFalse(); })->with([ - 'the password alone' => [['none'], 'Requiring a second factor needs one users can set up. Add --factor=totp, --factor=passkeys, --factor=security-keys.'], + 'the password alone' => [[], 'Requiring a second factor needs one users can set up. Add --factor=totp, --factor=passkeys, --factor=security-keys.'], 'email codes' => [['email-codes'], 'Requiring a second factor needs one users can set up, and an emailed code isn\'t one. Add --factor=totp'], ]); @@ -207,18 +199,18 @@ ->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::asExtraStep(),\n ]);"); + ->toContain(" // A step at sign in, not a second factor: a password and an emailed code is AAL1.\n Factors\EmailCode::asExtraStep(),\n ]);"); expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); }); - it('says nothing of email codes to an app that did not pick them', function (array $factors) { + it('leaves email codes commented out, and unmentioned, for an app that did not pick them', function (array $factors) { $this->artisan('keyring:install', ['--factor' => $factors, '--no-interaction' => true]) ->doesntExpectOutputToContain('Email codes') ->assertSuccessful(); expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) - ->not->toContain('emailed code')->not->toContain('EmailCode'); + ->toContain(" // A step at sign in, not a second factor: a password and an emailed code is AAL1.\n // Factors\EmailCode::asExtraStep(),\n ]);"); expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); })->with(['the password alone' => [[]], 'an authenticator app and security keys' => [['totp', 'security-keys']]]); @@ -283,7 +275,7 @@ ->assertSuccessful(); expect((require config_path('keyring.php'))['features'])->toBe([Features::resetPasswords(), Features::manageAuthenticators()]) - ->and(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'))->toContain('WebAuthn::passkeys(),')->toContain('keyring.enrolled')->not->toContain('Totp'); + ->and(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'))->toContain("\n Factors\WebAuthn::passkeys(),\n")->toContain("\n \$this->app->make(Kernel::class)->appendMiddlewareToGroup('web', 'keyring.enrolled');")->toContain("\n // Factors\Totp::class,\n"); }); it('does not ask about a second factor when the password is the only sign-in method', function () { @@ -293,7 +285,7 @@ ->assertSuccessful(); expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) - ->not->toContain('keyring.enrolled'); + ->not->toContain("\n \$this->app->make("); }); it('can run again without duplicating migrations or overwriting customised files', function () { @@ -1146,6 +1138,30 @@ function passkeysTable(): void $this->get('/anywhere')->assertOk()->assertSee('through'); }); +// Adding a sign-in method later is uncommenting its line, in an app whose +// code style may have removed any import only a comment named. +it('publishes a provider whose commented-out lines work once uncommented', function () { + $provider = (fn () => $this->provider(new Filesystem, [], false))->call(new InstallCommand); + + expect($provider)->not->toContain('use Illuminate\Contracts\Http\Kernel;')->not->toContain('use Keyring\Factors\\'); + + $class = 'UncommentedKeyringServiceProvider'; + $path = sys_get_temp_dir().'/keyring-provider-'.uniqid().'.php'; + file_put_contents($path, str_replace( + ['class KeyringServiceProvider', '// Factors\\', '// $this->app->make('], + ["class {$class}", 'Factors\\', '$this->app->make('], + $provider, + )); + + require $path; + File::delete($path); + + new ("App\\Providers\\{$class}")($this->app)->boot(); + + expect(Keyring::registered()->keys()->all())->toBe(['password', 'totp', 'recovery', 'passkey', 'security-key', 'email-code']) + ->and(app(Router::class)->getMiddlewareGroups()['web'])->toContain('keyring.enrolled'); +}); + it('publishes a provider that boots, with everything picked', function () { // The stub as a whole; keyring:install removes what isn't picked. new KeyringServiceProvider($this->app)->boot(); diff --git a/tests/Feature/StandardsDocsTest.php b/tests/Feature/StandardsDocsTest.php index 71ddcbea..a7e0f23a 100644 --- a/tests/Feature/StandardsDocsTest.php +++ b/tests/Feature/StandardsDocsTest.php @@ -18,10 +18,10 @@ $this->page = file_get_contents(__DIR__.'/../../docs/owasp-asvs.md'); $this->defaults = require __DIR__.'/../../config/keyring.php'; - // What keyring:install sets up with its default answers: an authenticator - // app everyone must set up, which brings managing sign-in methods. - $this->features = array_values(array_intersect(Features::all(), [...$this->defaults['features'], Features::manageAuthenticators()])); - $this->provider = (fn () => $this->provider(new Filesystem, self::DEFAULT_FACTORS, true, test()->features))->call(new InstallCommand); + // What keyring:install sets up with its default answers: the password + // alone, and the features the config ships with. + $this->features = $this->defaults['features']; + $this->provider = (fn () => $this->provider(new Filesystem, [], false, test()->features))->call(new InstallCommand); }); it('lists the features a default install turns on', function () { @@ -29,15 +29,19 @@ $listed = Str::matchAll('/`([a-z-]+)`/', $line[2])->all(); - expect($listed)->toBe($this->features)->toHaveCount(6) - ->and($line[1])->toBe('six'); + expect($listed)->toBe($this->features)->toHaveCount(5) + ->and($line[1])->toBe('five'); }); -it('says a default install has an authenticator app everyone must set up, which is what the installer writes', function () { - expect($this->page)->toContain('an authenticator app as a second factor that every user must set up before going further, with recovery codes') - ->and($this->provider)->toContain('Totp::class,')->toContain('RecoveryCodes::class,') - ->toContain("appendMiddlewareToGroup('web', 'keyring.enrolled');") - ->not->toContain('WebAuthn'); +it('says a default install has the password alone, with the rest there to turn on, which is what the installer writes', function () { + preg_match_all('/^ +(\/\/ )?Factors\\\\(\w+)::/m', $this->provider, $lines, PREG_SET_ORDER); + + expect($this->page)->toContain('- the password as the only sign-in method,') + ->toContain("It doesn't cover Level 2.") + ->toContain('| 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.') + ->and(array_column(array_filter($lines, fn (array $line) => $line[1] === ''), 2))->toBe(['Password']) + ->and(array_column(array_filter($lines, fn (array $line) => $line[1] !== ''), 2))->toBe(['Totp', 'RecoveryCodes', 'WebAuthn', 'WebAuthn', 'EmailCode']) + ->and($this->provider)->toContain(" // \$this->app->make(\Illuminate\Contracts\Http\Kernel::class)->appendMiddlewareToGroup('web', 'keyring.enrolled');"); }); it('counts the security emails Keyring sends and the risk signals a default install registers', function () {