diff --git a/CHANGELOG.md b/CHANGELOG.md index 21ea6579..dff4aa4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,13 +52,13 @@ The first release. Nothing is tagged yet. - A security log with a severity and a request ID on every entry, of sign ins, failures, lockouts, changes and what was refused, capped so a refused request can't fill it. Without the table it goes to your app's log. - "Was this you?" alerts at the next sign in. -- Security emails, each a notification published into your app. The installer registers the ones about changes to how an account signs in and about suspicious attempts, as far as your features go. +- Security emails about changes to how an account signs in and about suspicious attempts, sent from the start as far as your features go. Each is a notification you can swap for your own or turn off, and `SecurityNotice::toMailUsing()` writes them all from your own template. - `support_contact`, so every notice can say who to contact. - `Keyring\Events\*` for everything above, with Laravel's own auth events raised beside them. ### Tooling -- `keyring:install`, which asks which sign-in methods and features you want and publishes a provider, your actions and your notifications; `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; `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` 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 6a026d01..30685157 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Fortify keeps 2FA in three columns on `users`. That gives one TOTP per user, and - **Step-up:** `keyring:aal2` and `keyring.fresh:15m` middleware. A passkey or code counts, not just the password, and users with a second factor must use it. - **Protected account changes:** once Keyring handles them, `email` and `password` can only change through its flows. Email changes are confirmed from both addresses and can be reverted. - **Risk signals:** new device, new country, impossible travel, a session cookie showing up in another browser, repeated failures, a password found in a breach. Each level maps to an action, and a new app starts with the signals its features can feed. -- **A security log and security emails.** Every email is a notification class in your app, yours to reword, restyle or send another way. +- **A security log and security emails.** The emails are sent from the start, and each can be swapped for your own notification, restyled or turned off. - **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, or stated as a deliberate deviation or as your app's job, with the reason. - **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. diff --git a/config/keyring.php b/config/keyring.php index 5b2719bc..f016992a 100644 --- a/config/keyring.php +++ b/config/keyring.php @@ -187,8 +187,8 @@ |-------------------------------------------------------------------------- | | Where users can reach you about their account: a page's URL or an email - | address. Every notification is handed it as $contact, and the published - | ones end with "if this wasn't you and you need help, contact us" when + | address. Every notification is handed it as $contact, and Keyring's + | own end with "if this wasn't you and you need help, contact us" when | it's set. Null leaves the line out. | */ diff --git a/docs/configuration.md b/docs/configuration.md index 87a9ff26..fd3abb17 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -168,7 +168,7 @@ Where a user who has to choose a new password is sent from every other page unti 'support_contact' => null, ``` -Where users can reach you about their account: a page's URL (`'https://example.com/support'`) or an email address (`'support@example.com'`). Every notification is handed it as `$contact`, and the published security notices, the emailed code and the email change notice end with "If this wasn't you and you need help, contact us" and a link to it. `null` leaves the line out. See [Security Emails](security-log-and-emails.md#a-support-contact). +Where users can reach you about their account: a page's URL (`'https://example.com/support'`) or an email address (`'support@example.com'`). Every notification is handed it as `$contact`, and Keyring's security notices, the emailed code and the email change notice end with "If this wasn't you and you need help, contact us" and a link to it. `null` leaves the line out. See [Security Emails](security-log-and-emails.md#a-support-contact). ```php 'enrollments' => [ @@ -410,7 +410,7 @@ php artisan vendor:publish --tag=keyring-lang | `Keyring::respondWith($contract, $implementation)` | Swaps a response. See [Responses](sign-in-flow.md#responses). | | `Keyring::page($name, $component)` | Changes the component a page renders. See [Pages](sign-in-flow.md#pages). | | `Keyring::risk()->signals([...])->respond(...)` | Configures risk signals and actions. `Keyring::risk()->push(...)` adds to the signals already on. See [Risk](risk.md). | -| `Keyring::notifications([...])` | Registers your notification class for each email Keyring sends. A security notice with none isn't sent, and unknown types throw an `InvalidArgumentException`. See [Security Emails](security-log-and-emails.md#security-emails). | +| `Keyring::notifications([...])` | Swaps the notification Keyring sends for a type with your own class, or `null` to send none. Types left out keep Keyring's own, and unknown types throw an `InvalidArgumentException`. See [Security Emails](security-log-and-emails.md#security-emails). | | `Keyring::createUsersUsing($action)` | Sets the registration action. See [Registration](sign-in-flow.md#registration). | | `Keyring::resetUserPasswordsUsing($action)` | Sets the password reset action. See [Resetting the Password](protected-changes.md#resetting-the-password). | | `Keyring::updateUserPasswordsUsing($action)` | Sets the password change action. See [Changing the Password](protected-changes.md#changing-the-password). | @@ -452,7 +452,7 @@ It also answers questions about your setup, for your own controllers, factors an | `Keyring::requirementFor($user, $attempt)` | What this user must prove to finish the attempt. See [Checking Requirements in Code](policies.md#checking-requirements-in-code). | | `Keyring::statusMessage($status)` | The translated message for a status slug, or `null`. See [Flash Messages and Alerts](frontend.md#flash-messages-and-alerts). | | `Keyring::render($name, $props)` | Renders one of Keyring's [pages](sign-in-flow.md#pages), as Inertia or Blade, for a route of your own. | -| `Keyring::hasNotification($type)` | Whether a notification is registered for a [type](security-log-and-emails.md#email-types). | +| `Keyring::hasNotification($type)` | Whether a notification is sent for a [type](security-log-and-emails.md#email-types). | | `Keyring::protectedAttributes($user = null)` | The attributes that only change through Keyring's flows. Pass a user whose model keeps its password under another name to get that name. See [Protected Attributes](protected-changes.md#protected-attributes). | | `Keyring::response($contract, ...$with)` | Builds one of Keyring's [responses](sign-in-flow.md#responses), yours when you swapped it, for a route of your own. | | `Keyring::describeDevice($userAgent)` | A user agent as a name people recognise, or `null`. | @@ -460,7 +460,7 @@ It also answers questions about your setup, for your own controllers, factors an | `Keyring::email()` | The attribute holding the user's address, `email` by default. | | `Keyring::policy($user, $attempt)` | What the policy asks of this user, before considering what they've enrolled. | | `Keyring::steps()` | The pipeline's steps, in order. `Keyring::dangerouslyChangedSteps()` lists the mandatory ones an app took out. | -| `Keyring::notification($type, $arguments)` | The app's notification for a type, or `null`. `Keyring::requiredNotification()` throws when there isn't one. | +| `Keyring::notification($type, $arguments)` | The notification for a type, Keyring's own or yours, or `null` when it's turned off. `Keyring::requiredNotification()` throws when it is. | | `Keyring::belongsToGuard($user)` | Whether Keyring's guard would load this user back, so they can be signed in. | | `Keyring::recordedIp($request)` | The request's IP address as Keyring stores it. | | `Keyring::allowsSignIn($user)` | Whether the app lets this user be signed in. See [Who May Sign In](sign-in-flow.md#who-may-sign-in). | diff --git a/docs/extending.md b/docs/extending.md index 2a864004..3b2fc979 100644 --- a/docs/extending.md +++ b/docs/extending.md @@ -25,7 +25,7 @@ This page lists them all, with where each is explained. [Recipes](recipes.md) ha | How a user is found, and how usernames are normalised | `Keyring::findUsersUsing()`, `Keyring::normalizeUsernamesUsing()` | [Finding the User](sign-in-flow.md#finding-the-user) | | The attribute users sign in with, and the one holding their address | `username` and `email` | [Guard and Users](configuration.md#guard-and-users) | | Creating users, resetting and changing passwords, validating a new address | The published actions in `app/Actions/Keyring` | [Protected Changes](protected-changes.md) | -| Every email: wording, template, channel, or whether it's sent | The published notifications in `app/Notifications/Keyring` and `Keyring::notifications()` | [Security Emails](security-log-and-emails.md#security-emails) | +| Every email: wording, template, channel, or whether it's sent | `Keyring::notifications()`, with your own class for a type or `null`, and `SecurityNotice::toMailUsing()` | [Security Emails](security-log-and-emails.md#security-emails) | | What a page renders | `Keyring::page()` | [Pages](sign-in-flow.md#pages) | | What Keyring answers with | `Keyring::respondWith()` and the contracts in `Keyring\Contracts\Responses` | [Responses](sign-in-flow.md#responses) | | Validation and status messages | The `keyring-lang` translation files | [Messages and Translations](configuration.md#messages-and-translations) | diff --git a/docs/installation.md b/docs/installation.md index bdcc0b45..c4b033eb 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -35,12 +35,11 @@ php artisan migrate > composer require entity/keyring:dev-main > ``` -The command asks four things: +The command asks three things: 1. **Which sign-in methods besides the password?** None by default. 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). -4. **Email users when their password, sign-in methods or email address change?** Yes by default: password changed, sign-in method added or removed, recovery code used, new recovery codes made, email address changed, account locked and a suspicious sign in or session, and with the features that give them something to announce, a sign in on a new device (devices), a second factor that failed after the right password (any sign-in method besides the password) and an email change undone (email changes). See [Security Emails](security-log-and-emails.md#security-emails). Without prompts (`--no-interaction`, or in CI) you get the same defaults. You can also answer with options: @@ -48,9 +47,9 @@ Without prompts (`--no-interaction`, or in CI) you get the same defaults. You ca 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`. `--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. +`--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. -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. +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. If you're moving from Fortify, read [Upgrading From Fortify](upgrading-from-fortify.md) before migrating. @@ -62,9 +61,10 @@ 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, your actions and your emails. 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 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/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. | -| `app/Notifications/Keyring/*.php` | Every email Keyring sends, as ordinary Laravel notifications that are yours to reword, restyle or send another way. The ones a flow needs are registered, and so are the security notices unless you said no to them; one with nothing to announce until a feature is on is listed commented out. See [Security Emails](security-log-and-emails.md#security-emails). | + +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. You can publish files on their own with the `keyring-config`, `keyring-migrations` and `keyring-lang` tags. `keyring-config` publishes the full config file, with every option and its default: diff --git a/docs/owasp-asvs.md b/docs/owasp-asvs.md index 700d2eec..4254fc90 100644 --- a/docs/owasp-asvs.md +++ b/docs/owasp-asvs.md @@ -40,7 +40,7 @@ Both standards verify an application or a service, not a package. Keyring can me - 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), -- eight [security emails](security-log-and-emails.md#security-emails): password changed, sign-in method added, sign-in method removed, recovery code used, new recovery codes, email address changed, account locked, and suspicious activity, +- 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, - rate limits, the timebox, the session registry, and on every session a two hour inactivity limit (14 days for a browser that ticked "remember me"), a 30 day limit overall and a limit of 100 sessions per account. @@ -48,7 +48,9 @@ That covers Level 1, apart from what your own pages have to do and two things be It doesn't cover Level 2. Nothing in it asks for a second factor, because 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)). -An app that doesn't use the published `KeyringServiceProvider` gets the config defaults and nothing else: no security emails and no risk signals until it registers some. +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. ## Level 1 @@ -197,9 +199,9 @@ Everything in Level 2, and: | 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 | 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.5 Users are notified of suspicious authentication attempts | 3 | Partly | Keyring 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. `second_factor_failed` is sent once there's 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::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.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). | #### V6.4 Authentication Factor Lifecycle and Recovery @@ -388,7 +390,7 @@ Where Keyring doesn't meet a section whatever you configure. Sections that aren' | 4.2.1.2 At least two verified recovery addresses | Yours | Keyring has one, the `email` attribute. A second address, verified before it's used, is your app's to build: see [Known Limitations](security.md#known-limitations). | | 4.2.3 Account recovery is announced | Met by default | `password_changed` after a reset, and `recovery_code_used`. | | 4.6 At least two notification addresses, and every notice sent to all of them | Yours | Keyring mails your user model as Laravel does, at one address. Return more from `routeNotificationForMail()`: see [A Support Contact](security-log-and-emails.md#a-support-contact). | -| 4.6 A notice says who to contact | Needs setup | Set [`support_contact`](security-log-and-emails.md#a-support-contact), and the published notices end with it. It's `null` until you do. | +| 4.6 A notice says who to contact | Needs setup | Set [`support_contact`](security-log-and-emails.md#a-support-contact), and Keyring's notices end with it. It's `null` until you do. | | 5.1 A cookie isn't used instead of authentication | Deviates | "Remember me" brings a browser back signed in, with nothing proved, after its session idled out. Keyring binds it to the session it was ticked for, lets it work once, and gives the session it resumes no level, so anything behind `keyring:aal1`, `keyring:aal2` or `keyring.fresh` asks again. Routes behind `auth` alone are reachable on the cookie. Leave the checkbox off your login form, or set `sessions.end_on_lapse`, where you follow this section. | | 5.1 Requests that change something carry a CSRF token | Met by default | Laravel's, on the `web` group. | | 5.1.1 Session cookies are `Secure` and narrowly scoped | Met by default | Keyring's own, which hold only random identifiers. Laravel's session cookie is `Secure` once you set `SESSION_SECURE_COOKIE`. | diff --git a/docs/quick-start.md b/docs/quick-start.md index 21d195ba..50f800e4 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -183,10 +183,10 @@ use Keyring\Features; | `emailChanges()` | Email changes confirmed by the new address and undoable from the old one. Changing the email elsewhere then throws. | [Protected Changes](protected-changes.md#changing-the-email-address) | | `securityLog()` | A log of sign ins, failures, refusals and changes in `keyring_events`, and "was this you?" alerts. On unless you take it out, and then the events go to your app's log instead. | [Security Log & Emails](security-log-and-emails.md) | -A few more things aren't in the features list. They're in your `KeyringServiceProvider`, where `keyring:install` wrote a starting set of each: +A few more things aren't in the features list: -- [Security emails](security-log-and-emails.md#security-emails): the `Keyring::notifications([...])` list, and the classes in `app/Notifications/Keyring`. The ones a feature needs are commented out until it's on. -- [Risk signals](risk.md): the `Keyring::risk()->signals([...])` list. Turning on devices is when to uncomment `NewDevice` and `InactiveAccount`. +- [Security emails](security-log-and-emails.md#security-emails): Keyring sends its own from the start, each once its feature is on. `Keyring::notifications([...])` in your `KeyringServiceProvider` swaps one for your own class or turns it off. +- [Risk signals](risk.md): the `Keyring::risk()->signals([...])` list in your `KeyringServiceProvider`, where `keyring:install` wrote a starting set. Turning on devices is when to uncomment `NewDevice` and `InactiveAccount`. - A [support contact](security-log-and-emails.md#a-support-contact) for those emails to name: `support_contact` in `config/keyring.php`. - [Requiring a second factor](policies.md#requiring-a-second-factor): the `keyring.enrolled` middleware, with `enrollment_url` set to your page for adding one. `keyring:install` sets both up when you answer yes to requiring one. Step-up sends users there too when they don't have what a route needs. diff --git a/docs/recipes.md b/docs/recipes.md index 16043151..7b91f27a 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -160,29 +160,33 @@ A template is a Vue file. Whatever changes per email is a Blade variable inside ``` -`npx maizzle build` writes `notice.blade.php` and `text/notice.blade.php`. The published `SecurityNotice` then returns them, and every notice uses the one template: +`npx maizzle build` writes `notice.blade.php` and `text/notice.blade.php`. Tell `SecurityNotice` to return them, and every notice uses the one template: ```php -// app/Notifications/Keyring/SecurityNotice.php -public function toMail(object $notifiable): MailMessage -{ - $details = array_filter([__('When') => $this->when, __('Device') => $this->device, __('IP address') => $this->ip]); +// app/Providers/KeyringServiceProvider.php +use Illuminate\Notifications\Messages\MailMessage; +use Keyring\Notifications\SecurityNotice; + +SecurityNotice::toMailUsing(function (SecurityNotice $notice, object $notifiable) { + $details = array_filter([__('When') => $notice->when, __('Device') => $notice->device, __('IP address') => $notice->ip]); - return (new MailMessage)->subject($this->subject())->view( + return (new MailMessage)->subject($notice->subject())->view( ['html' => 'emails.keyring.notice', 'text' => 'emails.keyring.text.notice'], [ - 'subject' => $this->subject(), - 'intro' => $this->intro(), + 'subject' => $notice->subject(), + 'intro' => $notice->intro(), 'details' => array_map(fn (string $label, string $value) => ['label' => $label, 'value' => $value], array_keys($details), $details), - 'actionText' => $this->action(), - 'actionUrl' => $this->action() === null ? null : $this->url, - 'contact' => $this->contact, + 'actionText' => $notice->action(), + 'actionUrl' => $notice->action() === null ? null : $notice->url, + 'contact' => $notice->contact, ], ); -} +}); ``` -`$this->contact` is your [support contact](security-log-and-emails.md#a-support-contact), `null` until you set one. A template of your own has to show it itself: the published one does so in the `toMail()` this replaces. +`$notice->contact` is your [support contact](security-log-and-emails.md#a-support-contact), `null` until you set one. A template of your own has to show it itself: Keyring's does so in the `toMail()` this replaces. + +The [emails a flow needs](security-log-and-emails.md#emails-a-flow-needs), like the emailed code, each have their own shape. Give those a template by extending Keyring's class and registering yours, as [Your Own Templates](security-log-and-emails.md#your-own-templates) shows. Two things that catch people out: diff --git a/docs/security-log-and-emails.md b/docs/security-log-and-emails.md index 13a09e23..278c9910 100644 --- a/docs/security-log-and-emails.md +++ b/docs/security-log-and-emails.md @@ -241,50 +241,33 @@ public function share(Request $request): array ## Security Emails -Keyring writes no emails of its own. Every email it sends is a notification class in your app, published to `app/Notifications/Keyring` by `keyring:install` and registered in your `KeyringServiceProvider`: +Keyring sends its own emails. Each is an ordinary Laravel notification in `Keyring\Notifications`, sent through your app's mailer in Laravel's mail template, so there's nothing to publish or register. To change one, give Keyring your own class for its type in your `KeyringServiceProvider`, or `null` to turn it off: ```php -use App\Notifications\Keyring as Notifications; +use Keyring\Notifications\CloneSuspected; Keyring::notifications([ - 'verification_code' => Notifications\VerificationCode::class, - 'confirm_email_change' => Notifications\ConfirmEmailChange::class, - 'email_change_notice' => Notifications\EmailChangeNotice::class, - 'email_address_in_use' => Notifications\EmailAddressInUse::class, - 'already_registered' => Notifications\AlreadyRegistered::class, - 'password_changed' => Notifications\PasswordChanged::class, - 'authenticator_added' => Notifications\AuthenticatorAdded::class, - 'authenticator_removed' => Notifications\AuthenticatorRemoved::class, - 'recovery_code_used' => Notifications\RecoveryCodeUsed::class, - 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class, - 'email_changed' => Notifications\EmailChanged::class, - 'account_locked' => Notifications\AccountLocked::class, - 'new_device' => Notifications\NewDevice::class, - 'second_factor_failed' => Notifications\SecondFactorFailed::class, - 'suspicious_activity' => Notifications\SuspiciousActivity::class, - 'email_change_reverted' => Notifications\EmailChangeReverted::class, - // 'clone_suspected' => Notifications\CloneSuspected::class, + 'new_device' => \App\Notifications\NewDevice::class, // yours instead of Keyring's + 'recovery_code_used' => null, // not sent + 'clone_suspected' => CloneSuspected::class, // the one notice that starts off ]); ``` -A security notice that isn't listed isn't sent, so that list is how you turn one on or off. Unless you answer no (or pass `--no-emails`), `keyring:install` registers: +Types you leave out keep Keyring's own. Every security notice is on from the start except `clone_suspected`, which is sent once you list it as above. A notice goes out when its event happens, so one that belongs to something you haven't turned on is never sent: -- `password_changed`, `authenticator_added`, `authenticator_removed`, `recovery_code_used`, `recovery_codes_generated`, `email_changed`, `account_locked` and `suspicious_activity`, whichever sign-in methods and features you picked, -- `new_device` when `Features::devices()` is on, -- `second_factor_failed` when you picked a sign-in method besides the password, -- `email_change_reverted` when `Features::emailChanges()` is on. - -One of the last three that has nothing to announce yet is written commented out, with `clone_suspected`, so turning it on later is one line. Every notice's class is published either way. Nothing warns about a notice that isn't registered: with `--no-emails`, or in an app that doesn't use the published provider, no security notice is sent until you list some. +- `new_device` needs `Features::devices()`, +- `second_factor_failed` needs a sign-in method besides the password, +- `email_changed` and `email_change_reverted` need `Features::emailChanges()`. NIST SP 800-63B-4 requires a notice when an authenticator is bound to an account (Sec. 4.1.2.1: `authenticator_added`, and `password_changed` for a new password), when an account is recovered (Sec. 4.2.3: `password_changed` after a reset, and `recovery_code_used`) and when recovery codes are replaced (Sec. 4.2.1.1: `recovery_codes_generated`). It recommends one when an authenticator is removed (Sec. 4.5: `authenticator_removed`). -OWASP ASVS 5.0.0 asks for two kinds. Requirement 6.3.7 is a notice after a change to how someone signs in: `password_changed`, `authenticator_added`, `authenticator_removed`, `recovery_codes_generated`, `email_changed` and `email_change_reverted`. Requirement 6.3.5 is a notice of a suspicious attempt: `new_device`, `second_factor_failed`, `account_locked`, and `suspicious_activity` for what the [risk signals](risk.md#built-in-signals) find. The installer's defaults cover both as far as your features go, with one thing left to you for 6.3.5: a sign in after a long quiet period, or after several failures, is only announced once [your risk response notifies for it](risk.md#telling-the-user). [OWASP ASVS](owasp-asvs.md) has the whole list for each level. +OWASP ASVS 5.0.0 asks for two kinds. Requirement 6.3.7 is a notice after a change to how someone signs in: `password_changed`, `authenticator_added`, `authenticator_removed`, `recovery_codes_generated`, `email_changed` and `email_change_reverted`. Requirement 6.3.5 is a notice of a suspicious attempt: `new_device`, `second_factor_failed`, `account_locked`, and `suspicious_activity` for what the [risk signals](risk.md#built-in-signals) find. Keyring's own emails cover both as far as your features go, with one thing left to you for 6.3.5: a sign in after a long quiet period, or after several failures, is only announced once [your risk response notifies for it](risk.md#telling-the-user). [OWASP ASVS](owasp-asvs.md) has the whole list for each level. -Calling `Keyring::notifications()` again adds to the list, `null` takes a type out, and an unknown type throws an `InvalidArgumentException`, so a typo doesn't quietly turn an email off. +Calling `Keyring::notifications()` again adds to what you gave it before, and an unknown type throws an `InvalidArgumentException`, so a typo doesn't quietly leave an email as it was. An account is sent each kind of notice five times an hour at most (`limits.notices` every `limits.notices_per`), so nobody can make your app mail one person without end, by signing in from a new browser over and over, say. The [security log](#the-security-log) records every event either way. A `MustVerifyEmail` user gets none until their address is verified, because until then it's only what someone typed when registering. The one exception is `password_changed` after a password reset: the reset link went to that address, so whoever finished the reset reads its mailbox. -The classes are ordinary Laravel notifications and they're yours: change the wording, the channels or the whole template, or register a different class altogether. Keyring builds each one through the container and passes what it has to say as named constructor arguments, so a class takes only the ones it wants. +To reword an email, translate its strings: every one goes through `__()`, so a line in your `lang/en.json` replaces it. To restyle them all, publish Laravel's mail template (`php artisan vendor:publish --tag=laravel-mail`), which every `MailMessage` in your app uses. For anything more, see [Your Own Templates](#your-own-templates). Keyring builds each notification through the container and passes what it has to say as named constructor arguments, so a class of your own takes only the ones it wants. ### Email Types @@ -309,9 +292,9 @@ Every notice is also passed `when` (the time as text, in the app's timezone), `a Renaming a sign-in method, or choosing another as the default, sends nothing: neither changes what can sign in to the account. -`name`, `device` and `reasons` can hold what a user or browser sent: a key's name is whatever was typed. Keyring cuts each to one line of at most 500 characters, and it's still text to escape for wherever you show it. The published classes pass it through `Keyring\Support\MailText::plain()`, because Laravel reads mail lines as Markdown and a name could otherwise add a link to a genuine security email. +`name`, `device` and `reasons` can hold what a user or browser sent: a key's name is whatever was typed. Keyring cuts each to one line of at most 500 characters, and it's still text to escape for wherever you show it. Keyring's classes pass it through `Keyring\Support\MailText::plain()`, because Laravel reads mail lines as Markdown and a name could otherwise add a link to a genuine security email. -The published notices share an abstract `SecurityNotice` in the same folder, which holds the constructor, `via()` and `toMail()`. Each notice only says its subject and intro. They're queued once any open database transaction commits, so a change that's rolled back is never announced. +Keyring's notices share an abstract `Keyring\Notifications\SecurityNotice`, which holds the constructor, `via()` and `toMail()`. Each notice only says its `subject()`, its `intro()` and, when it has a button, its `action()`. They're queued once any open database transaction commits, so a change that's rolled back is never announced. ### A Support Contact @@ -322,7 +305,7 @@ NIST SP 800-63B-4 (Sec. 4.6) has a notice give clear instructions, including con 'support_contact' => 'https://example.com/support', // or 'support@example.com' ``` -Every notification Keyring builds is then handed it as `contact`, a security notice or an email a flow needs alike. The published security notices, `VerificationCode` and `EmailChangeNotice` end with "If this wasn't you and you need help, contact us" and the contact, as a link when it's a URL or an email address (`Keyring\Support\MailText::contact()` writes the line). The three emails that say nothing happened and can be ignored (`ConfirmEmailChange`, `EmailAddressInUse` and `AlreadyRegistered`) don't show it. Left at `null`, the default, no email has the line: set it before you say your notices follow NIST. +Every notification Keyring builds is then handed it as `contact`, a security notice or an email a flow needs alike. Keyring's security notices, `VerificationCode` and `EmailChangeNotice` end with "If this wasn't you and you need help, contact us" and the contact, as a link when it's a URL or an email address (`Keyring\Support\MailText::contact()` writes the line). The three emails that say nothing happened and can be ignored (`ConfirmEmailChange`, `EmailAddressInUse` and `AlreadyRegistered`) don't show it. Left at `null`, the default, no email has the line: set it before you say your notices follow NIST. The same section has notices go to every address an account has, and asks for at least two. Keyring knows one, the `email` attribute, and mails your user model as Laravel does. To send every notice to more than one address, return them from the model: @@ -338,7 +321,7 @@ That also changes where Laravel's own mail notifications go, which is usually wh ### Emails a Flow Needs -Five emails are part of a flow rather than a notice. The flow can't work without one, so it throws `Keyring\Exceptions\MissingNotification`, naming the type, when none is registered: +Five emails are part of a flow rather than a notice. The flow can't work without one, so it throws `Keyring\Exceptions\MissingNotification`, naming the type, if you set it to `null`: | Type | Sent to | Passes | |---|---|---| @@ -348,50 +331,71 @@ Five emails are part of a flow rather than a notice. The flow can't work without | `email_address_in_use` | An address someone tried to change their email to, when it already has an account. | | | `already_registered` | An address someone tried to [register](sign-in-flow.md#without-revealing-who-has-an-account) with, when it already has an account. | `loginUrl`, and `resetUrl` when password resets are on | -`verification_code` sends straight away; the three email change emails and `already_registered` are sent after the response, so timing doesn't reveal whether an address has an account. An email change is refused before anything is saved when one of its three is missing, and so is a registration without `already_registered`, unless `registration.reveal_taken` is on. +`verification_code` sends straight away; the three email change emails and `already_registered` are sent after the response, so timing doesn't reveal whether an address has an account. An email change is refused before anything is saved when one of its three is turned off, and so is a registration without `already_registered`, unless `registration.reveal_taken` is on. -The email change emails, `already_registered`, and the copies of `email_changed` and `email_change_reverted` that go to an address the account no longer has, are sent to a bare address: the `$notifiable` is an `AnonymousNotifiable` routed to mail, not your user. Keep `via()` and `toMail()` from reading user attributes in those classes. +The email change emails, `already_registered`, and the copies of `email_changed` and `email_change_reverted` that go to an address the account no longer has, are sent to a bare address: the `$notifiable` is an `AnonymousNotifiable` routed to mail, not your user. Keep `via()` and `toMail()` from reading user attributes in your own classes for those types. Password resets and email verification use Laravel's own `ResetPassword` and `VerifyEmail` notifications, with links Keyring builds from `APP_URL`. You change them the usual Laravel way, for example by overriding `sendPasswordResetNotification()` on your user model. The reset email is also sent after the response, and so is a new user's verification email, unless `registration.reveal_taken` is on. ### Your Own Templates -To use your own views, such as templates built with Maizzle, return them from `toMail()`. For one notice: +To write the email of every security notice from your own views, such as templates built with Maizzle, give `SecurityNotice` a callback in your `KeyringServiceProvider`. It's handed the notice and who it's for: + +```php +use Illuminate\Notifications\Messages\MailMessage; +use Keyring\Notifications\SecurityNotice; + +SecurityNotice::toMailUsing(fn (SecurityNotice $notice, object $notifiable) => (new MailMessage) + ->subject($notice->subject()) + ->view('emails.keyring.notice', [ + 'intro' => $notice->intro(), + 'when' => $notice->when, + 'device' => $notice->device, + 'ip' => $notice->ip, + 'actionText' => $notice->action(), + 'actionUrl' => $notice->action() === null ? null : $notice->url, + 'contact' => $notice->contact, + ])); +``` + +Blade's `{{ }}` escapes those values for HTML. The callback may return a `Mailable` instead. [Emails With Maizzle](recipes.md#emails-with-maizzle) walks through it, and the [example app](https://github.com/entity/keyring-example#emails) builds every email this way: Maizzle templates compiled to Blade views, one shared by every notice, with a local page to preview them. + +For one notice, or for one of the [emails a flow needs](#emails-a-flow-needs), extend Keyring's class and register yours: ```php -namespace App\Notifications\Keyring; +namespace App\Notifications; use Illuminate\Notifications\Messages\MailMessage; +use Keyring\Notifications\PasswordChanged as KeyringPasswordChanged; -class PasswordChanged extends SecurityNotice +class PasswordChanged extends KeyringPasswordChanged { - // subject() and intro() as published. - public function toMail(object $notifiable): MailMessage { return (new MailMessage) - ->subject(__('Your password was changed')) - ->view('emails.keyring.password-changed', [ - 'when' => $this->when, - 'device' => $this->device, - 'ip' => $this->ip, - ]); + ->subject($this->subject()) + ->view('emails.password-changed', ['when' => $this->when, 'device' => $this->device, 'ip' => $this->ip]); } } ``` -Blade's `{{ }}` escapes those values for HTML. [Emails With Maizzle](recipes.md#emails-with-maizzle) walks through it, and the [example app](https://github.com/entity/keyring-example#emails) builds every email this way: Maizzle templates compiled to Blade views, one shared by every notice, with a local page to preview them. To change every notice at once, edit `toMail()` in your `SecurityNotice`. A notification doesn't have to extend it either: any class whose constructor takes the arguments it wants will do, and `toMail()` may return a `Mailable`. +```php +Keyring::notifications(['password_changed' => \App\Notifications\PasswordChanged::class]); +``` + +A notification doesn't have to extend Keyring's either: any class whose constructor takes the arguments it wants will do. ### Slack, SMS and Other Channels Notifications can go anywhere Laravel can send. Choose the channels in `via()`, per user if you like, and add the matching method: ```php -namespace App\Notifications\Keyring; +namespace App\Notifications; use Illuminate\Notifications\Slack\SlackMessage; +use Keyring\Notifications\NewDevice as KeyringNewDevice; -class NewDevice extends SecurityNotice +class NewDevice extends KeyringNewDevice { public function via(object $notifiable): array { @@ -403,16 +407,16 @@ class NewDevice extends SecurityNotice // Slack reads <...> as a link, and a user agent is whatever the browser sent. return (new SlackMessage)->text(htmlspecialchars($this->subject().': '.$this->device, ENT_NOQUOTES)); } - - // subject(), intro() and action() as published. } ``` +Register it with `Keyring::notifications(['new_device' => \App\Notifications\NewDevice::class])`. + Slack needs Laravel's `laravel/slack-notification-channel` package; see [Laravel's notification docs](https://laravel.com/docs/notifications#slack-notifications) for it and the other channels. For the `database` or `broadcast` channels, add a `toArray()`. ### Sending Something Else Entirely -Keyring dispatches an [event](events.md) for everything it sends a notice about, whether or not a notification is registered. To do something other than notify the user, leave the type out of `Keyring::notifications()` and listen for the event. +Keyring dispatches an [event](events.md) for everything it sends a notice about, whether or not the notice is on. To do something other than notify the user, set the type to `null` in `Keyring::notifications()` and listen for the event. ## Laravel's Auth Events diff --git a/docs/security.md b/docs/security.md index eba7b2db..1468a36d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -644,7 +644,7 @@ Each of these is a choice. The reason is given once, here, and the [requirement- - **"Remember me" signs a browser back in without a factor.** NIST SP 800-63B-4 (Sec. 5.1) doesn't accept a cookie in place of authentication. A browser that ticked "remember me" comes back signed in after its session idled out, for up to 14 days (`sessions.remember_idle`), because that is what the checkbox is for. Keyring ties the cookie to the session it was ticked for, lets it work once and gives the session it resumes no assurance level, so routes behind `keyring:aal1`, `keyring:aal2` or `keyring.fresh` ask again, but a route behind `auth` alone is reached on the cookie. Where you follow that section, leave the checkbox off your login form or set `sessions.end_on_lapse`. See [Inactivity and "Remember Me"](devices-and-sessions.md#inactivity-and-remember-me). - **A session outlives its assurance level.** NIST SP 800-63B-4 (Sec. 5.2) ends a session when its inactivity or overall timeout passes. By default Keyring lowers the session's level instead: a session that signed in with two factors stops being AAL2 after an hour idle or 24 hours and carries on as AAL1, under the limits every session has. Sec. 5.1 allows a session to be treated as a lower level, and ending it would sign out the people who set up a second factor after an hour away while leaving everyone else signed in for 30 days. `sessions.end_on_lapse` ends it. See [Ending a Session With Its Level](devices-and-sessions.md#ending-a-session-with-its-level). - **An account has one email address.** NIST SP 800-63B-4 asks for at least two addresses to send notices to (Sec. 4.6) and two to recover an account through (Sec. 4.2.1.2). Keyring knows the one in your user model's `email` attribute: it's where reset links, emailed codes and security notices go. A library with one attribute to read can't supply a second. To send every notice to more than one address, return them from `routeNotificationForMail()` ([A Support Contact](security-log-and-emails.md#a-support-contact) shows how). A second address that can recover the account, verified before it's used, is your app's to build. -- **A notice doesn't say who to contact until you say where.** NIST SP 800-63B-4 (Sec. 4.6) has a notice carry contact information. The published notices have the line and leave it out while [`support_contact`](security-log-and-emails.md#a-support-contact) is `null`, since only you know where your support is. +- **A notice doesn't say who to contact until you say where.** NIST SP 800-63B-4 (Sec. 4.6) has a notice carry contact information. Keyring's notices have the line and leave it out while [`support_contact`](security-log-and-emails.md#a-support-contact) is `null`, since only you know where your support is. - **No pepper.** NIST SP 800-63B-4 (Sec. 3.1.1.2) and OWASP's Password Storage Cheat Sheet recommend one. See [Peppering Passwords](#peppering-passwords) for why it isn't built in and how to add it. - **The breach check fails open by default.** Laravel's check lets a new password through when Have I Been Pwned can't be reached, leaving the bundled list of common passwords, so that an outage elsewhere doesn't stop registrations. OWASP ASVS 5.0.0's requirement 16.5.2 would have it refuse. Set `passwords.refuse_unchecked` to refuse the password instead, at the cost of no new passwords while the service is unreachable. Outside production the check doesn't run at all unless `passwords.uncompromised` is `true`. - **The per-minute limits are kept in the cache.** Clearing the limiter's cache store starts the per-minute counts over and lifts their locks and risk locks, which OWASP ASVS 5.0.0's requirement 16.5.3 counts as failing open. A count on every attempt belongs somewhere fast, and what ends guessing doesn't depend on it: the failures in a row and the locks held until a reset are in your database. See [Rate Limiting](#rate-limiting). diff --git a/src/Concerns/ManagesNotifications.php b/src/Concerns/ManagesNotifications.php index 5f244eb1..d4898b5c 100644 --- a/src/Concerns/ManagesNotifications.php +++ b/src/Concerns/ManagesNotifications.php @@ -7,15 +7,16 @@ use Illuminate\Notifications\Notification; use InvalidArgumentException; use Keyring\Exceptions\MissingNotification; +use Keyring\Notifications; /** - * The app's notification for each email Keyring sends. + * The notification for each email Keyring sends: its own, or the app's. */ trait ManagesNotifications { /** - * Every notification Keyring can send: the security notices, which are - * only sent once the app registers one, then the emails a flow needs. + * Every notification Keyring can send: the security notices, then the + * emails a flow needs. */ public const array NOTIFICATIONS = [ 'new_device', 'password_changed', 'authenticator_added', 'authenticator_removed', @@ -25,14 +26,38 @@ trait ManagesNotifications 'already_registered', ]; - /** @var array> The app's notification for each type it sends. */ + /** + * Keyring's own notification for each type, sent unless the app gives + * its own or turns the type off. A suspected clone is the one type that + * starts off: the app turns it on with Notifications\CloneSuspected. + */ + protected const array DEFAULT_NOTIFICATIONS = [ + 'new_device' => Notifications\NewDevice::class, + 'password_changed' => Notifications\PasswordChanged::class, + 'authenticator_added' => Notifications\AuthenticatorAdded::class, + 'authenticator_removed' => Notifications\AuthenticatorRemoved::class, + 'second_factor_failed' => Notifications\SecondFactorFailed::class, + 'recovery_code_used' => Notifications\RecoveryCodeUsed::class, + 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class, + 'suspicious_activity' => Notifications\SuspiciousActivity::class, + 'account_locked' => Notifications\AccountLocked::class, + 'email_changed' => Notifications\EmailChanged::class, + 'email_change_reverted' => Notifications\EmailChangeReverted::class, + 'verification_code' => Notifications\VerificationCode::class, + 'confirm_email_change' => Notifications\ConfirmEmailChange::class, + 'email_change_notice' => Notifications\EmailChangeNotice::class, + 'email_address_in_use' => Notifications\EmailAddressInUse::class, + 'already_registered' => Notifications\AlreadyRegistered::class, + ]; + + /** @var array|null> What the app changed: its own notification for a type, or null for one it turned off. */ protected array $notifications = []; /** - * The app's notification for each type Keyring sends, added to any set - * before. A security notice with none isn't sent, and null takes one out - * again. Keyring builds each through the container, passing what it has - * to say as named constructor arguments. + * Change the notification Keyring sends for a type: the app's own class, + * or null to send none. Types left out keep Keyring's own, and a call + * adds to the ones before it. Keyring builds each through the container, + * passing what it has to say as named constructor arguments. * * @param array|null> $notifications */ @@ -42,33 +67,35 @@ public function notifications(array $notifications): static throw new InvalidArgumentException('Unknown notification types: '.implode(', ', $unknown).'. Keyring sends: '.implode(', ', self::NOTIFICATIONS).'.'); } - $this->notifications = array_filter([...$this->notifications, ...$notifications]); + $this->notifications = [...$this->notifications, ...$notifications]; return $this; } public function hasNotification(string $type): bool { - return isset($this->notifications[$type]); + return $this->notificationClass($type) !== null; } /** - * The app's notification of a type, or null when it hasn't one. Each is - * also handed where to reach the app's support ("support_contact"), as + * The notification of a type, or null when it's turned off. Each is also + * handed where to reach the app's support ("support_contact"), as * $contact, for the ones that say who to turn to. * * @param array $arguments */ public function notification(string $type, array $arguments = []): ?Notification { - return $this->hasNotification($type) - ? app($this->notifications[$type], ['contact' => config('keyring.support_contact'), ...$arguments]) - : null; + $class = $this->notificationClass($type); + + return $class === null + ? null + : app($class, ['contact' => config('keyring.support_contact'), ...$arguments]); } /** * For the emails a flow can't work without, like the code for an email - * code: the app's notification, or an exception saying which is missing. + * code: the notification, or an exception saying which was turned off. * * @param array $arguments */ @@ -76,4 +103,14 @@ public function requiredNotification(string $type, array $arguments = []): Notif { return $this->notification($type, $arguments) ?? throw MissingNotification::for($type); } + + /** + * @return class-string|null + */ + protected function notificationClass(string $type): ?string + { + return array_key_exists($type, $this->notifications) + ? $this->notifications[$type] + : self::DEFAULT_NOTIFICATIONS[$type] ?? null; + } } diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php index e4cec7d2..02a09d32 100644 --- a/src/Console/InstallCommand.php +++ b/src/Console/InstallCommand.php @@ -4,7 +4,6 @@ namespace Keyring\Console; -use Closure; use Illuminate\Auth\EloquentUserProvider; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; @@ -26,8 +25,6 @@ #[Signature('keyring:install {--factor=* : A sign-in method to add besides the password: totp, passkeys, security-keys or email-codes} {--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} - {--emails : Register the emails that tell users their password, sign-in methods or email address changed (the default)} - {--no-emails : Register no security emails, only the ones a flow needs} {--require-second-factor : Make every user set up a second factor (the default with 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}')] @@ -61,27 +58,6 @@ class InstallCommand extends Command */ protected const array SECOND_FACTORS = ['totp', 'passkeys', 'security-keys']; - /** - * The security notices registered unless the answer is no, and how the - * question names each. One is only offered once its notification is - * among the published ones, so a notice can be listed here before the - * release that brings its class. One with nothing to announce in this - * app yet (announces) is listed commented out. - */ - protected const array NOTICES = [ - 'password_changed' => 'password changed', - 'authenticator_added' => 'sign-in method added', - 'authenticator_removed' => 'sign-in method removed', - 'recovery_code_used' => 'recovery code used', - 'recovery_codes_generated' => 'new recovery codes made', - 'email_changed' => 'email address changed', - 'account_locked' => 'account locked', - 'new_device' => 'signed in on a new device', - 'second_factor_failed' => 'second factor failed after the right password', - 'suspicious_activity' => 'suspicious sign in or session', - 'email_change_reverted' => 'email change undone', - ]; - /** * The risk signals the provider starts with, and the feature each reads * from. One whose feature is off is left commented out, there to turn on @@ -133,8 +109,8 @@ public function handle(Filesystem $files): int return self::FAILURE; } - // The provider, actions and notifications are your code from here on. - // Every one is published, so turning a feature on later just works. + // The provider and actions are your code from here on. Every action + // is published, so turning a feature on later just works. $provider = app_path('Providers/KeyringServiceProvider.php'); $writesProvider = ! $files->exists($provider) || $this->option('force'); @@ -154,15 +130,13 @@ public function handle(Filesystem $files): int if ($writesProvider) { $files->ensureDirectoryExists(dirname($provider)); - $files->put($provider, $this->provider($files, $factors, $this->emails($files, $features, $factors), $enrolled, $features)); + $files->put($provider, $this->provider($files, $factors, $enrolled, $features)); } else { $this->components->warn("Skipped {$provider}, it already exists."); } - foreach (['Actions/Keyring', 'Notifications/Keyring'] as $directory) { - foreach ($files->files(self::STUBS.'/app/'.$directory) as $file) { - $this->write($files, app_path($directory.'/'.$file->getFilename()), $file->getContents()); - } + foreach ($files->files(self::STUBS.'/app/Actions/Keyring') as $file) { + $this->write($files, app_path('Actions/Keyring/'.$file->getFilename()), $file->getContents()); } ServiceProvider::addProviderToBootstrapFile('App\\Providers\\KeyringServiceProvider'); @@ -181,7 +155,7 @@ public function handle(Filesystem $files): int 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 and emails in your KeyringServiceProvider', + 'Add features later in config/keyring.php, and sign-in methods in your KeyringServiceProvider', ])); // What whoever runs the app will want to know before it's live. @@ -217,59 +191,6 @@ protected function requiresSecondFactor(array $factors): bool }; } - /** - * @param list $features - * @param list $factors - */ - protected function emails(Filesystem $files, array $features, array $factors): bool - { - return match (true) { - $this->option('emails') => true, - $this->option('no-emails') => false, - $this->input->isInteractive() => confirm( - label: 'Email users when their password, sign-in methods or email address change?', - default: true, - hint: Str::ucfirst(implode(', ', array_map( - fn (string $type) => self::NOTICES[$type], - array_filter($this->notices($files), fn (string $type) => $this->announces($type, $features, $factors)), - ))).'.', - ), - default => true, - }; - } - - /** - * The security notices on offer: those whose notification is published. - * - * @return list - */ - protected function notices(Filesystem $files): array - { - return array_values(array_filter( - array_keys(self::NOTICES), - fn (string $type) => $files->exists(self::STUBS.'/app/Notifications/Keyring/'.Str::studly($type).'.php'), - )); - } - - /** - * Whether a notice has anything to announce in this app: a new device - * takes devices, an undone email change takes email changes, and a - * failed second factor takes a sign-in method to ask for after the - * password. - * - * @param list $features - * @param list $factors - */ - protected function announces(string $type, array $features, array $factors): bool - { - return match ($type) { - 'new_device' => in_array(Features::devices(), $features, true), - 'email_change_reverted' => in_array(Features::emailChanges(), $features, true), - 'second_factor_failed' => $factors !== [], - default => true, - }; - } - protected function userModelHasKeyring(): bool { $provider = Keyring::provider(); @@ -366,14 +287,13 @@ 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, the - * risk signals the features can feed, and the security notices left - * commented when they weren't wanted. + * 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 $emails, bool $enrolled, array $features = self::FEATURES): string + protected function provider(Filesystem $files, array $factors, bool $enrolled, array $features = self::FEATURES): string { $remove = $factors === [] ? ['RecoveryCodes::class,'] : []; @@ -392,11 +312,7 @@ protected function provider(Filesystem $files, array $factors, bool $emails, boo }, ); - return $this->withNotices( - $files, - $this->withSignals($this->withoutUnusedImports($this->withoutOrphanedComments(implode("\n", $lines))), $features), - fn (string $type) => $emails && $this->announces($type, $features, $factors), - ); + return $this->withSignals($this->withoutUnusedImports($this->withoutOrphanedComments(implode("\n", $lines))), $features); } /** @@ -414,41 +330,6 @@ protected function withSignals(string $provider, array $features): string : (string) preg_replace('/^( +)(Signals\\\\(?:'.implode('|', $off).')::class,)$/m', '$1// $2', $provider); } - /** - * List each security notice on offer in the provider, after the one - * before it when the stub doesn't have it yet, and commented out when - * it isn't registered: the notices weren't wanted, or this one has - * nothing to announce yet. One that isn't on offer is taken out. - * - * @param Closure(string): bool $registers - */ - protected function withNotices(Filesystem $files, string $provider, Closure $registers): string - { - $offered = $this->notices($files); - $after = "'already_registered' => "; - - foreach (array_keys(self::NOTICES) as $type) { - $entry = "'{$type}' => Notifications\\".Str::studly($type).'::class,'; - $listed = '/^( +)(?:\/\/ )?'.preg_quote($entry, '/').'\n/m'; - - if (! in_array($type, $offered, true)) { - $provider = (string) preg_replace($listed, '', $provider); - - continue; - } - - $line = fn (array $match) => $match[1].($registers($type) ? '' : '// ').$entry."\n"; - - $provider = (string) (preg_match($listed, $provider) === 1 - ? preg_replace_callback($listed, $line, $provider) - : preg_replace_callback('/^( +)(?:\/\/ )?'.preg_quote($after, '/').'.*\n/m', fn (array $match) => $match[0].$line($match), $provider)); - - $after = "'{$type}' => "; - } - - return $provider; - } - /** * Comments whose code was removed, and the blank line before them. */ diff --git a/src/Exceptions/MissingNotification.php b/src/Exceptions/MissingNotification.php index a059f745..c0bd555d 100644 --- a/src/Exceptions/MissingNotification.php +++ b/src/Exceptions/MissingNotification.php @@ -11,7 +11,7 @@ class MissingNotification extends LogicException public static function for(string $type): self { return new self(sprintf( - 'No notification is registered for [%1$s], which this needs to send. Add \'%1$s\' to Keyring::notifications([...]) in your KeyringServiceProvider; keyring:install publishes one to app/Notifications/Keyring.', + 'No notification is registered for [%1$s], which this needs to send. Keyring::notifications([...]) set \'%1$s\' to null: give it a notification class there, or leave it out to send Keyring\'s own.', $type, )); } diff --git a/stubs/app/Notifications/Keyring/AccountLocked.php b/src/Notifications/AccountLocked.php similarity index 67% rename from stubs/app/Notifications/Keyring/AccountLocked.php rename to src/Notifications/AccountLocked.php index 639a8ac8..5987b83d 100644 --- a/stubs/app/Notifications/Keyring/AccountLocked.php +++ b/src/Notifications/AccountLocked.php @@ -2,21 +2,21 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class AccountLocked extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('Your account is locked'); } - protected function intro(): string + public function intro(): string { return __('Too many failed attempts to sign in have locked your account. Reset your password to unlock it.'); } - protected function action(): ?string + public function action(): ?string { return __('Reset your password'); } diff --git a/stubs/app/Notifications/Keyring/AlreadyRegistered.php b/src/Notifications/AlreadyRegistered.php similarity index 97% rename from stubs/app/Notifications/Keyring/AlreadyRegistered.php rename to src/Notifications/AlreadyRegistered.php index 2bf1e2c7..445ab406 100644 --- a/stubs/app/Notifications/Keyring/AlreadyRegistered.php +++ b/src/Notifications/AlreadyRegistered.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; diff --git a/stubs/app/Notifications/Keyring/AuthenticatorAdded.php b/src/Notifications/AuthenticatorAdded.php similarity index 69% rename from stubs/app/Notifications/Keyring/AuthenticatorAdded.php rename to src/Notifications/AuthenticatorAdded.php index 63d568dd..2e333ea3 100644 --- a/stubs/app/Notifications/Keyring/AuthenticatorAdded.php +++ b/src/Notifications/AuthenticatorAdded.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class AuthenticatorAdded extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('A sign-in method was added'); } - protected function intro(): string + public function intro(): string { return __('":name" was added as a way to sign in to your account.', ['name' => $this->name]); } diff --git a/stubs/app/Notifications/Keyring/AuthenticatorRemoved.php b/src/Notifications/AuthenticatorRemoved.php similarity index 68% rename from stubs/app/Notifications/Keyring/AuthenticatorRemoved.php rename to src/Notifications/AuthenticatorRemoved.php index fc634411..25d0da4d 100644 --- a/stubs/app/Notifications/Keyring/AuthenticatorRemoved.php +++ b/src/Notifications/AuthenticatorRemoved.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class AuthenticatorRemoved extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('A sign-in method was removed'); } - protected function intro(): string + public function intro(): string { return __('":name" was removed from your account.', ['name' => $this->name]); } diff --git a/stubs/app/Notifications/Keyring/CloneSuspected.php b/src/Notifications/CloneSuspected.php similarity index 72% rename from stubs/app/Notifications/Keyring/CloneSuspected.php rename to src/Notifications/CloneSuspected.php index 64801eb1..1e30c4da 100644 --- a/stubs/app/Notifications/Keyring/CloneSuspected.php +++ b/src/Notifications/CloneSuspected.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class CloneSuspected extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('A security key may have been copied'); } - protected function intro(): string + public function intro(): string { return __('":name" answered with an out-of-date counter, which can mean it was copied. We refused the sign-in.', ['name' => $this->name]); } diff --git a/stubs/app/Notifications/Keyring/ConfirmEmailChange.php b/src/Notifications/ConfirmEmailChange.php similarity index 96% rename from stubs/app/Notifications/Keyring/ConfirmEmailChange.php rename to src/Notifications/ConfirmEmailChange.php index 8bba4afa..24bd81d5 100644 --- a/stubs/app/Notifications/Keyring/ConfirmEmailChange.php +++ b/src/Notifications/ConfirmEmailChange.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; use DateTimeInterface; use Illuminate\Notifications\Messages\MailMessage; diff --git a/stubs/app/Notifications/Keyring/EmailAddressInUse.php b/src/Notifications/EmailAddressInUse.php similarity index 96% rename from stubs/app/Notifications/Keyring/EmailAddressInUse.php rename to src/Notifications/EmailAddressInUse.php index 6a796cd1..9bba90b0 100644 --- a/stubs/app/Notifications/Keyring/EmailAddressInUse.php +++ b/src/Notifications/EmailAddressInUse.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; diff --git a/stubs/app/Notifications/Keyring/EmailChangeNotice.php b/src/Notifications/EmailChangeNotice.php similarity index 98% rename from stubs/app/Notifications/Keyring/EmailChangeNotice.php rename to src/Notifications/EmailChangeNotice.php index f28a393b..aab3af59 100644 --- a/stubs/app/Notifications/Keyring/EmailChangeNotice.php +++ b/src/Notifications/EmailChangeNotice.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; diff --git a/stubs/app/Notifications/Keyring/EmailChangeReverted.php b/src/Notifications/EmailChangeReverted.php similarity index 71% rename from stubs/app/Notifications/Keyring/EmailChangeReverted.php rename to src/Notifications/EmailChangeReverted.php index 6342069c..1b417f65 100644 --- a/stubs/app/Notifications/Keyring/EmailChangeReverted.php +++ b/src/Notifications/EmailChangeReverted.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class EmailChangeReverted extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('Your email address change was undone'); } - protected function intro(): string + public function intro(): string { return __('A change to the email address on your account was just undone, and you were signed out everywhere.'); } diff --git a/stubs/app/Notifications/Keyring/EmailChanged.php b/src/Notifications/EmailChanged.php similarity index 76% rename from stubs/app/Notifications/Keyring/EmailChanged.php rename to src/Notifications/EmailChanged.php index 80ae5c73..e51f8dcb 100644 --- a/stubs/app/Notifications/Keyring/EmailChanged.php +++ b/src/Notifications/EmailChanged.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class EmailChanged extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('Your email address was changed'); } - protected function intro(): string + public function intro(): string { return __('The email address on your account was just changed. You now sign in and recover your account with the new address. To undo it, use the link in the email we sent to the old address when the change was requested.'); } diff --git a/stubs/app/Notifications/Keyring/NewDevice.php b/src/Notifications/NewDevice.php similarity index 65% rename from stubs/app/Notifications/Keyring/NewDevice.php rename to src/Notifications/NewDevice.php index 800779d5..5bccf605 100644 --- a/stubs/app/Notifications/Keyring/NewDevice.php +++ b/src/Notifications/NewDevice.php @@ -2,21 +2,21 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class NewDevice extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('New sign-in to your account'); } - protected function intro(): string + public function intro(): string { return __('Your account was just signed in to from a device we haven\'t seen before.'); } - protected function action(): ?string + public function action(): ?string { return __('This wasn\'t me'); } diff --git a/stubs/app/Notifications/Keyring/PasswordChanged.php b/src/Notifications/PasswordChanged.php similarity index 65% rename from stubs/app/Notifications/Keyring/PasswordChanged.php rename to src/Notifications/PasswordChanged.php index 34a4db30..86ca500d 100644 --- a/stubs/app/Notifications/Keyring/PasswordChanged.php +++ b/src/Notifications/PasswordChanged.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class PasswordChanged extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('Your password was changed'); } - protected function intro(): string + public function intro(): string { return __('The password for your account was just changed.'); } diff --git a/stubs/app/Notifications/Keyring/RecoveryCodeUsed.php b/src/Notifications/RecoveryCodeUsed.php similarity index 71% rename from stubs/app/Notifications/Keyring/RecoveryCodeUsed.php rename to src/Notifications/RecoveryCodeUsed.php index 50c8f3fa..7737816d 100644 --- a/stubs/app/Notifications/Keyring/RecoveryCodeUsed.php +++ b/src/Notifications/RecoveryCodeUsed.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class RecoveryCodeUsed extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('A recovery code was used'); } - protected function intro(): string + public function intro(): string { return __('A recovery code was used to sign in to your account. You have :remaining left.', ['remaining' => $this->remaining]); } diff --git a/stubs/app/Notifications/Keyring/RecoveryCodesGenerated.php b/src/Notifications/RecoveryCodesGenerated.php similarity index 72% rename from stubs/app/Notifications/Keyring/RecoveryCodesGenerated.php rename to src/Notifications/RecoveryCodesGenerated.php index 7457ce12..a7c6374b 100644 --- a/stubs/app/Notifications/Keyring/RecoveryCodesGenerated.php +++ b/src/Notifications/RecoveryCodesGenerated.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class RecoveryCodesGenerated extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('New recovery codes were made for your account'); } - protected function intro(): string + public function intro(): string { return __('A new set of recovery codes was made for your account. Any codes you saved before no longer work.'); } diff --git a/stubs/app/Notifications/Keyring/SecondFactorFailed.php b/src/Notifications/SecondFactorFailed.php similarity index 73% rename from stubs/app/Notifications/Keyring/SecondFactorFailed.php rename to src/Notifications/SecondFactorFailed.php index 4d4db324..11088c2b 100644 --- a/stubs/app/Notifications/Keyring/SecondFactorFailed.php +++ b/src/Notifications/SecondFactorFailed.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class SecondFactorFailed extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('Someone entered your password'); } - protected function intro(): string + public function intro(): string { return __('Someone signed in with your password but couldn\'t complete the second step. If this wasn\'t you, your password is probably known to someone else.'); } diff --git a/stubs/app/Notifications/Keyring/SecurityNotice.php b/src/Notifications/SecurityNotice.php similarity index 67% rename from stubs/app/Notifications/Keyring/SecurityNotice.php rename to src/Notifications/SecurityNotice.php index 3d90a675..daca70d1 100644 --- a/stubs/app/Notifications/Keyring/SecurityNotice.php +++ b/src/Notifications/SecurityNotice.php @@ -2,19 +2,21 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; +use Closure; use DateTimeInterface; use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Mail\Mailable; use Illuminate\Contracts\Queue\ShouldQueueAfterCommit; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Keyring\Support\MailText; /** - * What every security notice shares. Change via() to send them somewhere - * else, or toMail() to use your own views: here for all of them, or in one - * notice for just that one. + * What every security notice shares. To send one somewhere else or from + * your own views, extend it and give Keyring::notifications() your class. + * To write the email of every notice yourself, use toMailUsing(). * * Queued once any open transaction commits, so a change that's rolled back * is never announced. @@ -23,6 +25,13 @@ abstract class SecurityNotice extends Notification implements ShouldQueueAfterCo { use Queueable; + /** + * The app's own email for every notice, when it has one. + * + * @var (Closure(self, object): (MailMessage|Mailable))|null + */ + protected static ?Closure $toMailCallback = null; + /** * Keyring fills in whichever of these the notice has. Some hold what * users and browsers sent (a key's name, a user agent), cut to one line, @@ -42,14 +51,26 @@ public function __construct( public ?string $contact = null, ) {} - abstract protected function subject(): string; + /** + * Write the email of every notice yourself, from your own views say. + * The callback is given the notice and who it's for, and returns the + * mail. Null goes back to Keyring's own. + * + * @param (Closure(self, object): (MailMessage|Mailable))|null $callback + */ + public static function toMailUsing(?Closure $callback): void + { + self::$toMailCallback = $callback; + } + + abstract public function subject(): string; - abstract protected function intro(): string; + abstract public function intro(): string; /** * The label of the button to $url, for notices that have one. */ - protected function action(): ?string + public function action(): ?string { return null; } @@ -69,8 +90,12 @@ public function via(object $notifiable): array * Mail lines are read as Markdown, so anything that could hold a user's * text goes through MailText::plain() to stay plain text. */ - public function toMail(object $notifiable): MailMessage + public function toMail(object $notifiable): MailMessage|Mailable { + if (self::$toMailCallback !== null) { + return (self::$toMailCallback)($this, $notifiable); + } + $message = new MailMessage()->subject($this->subject())->line(MailText::plain($this->intro())); $details = array_filter([__('When') => $this->when, __('Device') => $this->device, __('IP address') => $this->ip]); diff --git a/src/Notifications/SendSecurityNotifications.php b/src/Notifications/SendSecurityNotifications.php index aa1bd167..9104966f 100644 --- a/src/Notifications/SendSecurityNotifications.php +++ b/src/Notifications/SendSecurityNotifications.php @@ -17,8 +17,8 @@ use Keyring\Support\Url; /** - * Sends the app's notification for each security notice it has registered - * with Keyring::notifications(). One with none registered isn't sent. + * Sends the notification for each security notice: Keyring's own, or the + * app's from Keyring::notifications(). One the app turned off isn't sent. */ class SendSecurityNotifications { diff --git a/stubs/app/Notifications/Keyring/SuspiciousActivity.php b/src/Notifications/SuspiciousActivity.php similarity index 71% rename from stubs/app/Notifications/Keyring/SuspiciousActivity.php rename to src/Notifications/SuspiciousActivity.php index 8a3f06c6..cec00747 100644 --- a/stubs/app/Notifications/Keyring/SuspiciousActivity.php +++ b/src/Notifications/SuspiciousActivity.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; class SuspiciousActivity extends SecurityNotice { - protected function subject(): string + public function subject(): string { return __('Unusual activity on your account'); } - protected function intro(): string + public function intro(): string { return __('We noticed something unusual and asked for extra verification: :reasons', ['reasons' => $this->reasons]); } diff --git a/stubs/app/Notifications/Keyring/VerificationCode.php b/src/Notifications/VerificationCode.php similarity index 97% rename from stubs/app/Notifications/Keyring/VerificationCode.php rename to src/Notifications/VerificationCode.php index 8c3973fa..61071664 100644 --- a/stubs/app/Notifications/Keyring/VerificationCode.php +++ b/src/Notifications/VerificationCode.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Notifications\Keyring; +namespace Keyring\Notifications; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; diff --git a/stubs/app/Providers/KeyringServiceProvider.php b/stubs/app/Providers/KeyringServiceProvider.php index bb1c08e3..5b50324f 100644 --- a/stubs/app/Providers/KeyringServiceProvider.php +++ b/stubs/app/Providers/KeyringServiceProvider.php @@ -8,7 +8,6 @@ use App\Actions\Keyring\ResetUserPassword; use App\Actions\Keyring\UpdateUserPassword; use App\Actions\Keyring\ValidateEmailChange; -use App\Notifications\Keyring as Notifications; use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\ServiceProvider; use Keyring\Facades\Keyring; @@ -74,29 +73,5 @@ public function boot(): void Keyring::resetUserPasswordsUsing(ResetUserPassword::class); Keyring::updateUserPasswordsUsing(UpdateUserPassword::class); Keyring::validateEmailChangesUsing(ValidateEmailChange::class); - - // The emails Keyring sends, in app/Notifications/Keyring. They're - // yours to restyle or send another way, and a security notice that - // isn't listed here isn't sent. One that's commented out has nothing - // to announce until its feature is on. See "Security Log & Emails". - Keyring::notifications([ - 'verification_code' => Notifications\VerificationCode::class, - 'confirm_email_change' => Notifications\ConfirmEmailChange::class, - 'email_change_notice' => Notifications\EmailChangeNotice::class, - 'email_address_in_use' => Notifications\EmailAddressInUse::class, - 'already_registered' => Notifications\AlreadyRegistered::class, - 'password_changed' => Notifications\PasswordChanged::class, - 'authenticator_added' => Notifications\AuthenticatorAdded::class, - 'authenticator_removed' => Notifications\AuthenticatorRemoved::class, - 'recovery_code_used' => Notifications\RecoveryCodeUsed::class, - 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class, - 'email_changed' => Notifications\EmailChanged::class, - 'account_locked' => Notifications\AccountLocked::class, - 'new_device' => Notifications\NewDevice::class, - 'second_factor_failed' => Notifications\SecondFactorFailed::class, - 'suspicious_activity' => Notifications\SuspiciousActivity::class, - 'email_change_reverted' => Notifications\EmailChangeReverted::class, - // 'clone_suspected' => Notifications\CloneSuspected::class, - ]); } } diff --git a/stubs/config/keyring.php b/stubs/config/keyring.php index 60a152fd..fb6037d2 100644 --- a/stubs/config/keyring.php +++ b/stubs/config/keyring.php @@ -80,8 +80,8 @@ |-------------------------------------------------------------------------- | | Where users can reach you about their account: a page's URL or an email - | address. The emails in app/Notifications/Keyring then end by saying who - | to contact if something wasn't them. Null leaves that line out. + | address. Keyring's emails then end by saying who to contact if + | something wasn't them. Null leaves that line out. | */ diff --git a/tests/Feature/AuthenticatorManagementTest.php b/tests/Feature/AuthenticatorManagementTest.php index 259ce551..fabd38b2 100644 --- a/tests/Feature/AuthenticatorManagementTest.php +++ b/tests/Feature/AuthenticatorManagementTest.php @@ -2,8 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\AuthenticatorAdded as AuthenticatorAddedNotice; -use App\Notifications\Keyring\RecoveryCodesGenerated as RecoveryCodesGeneratedNotice; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Http\Request; @@ -29,6 +27,8 @@ use Keyring\Login\Attempt; use Keyring\Login\Requirement; use Keyring\Models\Authenticator; +use Keyring\Notifications\AuthenticatorAdded as AuthenticatorAddedNotice; +use Keyring\Notifications\RecoveryCodesGenerated as RecoveryCodesGeneratedNotice; use Keyring\Sessions\SessionAssurance; use Keyring\Support\PasswordRules; use Keyring\Testing\VirtualAuthenticator; @@ -298,10 +298,11 @@ Notification::assertSentTo($this->user, AuthenticatorAddedNotice::class); }); -it('tells the user when their recovery codes are replaced, once the app registers the notice', function () { +it('tells the user when their recovery codes are replaced, unless the app turned the notice off', function () { $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); $this->verifiedWith($totp); Notification::fake(); + Keyring::notifications(['recovery_codes_generated' => null]); $this->postJson(route('keyring.authenticators.store', 'recovery'))->assertOk(); $this->postJson(route('keyring.authenticators.confirm', 'recovery'))->assertOk(); diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index f2f66a9d..959597ad 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -5,7 +5,6 @@ use App\Actions\Keyring\ResetUserPassword; use App\Actions\Keyring\UpdateUserPassword; use App\Actions\Keyring\ValidateEmailChange; -use App\Notifications\Keyring\SuspiciousActivity; use App\Providers\KeyringServiceProvider; use Illuminate\Console\Scheduling\Event; use Illuminate\Console\Scheduling\Schedule; @@ -39,6 +38,7 @@ use Keyring\Models\Authenticator; use Keyring\Models\PendingChange; use Keyring\Models\SecurityEvent; +use Keyring\Notifications\SuspiciousActivity; use Keyring\Risk\Checkpoint; use Keyring\Risk\Level; use Keyring\Risk\Signals\InactiveAccount; @@ -71,7 +71,7 @@ $files->delete($files->glob(database_path('migrations/*_create_keyring_*'))); }); - it('installs the password, registration, resets, verification, password changes, the security log and the security emails without asking', function () { + it('installs the password, registration, resets, verification, password changes and the security log without asking', function () { $this->artisan('keyring:install', ['--no-interaction' => true]) ->expectsOutputToContain('Nothing makes users set up a second factor') ->assertSuccessful(); @@ -87,33 +87,18 @@ // There to fill in: nobody but the app knows where its support is. ->and($config)->toHaveKey('support_contact', null) ->and(file_get_contents(config_path('keyring.php')))->toContain('// Features::devices(),') - // The emails a flow needs are registered, and the notices about changes. - ->and($provider)->toContain(" 'verification_code' => Notifications\VerificationCode::class,") - ->toContain(" 'already_registered' => Notifications\AlreadyRegistered::class,") - ->toContain(" 'password_changed' => Notifications\PasswordChanged::class,") - ->toContain(" 'authenticator_added' => Notifications\AuthenticatorAdded::class,") - ->toContain(" 'authenticator_removed' => Notifications\AuthenticatorRemoved::class,") - ->toContain(" 'recovery_code_used' => Notifications\RecoveryCodeUsed::class,") - ->toContain(" 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class,") - ->toContain(" 'email_changed' => Notifications\EmailChanged::class,") - ->toContain(" 'account_locked' => Notifications\AccountLocked::class,") - // What the risk signals find is announced. The notices with - // nothing to announce yet are there to turn on. - ->toContain(" 'suspicious_activity' => Notifications\SuspiciousActivity::class,") - ->toContain(" // 'new_device' => Notifications\NewDevice::class,") - ->toContain(" // 'second_factor_failed' => Notifications\SecondFactorFailed::class,") - ->toContain(" // 'email_change_reverted' => Notifications\EmailChangeReverted::class,") + // Keyring's emails are its own, so the provider lists none and + // none are published. + ->and($provider)->not->toContain('Notifications') + ->and(is_dir($this->sandbox.'/app/Notifications'))->toBeFalse() + ->and($provider) // The risk signals the default features can feed, and the rest // there to turn on. ->toContain(" Signals\SessionFingerprintChanged::class,\n") ->toContain(" Signals\SuccessAfterFailures::class,\n") ->toContain(" // Signals\NewDevice::class,\n") ->toContain(" // Signals\BreachedPassword::class,\n") - // Every notification there is, whichever are registered. - ->and(array_map(basename(...), glob($this->sandbox.'/app/Notifications/Keyring/*.php'))) - ->toEqualCanonicalizing(array_map(basename(...), glob(__DIR__.'/../../stubs/app/Notifications/Keyring/*.php'))) - ->toContain('AlreadyRegistered.php') - ->and($provider)->toContain('Password::class,') + ->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') @@ -127,20 +112,6 @@ expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); }); - it('registers a security notice for every one that is published, and no other', function () { - $this->artisan('keyring:install', ['--no-interaction' => true])->assertSuccessful(); - - $provider = file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); - - foreach (['PasswordChanged', 'AuthenticatorAdded', 'AuthenticatorRemoved', 'RecoveryCodeUsed', 'RecoveryCodesGenerated', 'EmailChanged', 'AccountLocked'] as $notice) { - $line = " '".Str::snake($notice)."' => Notifications\\{$notice}::class,"; - - file_exists(__DIR__."/../../stubs/app/Notifications/Keyring/{$notice}.php") - ? expect($provider)->toContain($line) - : expect($provider)->not->toContain($notice); - } - }); - it('adds the sign-in methods and features picked, and what they need', function () { $this->artisan('keyring:install', [ '--factor' => ['totp', 'passkeys'], @@ -152,14 +123,7 @@ $provider = file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); expect($config['features'])->toBe([Features::updatePasswords(), Features::manageAuthenticators(), Features::devices()]) - ->and($provider)->toContain(" 'recovery_code_used' => Notifications\RecoveryCodeUsed::class,") - // Devices are on and there's a second factor to fail, so both are announced. - ->toContain(" 'new_device' => Notifications\NewDevice::class,") - ->toContain(" 'second_factor_failed' => Notifications\SecondFactorFailed::class,") - ->toContain(" 'suspicious_activity' => Notifications\SuspiciousActivity::class,") - ->toContain(" // 'email_change_reverted' => Notifications\EmailChangeReverted::class,") - ->toContain(" // 'clone_suspected' => Notifications\CloneSuspected::class,") - ->toContain(" Signals\NewDevice::class,\n") + ->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'); @@ -275,22 +239,10 @@ expect(file_exists(config_path('keyring.php')))->toBeFalse(); }); - it('can leave out the security emails', function () { - $this->artisan('keyring:install', ['--factor' => ['totp'], '--no-emails' => true, '--no-interaction' => true]) - // The emails say who to contact once the app says where that is. + it('says where to tell the emails who users can contact', function () { + $this->artisan('keyring:install', ['--factor' => ['totp'], '--no-interaction' => true]) ->expectsOutputToContain('Set support_contact in config/keyring.php') ->assertSuccessful(); - - expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) - ->toContain(" // 'password_changed' => Notifications\PasswordChanged::class,") - ->toContain(" // 'second_factor_failed' => Notifications\SecondFactorFailed::class,") - ->toContain(" // 'suspicious_activity' => Notifications\SuspiciousActivity::class,") - ->toContain(" // 'authenticator_added' => Notifications\AuthenticatorAdded::class,") - ->toContain(" // 'email_changed' => Notifications\EmailChanged::class,") - ->toContain(" 'email_change_notice' => Notifications\EmailChangeNotice::class,") - ->toContain(" 'already_registered' => Notifications\AlreadyRegistered::class,"); - - expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); }); it('asks which sign-in methods and features to set up, with the safe answers as the defaults', function () { @@ -298,7 +250,6 @@ ->expectsChoice('Which sign-in methods besides the password?', ['passkeys'], ['totp' => 'Authenticator app', 'passkeys' => 'Passkeys', 'security-keys' => 'Security keys, as a second factor', 'email-codes' => 'Email codes, as an extra step at sign in (not a second factor)']) ->expectsConfirmation('Require a second factor for everyone?', 'yes') ->expectsQuestion('Which features?', [Features::resetPasswords(), Features::manageAuthenticators()]) - ->expectsConfirmation('Email users when their password, sign-in methods or email address change?', 'yes') ->assertSuccessful(); expect((require config_path('keyring.php'))['features'])->toBe([Features::resetPasswords(), Features::manageAuthenticators()]) @@ -309,12 +260,10 @@ $this->artisan('keyring:install') ->expectsChoice('Which sign-in methods besides the password?', [], ['totp' => 'Authenticator app', 'passkeys' => 'Passkeys', 'security-keys' => 'Security keys, as a second factor', 'email-codes' => 'Email codes, as an extra step at sign in (not a second factor)']) ->expectsQuestion('Which features?', [Features::registration(), Features::resetPasswords(), Features::emailVerification(), Features::updatePasswords()]) - ->expectsConfirmation('Email users when their password, sign-in methods or email address change?', 'no') ->assertSuccessful(); expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) - ->not->toContain('keyring.enrolled') - ->toContain(" // 'password_changed' => Notifications\PasswordChanged::class,"); + ->not->toContain('keyring.enrolled'); }); it('can run again without duplicating migrations or overwriting customised files', function () { @@ -361,95 +310,6 @@ }); })->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) { - $command = new InstallCommand; - $stub = file_get_contents(__DIR__.'/../../stubs/app/Providers/KeyringServiceProvider.php'); - $prefix = $emails ? '' : '// '; - - // A release where two of the notifications don't exist, or do, with a - // provider stub that lists both of them or neither. - $release = fn (bool $published, bool $listed) => new class($published, $listed ? $stub : preg_replace('/^.*(?:RecoveryCodesGenerated|AccountLocked).*\n/m', '', $stub)) extends Filesystem - { - public function __construct(protected bool $published, protected string $stub) {} - - public function exists($path) - { - return Str::endsWith($path, ['/RecoveryCodesGenerated.php', '/AccountLocked.php']) ? $this->published : parent::exists($path); - } - - public function get($path, $lock = false) - { - return Str::endsWith($path, '/Providers/KeyringServiceProvider.php') ? $this->stub : parent::get($path, $lock); - } - }; - - $provider = fn (bool $published, bool $listed) => (fn () => $this->provider($release($published, $listed), [], $emails, false))->call($command); - - expect($provider(published: true, listed: true))->toContain(<< Notifications\\PasswordChanged::class, - {$prefix}'authenticator_added' => Notifications\\AuthenticatorAdded::class, - {$prefix}'authenticator_removed' => Notifications\\AuthenticatorRemoved::class, - {$prefix}'recovery_code_used' => Notifications\\RecoveryCodeUsed::class, - {$prefix}'recovery_codes_generated' => Notifications\\RecoveryCodesGenerated::class, - {$prefix}'email_changed' => Notifications\\EmailChanged::class, - {$prefix}'account_locked' => Notifications\\AccountLocked::class, - // 'new_device' => Notifications\\NewDevice::class, - // 'second_factor_failed' => Notifications\\SecondFactorFailed::class, - {$prefix}'suspicious_activity' => Notifications\\SuspiciousActivity::class, - // 'email_change_reverted' => Notifications\\EmailChangeReverted::class, - // 'clone_suspected' => Notifications\\CloneSuspected::class, - - PHP) - ->toBe($provider(published: true, listed: false)) - ->and($provider(published: false, listed: true)) - ->not->toContain('RecoveryCodesGenerated')->not->toContain('AccountLocked') - ->toContain("{$prefix}'recovery_code_used' => Notifications\\RecoveryCodeUsed::class,\n {$prefix}'email_changed' => Notifications\\EmailChanged::class,\n") - ->toBe($provider(published: false, listed: false)); -})->with(['with the emails' => true, 'without them' => false]); - -it('registers a notice only once the app has something for it to announce', function (array $features, array $factors, array $registered, array $commented) { - $provider = (fn () => $this->provider(new Filesystem, $factors, true, false, $features))->call(new InstallCommand); - - foreach ($registered as $type) { - expect($provider)->toContain(" '{$type}' => Notifications\\".Str::studly($type)."::class,\n"); - } - - foreach ($commented as $type) { - expect($provider)->toContain(" // '{$type}' => Notifications\\".Str::studly($type)."::class,\n"); - } -})->with([ - 'the default features and the password alone' => [ - ['registration', 'reset-passwords', 'email-verification', 'update-passwords', 'security-log'], [], - ['password_changed', 'account_locked', 'suspicious_activity'], - ['new_device', 'second_factor_failed', 'email_change_reverted', 'clone_suspected'], - ], - 'devices' => [ - ['devices'], [], - ['new_device', 'suspicious_activity'], - ['second_factor_failed', 'email_change_reverted'], - ], - 'email changes' => [ - ['email-changes'], [], - ['email_changed', 'email_change_reverted'], - ['new_device', 'second_factor_failed'], - ], - 'a second sign-in method' => [ - ['manage-authenticators'], ['totp'], - ['second_factor_failed'], - ['new_device', 'email_change_reverted'], - ], - 'an emailed code, which is asked for after the password too' => [ - ['manage-authenticators'], ['email-codes'], - ['second_factor_failed'], - ['new_device', 'email_change_reverted'], - ], - 'everything' => [ - Features::all(), ['totp', 'passkeys'], - ['new_device', 'second_factor_failed', 'suspicious_activity', 'email_change_reverted'], - ['clone_suspected'], - ], -]); - describe('the risk signals a new provider starts with', function () { /** * The provider keyring:install writes for these features, and the @@ -460,7 +320,7 @@ public function get($path, $lock = false) */ function publishedSignals(array $features): array { - $provider = (fn () => $this->provider(new Filesystem, [], true, false, $features))->call(new InstallCommand); + $provider = (fn () => $this->provider(new Filesystem, [], false, $features))->call(new InstallCommand); preg_match_all('/^ +(\/\/ )?Signals\\\\(\w+)::class,$/m', $provider, $lines, PREG_SET_ORDER); @@ -503,7 +363,7 @@ function publishedSignals(array $features): array it('writes a provider that is valid PHP whichever are on', function (array $features) { $path = sys_get_temp_dir().'/keyring-provider-'.uniqid().'.php'; - file_put_contents($path, (fn () => $this->provider(new Filesystem, [], true, false, $features))->call(new InstallCommand)); + file_put_contents($path, (fn () => $this->provider(new Filesystem, [], false, $features))->call(new InstallCommand)); expectValidPhp($path); File::delete($path); diff --git a/tests/Feature/CustomFactorTest.php b/tests/Feature/CustomFactorTest.php index 26e4f8d9..8cb6c2df 100644 --- a/tests/Feature/CustomFactorTest.php +++ b/tests/Feature/CustomFactorTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\VerificationCode; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Notification; @@ -18,6 +17,7 @@ use Keyring\Login\Requirement; use Keyring\Login\Verification; use Keyring\Models\Authenticator; +use Keyring\Notifications\VerificationCode; use Keyring\Sessions\SessionAssurance; use Keyring\Tests\Fixtures\SmsCode; diff --git a/tests/Feature/EmailChangeHardeningTest.php b/tests/Feature/EmailChangeHardeningTest.php index a9b4db57..c31532ff 100644 --- a/tests/Feature/EmailChangeHardeningTest.php +++ b/tests/Feature/EmailChangeHardeningTest.php @@ -2,12 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\ConfirmEmailChange; -use App\Notifications\Keyring\EmailAddressInUse; -use App\Notifications\Keyring\EmailChanged; -use App\Notifications\Keyring\EmailChangeNotice; -use App\Notifications\Keyring\EmailChangeReverted; -use App\Notifications\Keyring\VerificationCode; use Illuminate\Database\Schema\Blueprint; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Facades\Auth; @@ -34,6 +28,12 @@ use Keyring\Features; use Keyring\Models\Authenticator; use Keyring\Models\PendingChange; +use Keyring\Notifications\ConfirmEmailChange; +use Keyring\Notifications\EmailAddressInUse; +use Keyring\Notifications\EmailChanged; +use Keyring\Notifications\EmailChangeNotice; +use Keyring\Notifications\EmailChangeReverted; +use Keyring\Notifications\VerificationCode; use Keyring\Rules\UnreservedAddress; use Keyring\Sessions\RegisteredSession; use Keyring\Sessions\Sessions; @@ -747,7 +747,8 @@ function otherSession(User $user, string $id = 'other-session'): string Notification::assertSentTo(new AnonymousNotifiable, EmailChanged::class, fn ($notice, $channels, $to) => $to->routes['mail'] === 'taylor@example.com'); }); - it('sends no notice unless the app opted in', function () { + it('sends no notice the app turned off', function () { + Keyring::notifications(['email_changed' => null]); $change = requestChange($this->user, 'new@example.com'); $tokens = tokensFor('new@example.com', 'taylor@example.com'); @@ -796,7 +797,7 @@ function otherSession(User $user, string $id = 'other-session'): string }); /** - * An app's own notification, nothing to do with the published one. + * An app's own notification, nothing to do with Keyring's. */ class OwnEmailChanged extends Illuminate\Notifications\Notification { diff --git a/tests/Feature/EmailCodeTest.php b/tests/Feature/EmailCodeTest.php index 29fa91af..f9cb36f7 100644 --- a/tests/Feature/EmailCodeTest.php +++ b/tests/Feature/EmailCodeTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\VerificationCode; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Notification; @@ -22,6 +21,7 @@ use Keyring\Login\Verification; use Keyring\Models\Authenticator; use Keyring\Models\Device; +use Keyring\Notifications\VerificationCode; use Keyring\Risk\Action; use Keyring\Risk\Signals\NewDevice; use Keyring\Sessions\SessionAssurance; diff --git a/tests/Feature/EmailedLinksTest.php b/tests/Feature/EmailedLinksTest.php index c65ec162..6f50c1ea 100644 --- a/tests/Feature/EmailedLinksTest.php +++ b/tests/Feature/EmailedLinksTest.php @@ -2,9 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\ConfirmEmailChange; -use App\Notifications\Keyring\EmailChangeNotice; -use App\Notifications\Keyring\NewDevice; use Illuminate\Auth\Events\Verified; use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; @@ -20,6 +17,9 @@ use Keyring\Http\Middleware\ValidatePostedSignature; use Keyring\Models\Device; use Keyring\Models\PendingChange; +use Keyring\Notifications\ConfirmEmailChange; +use Keyring\Notifications\EmailChangeNotice; +use Keyring\Notifications\NewDevice; use Keyring\Tests\Fixtures\User; // An emailed link has to carry its token in its URL. The page it opens posts diff --git a/tests/Feature/ExtendingTest.php b/tests/Feature/ExtendingTest.php index e46e34dc..2854c543 100644 --- a/tests/Feature/ExtendingTest.php +++ b/tests/Feature/ExtendingTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); -use App\Notifications\Keyring\ConfirmEmailChange; use Illuminate\Auth\Events\Failed; use Illuminate\Auth\Events\Lockout; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Routing\RouteCollection; use Illuminate\Routing\UrlGenerator; use Illuminate\Support\Facades\Event; @@ -17,9 +17,11 @@ use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Str; use Illuminate\Validation\Rules\Password; use Illuminate\Validation\ValidationException; use Keyring\Changes\EmailChanges; +use Keyring\Changes\ProtectedAttributes; use Keyring\Contracts\ResetsUserPasswords; use Keyring\Contracts\Responses\StatusResponse; use Keyring\Contracts\SessionRegistry; @@ -32,6 +34,7 @@ use Keyring\Exceptions\ProtectedAttributeException; use Keyring\Facades\Keyring; use Keyring\Factors\EmailCode; +use Keyring\Factors\FactorRegistry; use Keyring\Factors\Password as PasswordFactor; use Keyring\KeyringManager; use Keyring\KeyringServiceProvider; @@ -41,6 +44,9 @@ use Keyring\Models\Authenticator; use Keyring\Models\PendingChange; use Keyring\Models\SecurityEvent; +use Keyring\Notifications\CloneSuspected; +use Keyring\Notifications\ConfirmEmailChange; +use Keyring\Notifications\SecurityNotice; use Keyring\Pipeline\Context; use Keyring\Pipeline\Outcome; use Keyring\Pipeline\Steps; @@ -136,6 +142,53 @@ public function toResponse($request) $this->actingAs($this->user)->withAssurance(Assurance::AAL1)->postJson('/user/authenticators/sms')->assertNotFound(); }); +it('sends its own notification for every type but a suspected clone, until the app says otherwise', function () { + $keyring = new KeyringManager(new FactorRegistry, app(ProtectedAttributes::class)); + + foreach (array_diff(KeyringManager::NOTIFICATIONS, ['clone_suspected']) as $type) { + expect($keyring->notification($type, [ + 'when' => 'Monday', 'code' => '12345678', 'minutes' => 10, 'email' => 'n•••@example.com', + 'url' => 'https://example.com/link', 'expiresAt' => now()->addDay(), 'revertUrl' => 'https://example.com/revert', + 'loginUrl' => 'https://example.com/login', + ]))->toBeInstanceOf('Keyring\\Notifications\\'.Str::studly($type)); + } + + expect($keyring->hasNotification('clone_suspected'))->toBeFalse() + ->and($keyring->notification('clone_suspected', ['when' => 'Monday']))->toBeNull(); + + // The app's own class for one, another turned off, and the clone turned on. + $keyring->notifications(['confirm_email_change' => CustomConfirmEmailChange::class, 'new_device' => null]) + ->notifications(['clone_suspected' => CloneSuspected::class]); + + expect($keyring->notification('confirm_email_change', ['url' => 'https://example.com/confirm', 'expiresAt' => now()->addDay()]))->toBeInstanceOf(CustomConfirmEmailChange::class) + ->and($keyring->hasNotification('new_device'))->toBeFalse() + ->and($keyring->notification('clone_suspected', ['when' => 'Monday']))->toBeInstanceOf(CloneSuspected::class) + // The rest are as they were. + ->and($keyring->hasNotification('password_changed'))->toBeTrue(); +}); + +it('lets the app write the email of every security notice in one place', function () { + SecurityNotice::toMailUsing(fn (SecurityNotice $notice, object $notifiable) => new MailMessage() + ->subject('Acme: '.$notice->subject()) + ->line($notice->intro()) + ->line("For {$notifiable->email}, {$notice->when}.")); + + try { + $mail = Keyring::requiredNotification('password_changed', ['when' => 'Monday'])->toMail($this->user); + $device = Keyring::requiredNotification('new_device', ['when' => 'Monday', 'url' => 'https://example.com/report']); + + expect($mail->subject)->toBe('Acme: Your password was changed') + ->and(renderedMail($mail)['text'])->toContain('The password for your account was just changed.')->toContain('For taylor@example.com, Monday.') + ->and($device->toMail($this->user)->subject)->toBe('Acme: New sign-in to your account') + ->and($device->action())->toBe('This wasn\'t me'); + } finally { + SecurityNotice::toMailUsing(null); + } + + // Keyring's own again. + expect(Keyring::requiredNotification('password_changed', ['when' => 'Monday'])->toMail($this->user)->subject)->toBe('Your password was changed'); +}); + it('sends the app\'s own notification for an email a flow needs', function () { Notification::fake(); Keyring::notifications(['confirm_email_change' => CustomConfirmEmailChange::class]); @@ -307,6 +360,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('lets apps add steps around the mandatory ones and replace the others', function () { Log::spy(); + Notification::fake(); Keyring::pipeline(fn (Steps $steps) => $steps ->before(EnsureNotThrottled::class, NotesItRan::class) @@ -336,6 +390,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('lets an app dangerously remove a mandatory step, and logs a warning', function () { Log::spy(); + Notification::fake(); config(['keyring.limits.per_account' => 3, 'keyring.limits.per_ip' => 100]); Keyring::pipeline(fn (Steps $steps) => $steps->dangerouslyRemove(EnsureNotThrottled::class)); @@ -353,6 +408,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('lets an app dangerously replace a mandatory step, and logs a warning', function () { Log::spy(); + Notification::fake(); Keyring::pipeline(fn (Steps $steps) => $steps->dangerouslyReplace(EnsureNotThrottled::class, NotesItRan::class)); @@ -437,7 +493,7 @@ public function update(Authenticatable&Model $user, array $input): void } } -it('publishes a notification for every type, that builds from what keyring passes and renders', function (string $type) { +it('has a notification for every type, that builds from what keyring passes and renders', function (string $type) { sendNotifications(); $notification = Keyring::requiredNotification($type, [ @@ -490,9 +546,9 @@ public function handle(Context $context, Closure $next): Context // recipient says the event wasn't theirs. describe('a support contact', function () { /** - * The published notification of a type, as Keyring would build it. + * Keyring's own notification of a type, as it would build it. */ - function publishedNotification(string $type): Illuminate\Notifications\Notification + function ownNotification(string $type): Illuminate\Notifications\Notification { sendNotifications(); @@ -505,7 +561,7 @@ function publishedNotification(string $type): Illuminate\Notifications\Notificat it('is in every notice about the account once the app sets one', function (string $type) { config(['keyring.support_contact' => 'https://example.com/support?from=email']); - $mail = renderedMail(publishedNotification($type)->toMail($this->user)); + $mail = renderedMail(ownNotification($type)->toMail($this->user)); expect($mail['text'])->toContain('contact us')->toContain('https://example.com/support?from=email') ->and($mail['html'])->toContain('href="https://example.com/support?from=email"'); @@ -514,7 +570,7 @@ function publishedNotification(string $type): Illuminate\Notifications\Notificat it('links an email address as one', function () { config(['keyring.support_contact' => 'help@example.com']); - $mail = renderedMail(publishedNotification('password_changed')->toMail($this->user)); + $mail = renderedMail(ownNotification('password_changed')->toMail($this->user)); expect($mail['html'])->toContain('href="mailto:help@example.com"')->toContain('>help@example.com') ->and($mail['text'])->toContain('contact us: [help@example.com](mailto:help@example.com)'); @@ -523,14 +579,14 @@ function publishedNotification(string $type): Illuminate\Notifications\Notificat it('leaves anything that isn\'t a page or an address as plain text', function () { config(['keyring.support_contact' => 'Call 020 7946 0000 [or](https://evil.example) visit reception']); - $mail = renderedMail(publishedNotification('password_changed')->toMail($this->user)); + $mail = renderedMail(ownNotification('password_changed')->toMail($this->user)); expect($mail['html'])->toContain('contact us: Call 020 7946 0000 [or](https://evil.example) visit reception')->not->toContain('href="https://evil.example"') ->and($mail['text'])->toContain('contact us: Call 020 7946 0000 [or](https://evil.example) visit reception'); }); it('is left out until then', function (string $type) { - $notification = publishedNotification($type); + $notification = ownNotification($type); expect($notification->contact)->toBeNull() ->and(renderedMail($notification->toMail($this->user))['text'])->not->toContain('contact us'); diff --git a/tests/Feature/FeaturesTest.php b/tests/Feature/FeaturesTest.php index 959c2cd4..e5a9a066 100644 --- a/tests/Feature/FeaturesTest.php +++ b/tests/Feature/FeaturesTest.php @@ -83,12 +83,12 @@ $this->inertia()->get(route('keyring.login.challenge'))->assertJsonPath('props.canTrustDevice', false); }); -it('starts with the password, registration, password resets, email verification, password changes, the security log and no emails', function () { +it('starts with the password, registration, password resets, email verification, password changes, the security log and its own emails', function () { $config = require __DIR__.'/../../config/keyring.php'; expect(new FactorRegistry()->all()->keys()->all())->toBe(['password']) ->and($config['features'])->toBe([Features::registration(), Features::resetPasswords(), Features::emailVerification(), Features::updatePasswords(), Features::securityLog()]) ->and($config['registration']['reveal_taken'])->toBeFalse() - ->and(new KeyringManager(new FactorRegistry, app(ProtectedAttributes::class))->hasNotification('password_changed'))->toBeFalse() + ->and(new KeyringManager(new FactorRegistry, app(ProtectedAttributes::class))->hasNotification('password_changed'))->toBeTrue() ->and($config['protected'])->toBe([]); }); diff --git a/tests/Feature/MailLimitsTest.php b/tests/Feature/MailLimitsTest.php index f1cce52c..464441f2 100644 --- a/tests/Feature/MailLimitsTest.php +++ b/tests/Feature/MailLimitsTest.php @@ -2,12 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\AccountLocked; -use App\Notifications\Keyring\ConfirmEmailChange; -use App\Notifications\Keyring\EmailChangeNotice; -use App\Notifications\Keyring\NewDevice; -use App\Notifications\Keyring\PasswordChanged; -use App\Notifications\Keyring\RecoveryCodesGenerated as RecoveryCodesGeneratedNotice; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; use Illuminate\Testing\TestResponse; @@ -18,6 +12,12 @@ use Keyring\Models\Authenticator; use Keyring\Models\PendingChange; use Keyring\Models\SecurityEvent; +use Keyring\Notifications\AccountLocked; +use Keyring\Notifications\ConfirmEmailChange; +use Keyring\Notifications\EmailChangeNotice; +use Keyring\Notifications\NewDevice; +use Keyring\Notifications\PasswordChanged; +use Keyring\Notifications\RecoveryCodesGenerated as RecoveryCodesGeneratedNotice; use Keyring\Tests\Fixtures\User; // None of this mail is a guess at anything, so the limits on guessing never diff --git a/tests/Feature/ProtectedChangesTest.php b/tests/Feature/ProtectedChangesTest.php index 25efef8c..d6c3707b 100644 --- a/tests/Feature/ProtectedChangesTest.php +++ b/tests/Feature/ProtectedChangesTest.php @@ -2,9 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\ConfirmEmailChange; -use App\Notifications\Keyring\EmailAddressInUse; -use App\Notifications\Keyring\EmailChangeNotice; use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Notifications\AnonymousNotifiable; @@ -22,6 +19,9 @@ use Keyring\Exceptions\ProtectedAttributeException; use Keyring\Facades\Keyring; use Keyring\Models\Authenticator; +use Keyring\Notifications\ConfirmEmailChange; +use Keyring\Notifications\EmailAddressInUse; +use Keyring\Notifications\EmailChangeNotice; use Keyring\Sessions\Sessions; use Keyring\Support\Url; use Keyring\Tests\Fixtures\User; diff --git a/tests/Feature/RateLimitKeysTest.php b/tests/Feature/RateLimitKeysTest.php index f5d8cd20..318bcb2b 100644 --- a/tests/Feature/RateLimitKeysTest.php +++ b/tests/Feature/RateLimitKeysTest.php @@ -2,8 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\NewDevice; -use App\Notifications\Keyring\VerificationCode; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\RateLimiter as Limiter; use Illuminate\Support\Facades\Cache; @@ -16,6 +14,8 @@ use Keyring\Factors\Password; use Keyring\Factors\WebAuthn; use Keyring\Models\Authenticator; +use Keyring\Notifications\NewDevice; +use Keyring\Notifications\VerificationCode; use Keyring\Support\Throttle; use Keyring\Testing\VirtualAuthenticator; diff --git a/tests/Feature/RegistrationTest.php b/tests/Feature/RegistrationTest.php index c1b0645b..2e8ec255 100644 --- a/tests/Feature/RegistrationTest.php +++ b/tests/Feature/RegistrationTest.php @@ -3,7 +3,6 @@ declare(strict_types=1); use App\Actions\Keyring\CreateNewUser; -use App\Notifications\Keyring\AlreadyRegistered; use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Events\Verified; use Illuminate\Auth\Notifications\ResetPassword; @@ -31,6 +30,7 @@ use Keyring\Login\Registration; use Keyring\Models\Device; use Keyring\Models\PendingChange; +use Keyring\Notifications\AlreadyRegistered; use Keyring\Sessions\SessionAssurance; use Keyring\Tests\Fixtures\PlainUser; use Keyring\Tests\Fixtures\RacedRegistration; diff --git a/tests/Feature/RiskTest.php b/tests/Feature/RiskTest.php index 3b1d2e4f..95c3bca9 100644 --- a/tests/Feature/RiskTest.php +++ b/tests/Feature/RiskTest.php @@ -2,11 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\AuthenticatorAdded as AuthenticatorAddedNotice; -use App\Notifications\Keyring\NewDevice as NewDeviceNotice; -use App\Notifications\Keyring\PasswordChanged; -use App\Notifications\Keyring\SecondFactorFailed; -use App\Notifications\Keyring\SuspiciousActivity; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\QueryException; use Illuminate\Http\Request; @@ -30,6 +25,11 @@ use Keyring\Login\Requirement; use Keyring\Models\Authenticator; use Keyring\Models\SecurityEvent; +use Keyring\Notifications\AuthenticatorAdded as AuthenticatorAddedNotice; +use Keyring\Notifications\NewDevice as NewDeviceNotice; +use Keyring\Notifications\PasswordChanged; +use Keyring\Notifications\SecondFactorFailed; +use Keyring\Notifications\SuspiciousActivity; use Keyring\Risk\Action; use Keyring\Risk\Assessment; use Keyring\Risk\Checkpoint; @@ -355,7 +355,8 @@ function expectOwnerStillSignedIn(string $session): void expect(app(SecurityLog::class)->pullAlerts($this->user))->toBeEmpty(); }); -it('sends security emails only when asked to', function () { +it('sends no security email the app turned off', function () { + Keyring::notifications(['new_device' => null]); signInAs(); Notification::assertNothingSent(); $this->post('/logout'); @@ -439,7 +440,7 @@ function expectOwnerStillSignedIn(string $session): void 'several lines' => ["[Not you?](https://evil.example/x)\n\nRobert's key", "[Not you?](https://evil.example/x) Robert's key"], ]); -it('shows a name someone typed as plain text in the published email', function () { +it('shows a name someone typed as plain text in the email', function () { $notice = new AuthenticatorAddedNotice(when: 'now', name: "[Not you?](https://evil.example/x) Robert's key"); $mail = renderedMail($notice->toMail($this->user)); diff --git a/tests/Feature/SignedLinksTest.php b/tests/Feature/SignedLinksTest.php index 54ce24f6..12cc8059 100644 --- a/tests/Feature/SignedLinksTest.php +++ b/tests/Feature/SignedLinksTest.php @@ -2,12 +2,12 @@ declare(strict_types=1); -use App\Notifications\Keyring\NewDevice; use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Http\Middleware\TrustProxies; use Illuminate\Support\Facades\Notification; use Keyring\Models\Device; +use Keyring\Notifications\NewDevice; use Keyring\Tests\Fixtures\User; beforeEach(function () { diff --git a/tests/Feature/StandardsDocsTest.php b/tests/Feature/StandardsDocsTest.php index c8bd430a..7c340438 100644 --- a/tests/Feature/StandardsDocsTest.php +++ b/tests/Feature/StandardsDocsTest.php @@ -4,7 +4,10 @@ use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Str; +use Keyring\Changes\ProtectedAttributes; use Keyring\Console\InstallCommand; +use Keyring\Factors\FactorRegistry; +use Keyring\KeyringManager; use Keyring\Support\Duration; // docs/owasp-asvs.md says what a default install gives an app and where @@ -15,7 +18,7 @@ $this->defaults = require __DIR__.'/../../config/keyring.php'; // What keyring:install writes with its default answers. - $this->provider = (fn () => $this->provider(new Filesystem, [], true, false))->call(new InstallCommand); + $this->provider = (fn () => $this->provider(new Filesystem, [], false))->call(new InstallCommand); }); it('lists the features a default install turns on', function () { @@ -27,18 +30,21 @@ ->and($line[1])->toBe('five'); }); -it('counts the security emails and risk signals a default install registers', function () { - $notices = Str::matchAll("/^ +'([a-z_]+)' => Notifications/m", $this->provider) +it('counts the security emails Keyring sends and the risk signals a default install registers', function () { + // What Keyring sends before an app changes anything. + $keyring = new KeyringManager(new FactorRegistry, app(ProtectedAttributes::class)); + $notices = collect(KeyringManager::NOTIFICATIONS) ->reject(fn (string $type) => in_array($type, ['verification_code', 'confirm_email_change', 'email_change_notice', 'email_address_in_use', 'already_registered'], true)) + ->filter(fn (string $type) => $keyring->hasNotification($type)) ->values(); $signals = Str::matchAll('/^ +Signals\\\\(\w+)::class,$/m', $this->provider); preg_match('/^- (\w+) \[security emails\]\([^)]+\): (.+),$/m', $this->page, $emails); preg_match('/^- (\w+) \[risk signals\]\([^)]+\): (.+),$/m', $this->page, $risk); - expect($notices->all())->toBe(['password_changed', 'authenticator_added', 'authenticator_removed', 'recovery_code_used', 'recovery_codes_generated', 'email_changed', 'account_locked', 'suspicious_activity']) - ->and($emails[1])->toBe('eight') - // One phrase for each, in the order the provider lists them. + expect($notices->all())->toBe(['new_device', 'password_changed', 'authenticator_added', 'authenticator_removed', 'second_factor_failed', 'recovery_code_used', 'recovery_codes_generated', 'suspicious_activity', 'account_locked', 'email_changed', 'email_change_reverted']) + ->and($emails[1])->toBe('eleven') + // One phrase for each, in the order Keyring lists them. ->and(preg_split('/, (?:and )?/', $emails[2]))->toHaveCount($notices->count()) ->and($signals->all())->toBe(['SessionFingerprintChanged', 'RepeatedFactorFailures', 'SuccessAfterFailures']) ->and($risk[1])->toBe('three') diff --git a/tests/Feature/ThrottlingTest.php b/tests/Feature/ThrottlingTest.php index 1de63b8e..ce28554e 100644 --- a/tests/Feature/ThrottlingTest.php +++ b/tests/Feature/ThrottlingTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\AccountLocked as AccountLockedNotice; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; @@ -28,6 +27,7 @@ use Keyring\Models\Authenticator; use Keyring\Models\FailureCount; use Keyring\Models\SecurityEvent; +use Keyring\Notifications\AccountLocked as AccountLockedNotice; use Keyring\Pipeline\AccountLimit; use Keyring\Pipeline\Context; use Keyring\Pipeline\Steps\EnsureNotThrottled; @@ -868,14 +868,15 @@ function lockOut(int $times, string $email = 'taylor@example.com', string $passw $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'a brand new passphrase'])->assertRedirect('/dashboard'); }); - it('tells the owner it is locked and how to unlock it, once the app registers the notice', function () { + it('tells the owner it is locked and how to unlock it, unless the app turned the notice off', function () { Notification::fake(); + Keyring::notifications(['account_locked' => null]); lockOut(3); Notification::assertNothingSent(); completeReset($this->user); - sendNotifications(['account_locked']); + Keyring::notifications(['account_locked' => AccountLockedNotice::class]); $this->travel(2)->days(); lockOut(3, password: 'not this either'); diff --git a/tests/Feature/TweakableDefaultsTest.php b/tests/Feature/TweakableDefaultsTest.php index 1966d80d..945e2e5c 100644 --- a/tests/Feature/TweakableDefaultsTest.php +++ b/tests/Feature/TweakableDefaultsTest.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use App\Notifications\Keyring\VerificationCode; use Illuminate\Http\Request; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Route; @@ -21,6 +20,7 @@ use Keyring\KeyringManager; use Keyring\Models\Device; use Keyring\Models\SecurityEvent; +use Keyring\Notifications\VerificationCode; use Keyring\Pipeline\NameLimit; use Keyring\Sessions\Sessions; use Keyring\Support\Throttle; diff --git a/tests/Helpers.php b/tests/Helpers.php index 43025229..fcb0ed6a 100644 --- a/tests/Helpers.php +++ b/tests/Helpers.php @@ -87,8 +87,8 @@ function totpCode(string $secret, int $step = 0): string } /** - * Register the published notification for each type, or for every one, as - * an app's KeyringServiceProvider would. + * Turn on Keyring's own notification for each type, or for every one: the + * suspected clone, which starts off, and any a test turned off. * * @param list|null $types */ @@ -97,7 +97,7 @@ function sendNotifications(?array $types = null): void $types ??= KeyringManager::NOTIFICATIONS; Keyring\Facades\Keyring::notifications(array_combine($types, array_map( - fn (string $type) => 'App\\Notifications\\Keyring\\'.Str::studly($type), + fn (string $type) => 'Keyring\\Notifications\\'.Str::studly($type), $types, ))); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 1ef48ebd..21190c7f 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -66,13 +66,6 @@ protected function setUp(): void // Laravel's own listener for new users, which an app's event service // provider registers and testbench leaves out. Event::listen(Registered::class, SendEmailVerificationNotification::class); - - // And the emails it registers: the ones a flow needs, and four of the - // security notices keyring:install turns on. - sendNotifications([ - 'verification_code', 'confirm_email_change', 'email_change_notice', 'email_address_in_use', 'already_registered', - 'password_changed', 'authenticator_added', 'authenticator_removed', 'recovery_code_used', - ]); } protected function defineDatabaseMigrations(): void