# Security Log & Emails

Source: https://keyringauth.com/docs/0.x/rust/security-log-and-emails

## Introduction

Keyring writes a security log of what happens to your users' accounts, and emails them when something important changes, as the PHP package does. The log is the PHP package's table, with the same columns, entry types, severities and `meta`, so a log either side wrote reads on the other. The emails have the PHP package's subjects and wording.

## The Security Log

Keyring writes each entry as a row in `keyring_events`, from its own events, as the PHP package's `RecordSecurityEvents` does. It's on by default, through `security_log.enabled`, the PHP package's `Features::securityLog()`:

| Setting | Default |
|---|---|
| `security_log.enabled` | `true` |
| `security_log.keep_for` | 180 days |
| `security_log.context_key` | `trace_id` |
| `security_log.refusals`, `refusals_per` | 20, one hour |
| `security_log.alerts` | The PHP package's: `second_factor_failed`, `device_reported`, `email_change_reverted`, `clone_suspected`, `remember_me_reused` and `session_contested` |
| `security_log.unlisted` | Empty |

What a row holds, and what it never holds, is the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/security-log-and-emails#the-security-log) describe. Each entry is kept in a transaction of its own, a savepoint inside the caller's. The log never stops a sign in: if a write fails, Keyring reports the error, writes the entry to the application's log instead, and carries on. The one exception is `protection_bypassed`, which [`without_protection()`](https://keyringauth.com/docs/0.x/rust/protected-changes#bypassing-protection) won't go past.

To write entries of your own, `laravel_keyring::security_log::record()`, `record_or_fail()` and `record_refusal()` take an `Entry`:

```rust
use laravel_keyring::security_log::{self, Entry, Severity};

security_log::record(
    Entry::new("acme.api_token_issued")
        .user(&user)
        .meta("client", "billing-service")
        .severity(Severity::Notice),
)
.await;
```

### Without the Table

With `security_log.enabled` off, or for an entry the table won't take, each entry is a `tracing` event under the `keyring::security_log` target, with the PHP package's message (`Keyring: {type}`) and context, rather than a line on a log channel. There's no `security_log.channel`: route the target with your `tracing` subscriber. tracing has no `notice` or `critical`, so `notice` goes out at `INFO` and `critical` at `ERROR`, with the severity as a field.

### Request IDs

A request's entries share a `request_id`: your application's own, from laravel-rust's context under `security_log.context_key` (`trace_id`), or a UUID Keyring keeps hidden in the context. See the [PHP docs](https://keyringauth.com/docs/0.x/security-log-and-emails#request-ids).

### Times

Times are stored as the PHP package stores them with `app.timezone` at Laravel's default, UTC: `Y-m-d H:i:s`, whole seconds with no offset. IDs are lowercase ULIDs that go up within a millisecond, as Symfony's do, so the later of two entries has the greater ID.

### Refusals That Repeat

Refusals (`locked_out`, `rate_limited`, `access_refused`, and `factor_failed` for a name nobody has, or a password for an account without one) are written `security_log.refusals` times every `refusals_per` at most per account or address, the first one left out as `refusals_limited`, and a lock or full limiter once for its wait, as in the PHP package. A passkey alone that fails names its account, so its `factor_failed` is a refusal on the account too, where the PHP package writes every one.

### Refused Links

A reset link's token, a verification or "this wasn't me" link's signature, an email change's link, and an emailed code's sign-in link Keyring didn't make (`sign_in_link`, `token`) are logged as `link_refused` when they're refused, with `LinkRefused`, as in the PHP package. `http::ValidateSignature` logs a refused link of your own under the name you give it, as laravel-rust's routes have no names.

### Showing Recent Activity

`security_log::activity(&user, limit)` returns a user's most recent entries, newest first, as `Keyring::activity()`:

```rust
let activity: Vec<_> = laravel_keyring::security_log::activity(&user, 25)
    .await?
    .into_iter()
    .map(|event| {
        serde_json::json!({
            "type": event.event_type,
            "factor": event.factor,
            "ip": event.ip,
            "at": event.created_at.to_string(),
        })
    })
    .collect();
```

Each is a `SecurityEvent`, with the row's columns as fields (`event_type` for the `type` column). List types that are about a user without being something they did in `security_log.unlisted`, and `activity()` leaves them out; Keyring's own types are never left out. `impersonation.show_in_activity` off leaves the impersonation entries out. `security_log::unlisted_activity_types()` is the list `activity()` uses, for a query of your own, and `security_log::count()` counts a user's entries of a type.

### Pruning

`keyring:prune` deletes entries older than `security_log.keep_for`, 180 days by default. Keyring [schedules it daily](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#pruning). `user_deleted()` deletes a user's entries.

### What's Stored

Entries keep the request's address and user agent. To store less, set `record_ips_using`, the PHP package's `Keyring::recordIpsUsing()`: a plain function of the request that returns what to keep, or `None`. It applies to the log, the emails, the sessions and the devices. Rate limits always use the real address:

```rust
config.section_mut::<laravel_keyring::KeyringConfig>().record_ips_using = Some(|request| {
    // Keep the /24 only.
    let ip = request.ip().to_string();
    Some(ip.rsplit_once('.').map_or(ip.clone(), |(network, _)| format!("{network}.0")))
});
```

The table's addresses and user agents are the request's, which [Trusted Proxies](https://keyringauth.com/docs/0.x/rust/security#trusted-proxies) decides.

### Severity

`security_log::Severity` is the PHP package's: `Info`, `Notice`, `Warning` and `Critical`, as its [docs](https://keyringauth.com/docs/0.x/security-log-and-emails#severity) describe.

### Entry Types

The entry types are the PHP package's, with the same names and `meta`, as its [list](https://keyringauth.com/docs/0.x/security-log-and-emails#entry-types) describes.

## "Was This You?" Alerts

As in the PHP package: after a successful sign in, Keyring flashes `keyring.alerts` to the session, the unseen `security_log.alerts` entries, each `{ "type", "factor", "at", "ip" }`, for a browser the account had already used when they were logged, and marks them seen. A JSON sign in returns them as `alerts` on the `200` `authenticated` answer.

To read them yourself, `security_log::pull_alerts(&user, since)` returns the unseen alerts, newest first, and marks them seen. To show a banner, share them from your Inertia middleware:

```rust
let alerts = session.get::<serde_json::Value>("keyring.alerts").unwrap_or_else(|| serde_json::json!([]));

Ok(props! {
    keyringAlerts => alerts,
})
```

## Security Emails

Keyring's emails are a `notifications::SecurityNotice` queued to the user through laravel-rust's notifications, with the PHP package's subjects and wording. Your user implements laravel-rust's `ReceivesMail`, which says where they go. Run a queue worker, or use the `sync` queue connection.

Each kind can be turned off, or replaced with an email of your own, on `notifications`:

```rust
use laravel::mail::Message;
use laravel_keyring::KeyringConfig;
use laravel_keyring::notifications::NoticeKind;

let notifications = &mut config.section_mut::<KeyringConfig>().notifications;

// Not sent.
notifications.turn_off(NoticeKind::RecoveryCodeUsed);
// Sent, starting off as in the PHP package.
notifications.turn_on(NoticeKind::CloneSuspected);
// Yours instead of Keyring's, which also turns it on.
notifications.mail(NoticeKind::NewDevice, |notice| {
    notice.message().subject("New sign in to your Acme account")
});
```

`turn_off(kind)` and `turn_on(kind)` are `null` and listing a type in `Keyring::notifications()`, and `mail(kind, ...)` is a class of your own for it. `notifications.enabled(kind)` says whether a kind is sent. A replacement is always an email on the mail channel.

laravel-rust builds an email as it queues it, where Laravel builds it in the worker, so one that can't be built (an address the mailer won't take) is reported and the request carries on. An account gets each kind `limits.notices` times every `limits.notices_per` at most (5 an hour), and a user type that derives `MustVerifyEmail` gets none until the address is verified, but for `password_changed` after a reset, as in the PHP package.

### Email Types

The kinds are the PHP package's types, as `NoticeKind`: `NewDevice`, `PasswordChanged`, `AuthenticatorAdded`, `AuthenticatorRemoved`, `SecondFactorFailed`, `RecoveryCodeUsed`, `RecoveryCodesGenerated`, `AccountLocked`, `SuspiciousActivity`, `CloneSuspected` (which starts off), `EmailChanged` and `EmailChangeReverted`. When each is sent is in the [PHP table](https://keyringauth.com/docs/0.x/security-log-and-emails#email-types). `email_changed` and `email_change_reverted` also go to the other address, without the device and address.

The `SecurityNotice` has `kind`, `when` (the time as text, in UTC), `at`, `device`, `ip`, `name`, `remaining`, `reasons`, `url` and `contact`, and `subject()`, `intro()`, `action()`, `if_not_you()` and `message()`, Keyring's own email. The account-locked email has its reset button while password resets are on, and is sent in the background, off the refused sign in's answer.

### A Support Contact

Set `support_contact`, a URL or an address, and every email Keyring builds ends with it, as in the PHP package:

```rust
config.section_mut::<laravel_keyring::KeyringConfig>().support_contact = Some("https://example.com/support".to_owned());
```

`authenticators_url` is your sign-in methods page, which `authenticator_added` and `recovery_codes_generated` link to. To send notices to more than one address, return them from your user's `ReceivesMail`.

### Emails a Flow Needs

The emails a flow needs, and the reset and verification links, are Keyring's own plain-text and HTML emails, with the PHP package's wording and Laravel's for the two links, until you give one of your own. Each has a method on `notifications`, given a closure that takes what the email says and returns the message, where the PHP package takes a class in `Keyring::notifications()`, or `toMailUsing()` on Laravel's `ResetPassword` and `VerifyEmail`:

| Method | Given | What's in It |
|---|---|---|
| `reset_link()` | `ResetLink` | `url`, `token`, `address`, `minutes` (`passwords.expire`), and `user::<User>()` |
| `verification_link()` | `VerificationLink` | `url` (the signed link), `address`, `minutes` (`verification_expire`), and `user::<User>()` |
| `already_registered()` | `AlreadyRegistered` | `login_url`, and `reset_url` while password resets are on |
| `confirm_email_change()` | `ConfirmEmailChange` | `url`, `expires_at` |
| `email_change_notice()` | `EmailChangeNotice` | `email` (the new address, mostly hidden), `revert_url`, `confirm_url` when this address must confirm too, and `contact` |
| `email_address_in_use()` | `EmailAddressInUse` | Nothing |
| `verification_code()` | `VerificationCode` | `code`, `minutes`, `enrolling`, `contact`, and `url`, the [sign-in link](https://keyringauth.com/docs/0.x/rust/factors#signing-in-from-the-email), when email codes send one |

The types are in `laravel_keyring::notifications`, and each one's `message()` is Keyring's own email, to start from:

```rust
use laravel::mail::Message;
use laravel_keyring::KeyringConfig;

laravel::Application::configure().with_config(|config, _| {
    config
        .section_mut::<KeyringConfig>()
        .notifications
        // An email of your own.
        .reset_link(|link| {
            Message::new()
                .subject("Reset your Acme password")
                .text(format!("Reset it within {} minutes: {}", link.minutes, link.url))
        })
        // Keyring's, under a subject of your own.
        .already_registered(|email| email.message().subject("You already have an Acme account"));
});
```

Keyring adds the recipient's address, and a later call replaces an earlier one. The links, the counting, the throttles and what's stored stay as they are. The links are queued and the code goes out at once, as in the PHP package. There's no `createUrlUsing()`: to link to a page of your own, use the reset token, and Keyring still checks the link it stores. None of these can be turned off, as a PHP `null` only makes the flow refuse with `MissingNotification`: turn the flow off instead. `notifications.verification_code()` goes before `email_codes.mail_using`, which still works. Each link signs someone in, resets a password or moves an account, so keep it out of your logs: the types' `Debug` leaves the links and the token out.

### Your Own Templates

To write every security notice's email your own way, set `notifications.mail_using`, as `SecurityNotice::toMailUsing()`. It's a plain function of the notice, used for every kind you haven't given `mail()`:

```rust
use laravel::mail::Message;
use laravel_keyring::notifications::SecurityNotice;

config.section_mut::<laravel_keyring::KeyringConfig>().notifications.mail_using = Some(|notice: &SecurityNotice| {
    Message::new()
        .subject(notice.subject())
        .text(format!(
            "{}\n\nWhen: {}\nDevice: {}\n\n{}",
            notice.intro(),
            notice.when,
            notice.device.as_deref().unwrap_or("Unknown"),
            notice.if_not_you(),
        ))
});
```

Values such as `name`, `device` and `reasons` can contain what a user or browser sent, cut to one line of at most 500 characters. Escape them in HTML. `mail_using` doesn't reach the [emails a flow needs](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#emails-a-flow-needs).

### Slack, SMS and Other Channels

Not available: a replacement is always an email, on the mail channel, since one kind's email is a closure that returns a `Message` rather than a notification class. To reach another channel, [listen for the event](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#sending-something-else-entirely) behind the notice and send it yourself.

### Sending Something Else Entirely

Turn the kind off, and listen for the event behind it (see [Events](https://keyringauth.com/docs/0.x/rust/events)), as in the PHP package:

```rust
use laravel::event::Event;
use laravel_keyring::events::NewDeviceSignedIn;
use laravel_keyring::notifications::NoticeKind;

async fn tell_slack(event: Event<NewDeviceSignedIn<User>>) -> laravel::Result<()> {
    // event.user, event.device ...
    Ok(())
}

laravel::Application::configure()
    .with_config(|config, _| {
        config.section_mut::<laravel_keyring::KeyringConfig>().notifications.turn_off(NoticeKind::NewDevice);
    })
    .with_events(|events, _| {
        events.listen(tell_slack);
    });
```

## Laravel's Auth Events

Not available: laravel-rust has no `Failed`, `Lockout`, `PasswordReset`, `Registered` or `Verified` events, so Keyring dispatches its own alone, and listeners built for Laravel's won't hear them. See [Events](https://keyringauth.com/docs/0.x/rust/events).
