Account SecuritySecurity Log & Emails

Security Log & Emails

On this page

Introduction

Keyring writes a security log of what happens to your users' accounts, and it emails them when something important changes. This page covers reading the log, showing recent activity, the "was this you?" alerts, and the security emails and how to change them.

The Security Log

Keyring writes each entry as a Keyring\Models\SecurityEvent row in the keyring_events table. The log is on by default, through Features::securityLog(). Configure it in the security_log section of config/keyring.php:

PHP
'security_log' => [    'keep_for' => '180d',    'channel' => env('KEYRING_LOG_CHANNEL'),    'context_key' => 'trace_id',    'refusals' => 20,    'refusals_per' => '1h',    'alerts' => ['second_factor_failed', 'device_reported', 'email_change_reverted', 'clone_suspected', 'remember_me_reused', 'session_contested'],    'unlisted' => [],],

A row has a type, a severity, the user (authenticatable_type and authenticatable_id), a factor, a device_id, an ip, a user_agent, a request_id, meta, seen_at and created_at. The log never holds passwords, codes, tokens, signatures, session IDs or anything else from the request body.

While someone is impersonating a user, the requests are the impersonator's. So any entry written on the user's account in those requests has no IP address or user agent, and neither do the user's impersonation_started and impersonation_ended entries. The impersonator's own entries keep them.

The log never stops a sign in. If a write fails, Keyring reports the error, writes the entry to your application's log instead, and carries on. The one exception is protection_bypassed. If that entry can't be written, Keyring::withoutProtection() throws before it runs your callback, so a bypass is never unlogged.

Without the Table

Without Features::securityLog(), nothing is written to keyring_events. Each event becomes a line in your application's log instead, written as Keyring: {type} at the entry's severity. The context holds at (the time, with its offset), user (as {morph class}:{id}), factor, device_id, ip, user_agent, request_id and meta.

Set security_log.channel to the channel to use. Leave it empty for your default channel:

PHP
// config/logging.php'security' => ['driver' => 'daily', 'path' => storage_path('logs/security.log'), 'days' => 180],
Terminal
KEYRING_LOG_CHANNEL=security

The channel decides how long lines are kept and who can read them.

Warning

The "was this you?" alerts, Keyring::activity() and the RepeatedFactorFailures, SuccessAfterFailures and CredentialStuffing risk signals all read the table. Without it, they find nothing.

Request IDs

Every entry a request writes gets the same request_id, so you can read them together:

PHP
SecurityEvent::query()->where('request_id', $event->request_id)->oldest('id')->get();

The ID comes from Laravel's Context feature. If your app already sets one, such as trace_id, Keyring uses it:

PHP
use Illuminate\Support\Facades\Context;use Illuminate\Support\Str; // A middleware of yoursContext::add('trace_id', (string) Str::uuid());

Set security_log.context_key to your key. Your log lines and any queued job from the request then carry the same ID. Without one, Keyring makes a UUID and keeps it hidden. An ID over 64 characters is cut. Set the key to null to leave request_id empty.

Times

created_at is a plain timestamp in app.timezone, with no offset. Leave app.timezone as UTC, the Laravel default and what OWASP ASVS 5.0.0 (16.2.2) recommends. Lines in your application's log carry an offset, as at, instead.

Refusals That Repeat

Refused users can ask again as often as they like, so Keyring limits how often refusals are written:

  • A lock is logged when it starts. locked_out is written once per factor and IP address, until the lock's wait is over. rate_limited is written once per route, until that limiter has room again. Every refused request still dispatches its event, Lockout or RateLimited, so your listeners see each one.
  • Refusals are counted. locked_out, rate_limited, access_refused, enrollment_refused, authenticator_removal_refused, link_refused, verification_refused, impersonation_refused, and factor_failed for an unknown name are each written at most security_log.refusals times per refusals_per. The default is 20 an hour. The count is per account, or per IP address when no account is named.
  • The log says where it stopped. The first entry left out is replaced by one refusals_limited entry.

A failed factor for a real account isn't limited this way. The account's own rate limits bound it instead.

Set refusals to null to write every refusal. The counts live in the rate limiter's cache store.

The link_refused entry covers each emailed link Keyring checks:

link reason
email_change_confirm, email_change_revert token when the token was wrong. ended when the change is over (expired, cancelled, used or undone). unknown when there's no such change. Only pressing the page's button is logged.
password_reset token when the token wasn't sent to that address or has expired. The entry holds neither the token nor the address.
sign_in_link token when the link's token isn't one Keyring made. A link that has ended (used, replaced, expired) isn't logged, since mail scanners open links after they're used.
A signed route's name, such as verification.verify signature when the signature didn't match. expired when it matched but is out of date.

Signed links are checked by the keyring.signed middleware. It works like Laravel's signed middleware, with the refusal logged. To log refusals on a route of your own, add the middleware to it:

PHP
Route::get('/invitations/{invitation}', AcceptInvitation::class)->middleware('keyring.signed:relative')->name('invitations.accept');

Showing Recent Activity

Keyring::activity() returns a user's most recent entries, newest first. It takes an optional limit, which defaults to 25:

PHP
use Keyring\Facades\Keyring; return Inertia::render('settings/security', [    'activity' => Keyring::activity($request->user())->map(fn ($event) => [        'type' => $event->type,        'factor' => $event->factor,        'ip' => $event->ip,        'at' => $event->created_at->toIso8601String(),    ]),]);

Some entries are about a user without being something they did, such as a token a package issued to another app's server. List those types in security_log.unlisted, and Keyring::activity() leaves them out:

PHP
'security_log' => [    // ...    'unlisted' => ['acme.token_issued'],],

A package can add its own types when it boots:

PHP
config()->push('keyring.security_log.unlisted', 'acme.token_issued');

Start each type with the package's name so it can't clash with another. Your own service provider can push too, with config()->push(). Don't assign the option there, since that replaces what packages have pushed. Keep the option a list, even for one type. A string leaves nothing out, and the first package to push to it throws an error.

Keyring's own types are never left out, even if you list them. The impersonation entries are the exception. Keyring::activity() leaves out impersonation_started and impersonation_ended when impersonation.show_in_activity is false, and impersonation_refused is never hidden.

Unlisted entries still belong to the user. Only Keyring::activity() leaves them out. If you build your own activity page, add ->whereNotIn('type', Keyring::unlistedActivityTypes()) to the query. That's the list Keyring::activity() uses, including the two impersonation types when impersonation.show_in_activity is false.

Pruning

keyring:prune deletes entries older than security_log.keep_for, which is 180 days by default. Keyring schedules it daily.

When a user is force deleted, their entries go with them. A soft deleted user keeps theirs.

What's Stored

Entries keep the request's IP address and user agent. To store less, tell Keyring what to keep. Rate limits always use the real address, but the ip in security emails follows this too:

PHP
use Illuminate\Http\Request;use Symfony\Component\HttpFoundation\IpUtils; // The network, not the machine. Or return null to keep none.Keyring::recordIpsUsing(fn (Request $request) => IpUtils::anonymize((string) $request->ip()));

For everything Keyring keeps, see What Keyring Keeps.

Severity

Each entry has one of four severities, stored in the severity column as a Keyring\Enums\Severity case. They're PSR-3 log levels, so a log channel filters them with its usual level setting.

Severity Means
info Someone did what they were allowed to do.
notice How the account signs in has changed, or something is worth a look.
warning Something failed or was refused, or looks like someone else at work.
critical A sign-in method or a safeguard can't be relied on.

Severity::of() returns the severity of a type. Your own types are info unless you say otherwise:

PHP
use Keyring\Activity\SecurityLog;use Keyring\Enums\Severity; app(SecurityLog::class)->record('exported_data', $user, severity: Severity::Notice);

To watch the most serious entries, query for them, or send the log to a channel that raises alerts:

PHP
use Keyring\Enums\Severity;use Keyring\Models\SecurityEvent; SecurityEvent::query()->where('severity', Severity::Critical)->where('created_at', '>', now()->subDay())->get();

Entry Types

Type Severity When meta
signed_in info A login completed. factors
confirmed info A step-up completed. factors
factor_failed warning A factor failed.
second_factor_failed warning A factor failed after the password, or after another first step such as an identity provider sign in.
locked_out warning A rate limit started refusing an IP address for a factor. Logged once per lock, and not linked to a user. retry_after
rate_limited warning The form limiter refused one of Keyring's other routes. Logged once per route for each wait. limiter, route, retry_after
account_locked warning Failed attempts got the password or a passkey refused until a password reset.
signed_out info The user signed out.
authenticator_added, authenticator_removed notice A sign-in method was added or removed. name
recovery_codes_generated info New recovery codes were made.
recovery_code_used notice A recovery code was used. remaining
new_device notice A sign in from a new device. device
device_revoked info A device was signed out. device
device_reported warning A device was signed out from the "this wasn't me" link. device
sessions_revoked info Sessions were signed out. count
session_ended info Keyring signed a session out on its own. reason: revoked, expired, idle, other_user, reused, risk or not_allowed
session_resumed info "Remember me" signed a browser back in. Nothing was proved.
remember_me_reused warning A "remember me" cookie was used twice, and the session ended for both browsers. device
session_contested warning Two requests holding one session both moved it, so the session ended for both. device
email_change_requested info An email change was requested.
email_changed notice An email change was applied.
email_change_reverted warning An email change was undone.
password_changed notice The password was changed.
password_reset notice A reset completed. It cleared the account's sign-in lockouts. sign_in_locks_cleared
protection_bypassed warning Keyring::withoutProtection was used, by the signed-in user. reason
clone_suspected critical A passkey or security key's counter went backwards. name
risk_step_up, risk_reauthenticate, risk_notified, risk_password_change notice A risk action did something. risk_password_change holds the user until they choose a new password. checkpoint, score, reasons
risk_denied, risk_locked, risk_revoked_sessions warning A risk action refused, locked or signed out. checkpoint, score, reasons
access_refused warning A user asked for an authenticator, device or session that isn't theirs or doesn't exist. Also written when they open another account's verification link. resource (authenticator, device, session or email_verification), id (cut to 64 characters; a session's handle, never its registry ID)
enrollment_refused warning A sign-in method wasn't added. reason: invalid, not_allowed (the account may not add one yet), frozen (see frozen sign-in methods), or password (the password was wrong)
authenticator_removal_refused warning A sign-in method was kept, because removing it would break the user's sign-in policy or the methods are frozen. name, reason (last_factor or frozen)
link_refused warning An emailed link was refused. link and reason, below
verification_refused critical A sign in or step-up was refused at the end, because a mandatory step hadn't run. skipped, the steps
refusals_limited warning Entries of a refused kind stopped being written for a while. See Refusals That Repeat. type, the entry type left out
impersonation_started notice Someone signed in as another user. Logged on both accounts. See Impersonation. impersonator and user (the two IDs), role (impersonator or impersonated)
impersonation_ended info An impersonation ended. Logged on both accounts, or on the other alone once one is deleted. impersonator, user, role, reason (stopped, expired, revoked, impersonator_session_ended, lost, signed_out or failed), returned
impersonation_refused warning A start of an impersonation was refused. Logged on the impersonator's account. reason (an ImpersonationRefusal value, such as not_allowed, or not_found for an ID nobody has), user (the ID asked for, cut to 64 characters)

A wrong password for an unknown account is logged as factor_failed, with no user. Form validation errors aren't logged.

"Was This You?" Alerts

After a successful sign in, Keyring flashes keyring.alerts to the session. These are unseen log entries worth asking the user about.

JSON
[  { "type": "second_factor_failed", "factor": "totp", "at": "2026-11-08T09:12:00+00:00", "ip": "198.51.100.4" }]

With Features::devices() on, a browser only gets alerts for entries logged after the account first used that browser. A browser first used after an alert was logged doesn't get it either, since it could belong to whoever caused the event.

The types that become alerts are listed in security_log.alerts. Any entry type can be added. A second_factor_failed alert is the classic sign that someone else knows the password.

To read alerts yourself, call pullAlerts(). It returns the unseen alerts, newest first, and marks them seen, so each comes back once. Pass since: to get only the entries logged after a time:

PHP
use Keyring\Activity\SecurityLog; $alerts = app(SecurityLog::class)->pullAlerts($request->user());

A JSON sign in returns them too, as alerts on the 200 authenticated answer. The list is empty when there's nothing to ask about. Alerts are also flashed for JSON requests, so a page loaded afterwards can read them. A frontend Laravel doesn't serve should show the ones in the answer, and not also read the flash, or it'll show them twice. See Where Each Answer Goes.

To show a banner, share the alerts through your Inertia middleware:

PHP
// app/Http/Middleware/HandleInertiaRequests.phppublic function share(Request $request): array{    return [        ...parent::share($request),        'keyringAlerts' => fn () => $request->session()->get('keyring.alerts', []),    ];}

Security Emails

Keyring's emails are ordinary Laravel notifications in the Keyring\Notifications namespace, sent through your mailer. Nothing to publish or register. To replace one, or turn it off, pass a class or null to Keyring::notifications(), usually from your KeyringServiceProvider:

PHP
use Keyring\Notifications\CloneSuspected; Keyring::notifications([    '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]);

Types you leave out keep Keyring's notification. Every security notice starts on except clone_suspected, which you turn on by listing it as above. A notice is only sent when its event happens, so these need their feature on:

  • 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().

Calling Keyring::notifications() again adds to earlier calls. An unknown type throws an InvalidArgumentException.

An account gets each kind of notice at most limits.notices times every limits.notices_per (5 an hour by default), so nobody can make your app mail one person without end. The security log records every event either way.

A MustVerifyEmail user gets no security emails until the address is verified. The one exception is password_changed after a reset, since the reset link went to that address.

To reword an email, translate its strings. Each goes through __, so a line in lang/en.json replaces it. To restyle them all, publish Laravel's mail template with php artisan vendor:publish --tag=laravel-mail.

Email Types

The security notices, each sent to the user. Each notice receives the named constructor arguments in the Passes column, built through the container.

Type Sent When Passes
new_device A sign in from a new device. url, the "this wasn't me" link. None for a "remember me" browser on an account at devices.limit.
password_changed The password was changed or reset.
authenticator_added A sign-in method was added. name, and url when authenticators_url is set
authenticator_removed A sign-in method was removed. name
second_factor_failed The password, or an identity provider sign in, was right, but the next factor failed. name, the first step's method, when it wasn't the password
recovery_code_used A recovery code was used. remaining
recovery_codes_generated A new set of recovery codes was made, including the set that comes with a first extra sign-in method. url, when authenticators_url is set
account_locked Failed attempts got the password or a passkey refused until a reset. url (the password.request route, when the app has one), device, ip
suspicious_activity A risk action with notify() ran. reasons
clone_suspected A passkey or security key looked cloned. name
email_changed An email change was applied. Sent to both addresses.
email_change_reverted An email change was undone.

Every notice also gets when (the time as text, in your app's timezone), at (the same moment as a date, for formatting in the user's timezone), device, ip and contact, your support contact. The copy of email_change_reverted sent to the new address leaves out device and ip, since that address may belong to whoever took over the account.

Most notices tell the user who didn't do it to change their password and check their sign-in methods. authenticator_added and recovery_codes_generated also say to sign out everywhere, since someone else may be signed in. With authenticators_url set, both have a "Review your sign-in methods" button. The link is built from APP_URL, carries no token, and does nothing until the owner is signed in on that page.

Values such as name, device and reasons can contain what a user or browser sent. Keyring cuts each to one line of at most 500 characters. Its own emails pass them through Keyring\Support\MailText::plain, since Laravel reads mail lines as Markdown, and a name could otherwise add a link. Do the same in your own MailMessage lines, and escape them anywhere else you show them.

A Support Contact

NIST SP 800-63B-4 (Sec. 4.6) asks that a notice tell a recipient who says it wasn't them how to get help. Keyring can't know your support team, so set it:

PHP
// config/keyring.php'support_contact' => 'https://example.com/support',   // or 'support@example.com'

Every notification Keyring builds gets it as contact, flow emails included. The security notices, VerificationCode and EmailChangeNotice end with "If this wasn't you and you need help, contact us", followed by the contact, as a link when it's a URL or an email address. The default is null, which leaves the line out. Set it before you say your notices follow NIST.

Section 4.6 also asks for notices to go to every address an account has, at least two. Keyring only knows the email attribute. To send to more, return them from your user model:

PHP
// app/Models/User.phppublic function routeNotificationForMail(): array{    return array_filter([$this->email, $this->backup_email]);}

This also changes where Laravel's own mail goes. Keeping and verifying a second address is up to your app. See Known Limitations. The OWASP ASVS page lists what each level expects.

Emails a Flow Needs

Five emails are part of a flow, not notices, and the flow can't work without them. Each is built the same way, with contact included. If you set one to null, the flow throws a Keyring\Exceptions\MissingNotification that names the type:

Type Sent To Passes
verification_code The user, with an email code. code, minutes, enrolling (true when it confirms a new email code sign-in method), and url, the sign-in link, when the factor sends one
confirm_email_change The new address. url, expiresAt
email_change_notice The current address. email (the new address, mostly hidden), revertUrl, and confirmUrl when this address must confirm too
email_address_in_use An address someone tried to change to, when it already has an account.
already_registered An address someone tried to register with, when it already has an account. loginUrl, and resetUrl when password resets are on

Keyring's verification_code puts the code in its body as one run of digits beside the word "code", and not in its subject, so mail apps can offer to copy it without the code reaching mail logs. A replacement should do the same (see Email Codes). One that takes url should show it as a button beside the code, and say it only signs in from the browser where the sign in started.

The 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 saving if one of its three emails is off, and registration is refused without already_registered, unless registration.reveal_taken is on.

The email change emails, already_registered, and any copy sent to an address the account no longer has go to a bare address. Their $notifiable is an AnonymousNotifiable, so keep via and toMail in your own classes from reading user attributes.

Password resets and verification use Laravel's own notifications, and you change them the usual Laravel way. See Resetting the Password.

Your Own Templates

Keyring builds each notice with the arguments above, then sends it. To write every security notice's email from your own views, such as Maizzle templates, give SecurityNotice a callback in your KeyringServiceProvider. It receives the notice and the person 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. The callback may return a Mailable instead. Emails With Maizzle walks through this approach. toMailUsing doesn't reach the emails a flow needs.

Keyring's notices extend the abstract Keyring\Notifications\SecurityNotice class. It defines subject, intro, and action when it has a button, and may override ifNotYou. Notices are queued once any open database transaction commits, so a rolled-back change is never announced.

For a single notice, extend Keyring's class and register yours:

PHP
namespace App\Notifications; use Illuminate\Notifications\Messages\MailMessage;use Keyring\Notifications\PasswordChanged as KeyringPasswordChanged; class PasswordChanged extends KeyringPasswordChanged{    public function toMail(object $notifiable): MailMessage    {        return (new MailMessage)            ->subject($this->subject())            ->view('emails.password-changed', ['when' => $this->when, 'device' => $this->device, 'ip' => $this->ip]);    }}
PHP
Keyring::notifications(['password_changed' => \App\Notifications\PasswordChanged::class]);

Any class whose constructor takes the arguments it wants will do. It needn't extend Keyring's.

Slack, SMS and Other Channels

A notification can go to any channel Laravel supports. Choose the channels in via, per user if you like, and add a method for each:

PHP
namespace App\Notifications; use Illuminate\Notifications\Slack\SlackMessage;use Keyring\Notifications\NewDevice as KeyringNewDevice; class NewDevice extends KeyringNewDevice{    public function via(object $notifiable): array    {        return $notifiable->slack_webhook ? ['mail', 'slack'] : ['mail'];    }     public function toSlack(object $notifiable): SlackMessage    {        // 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));    }}

Register it with Keyring::notifications(['new_device' => \App\Notifications\NewDevice::class]). Slack needs Laravel's laravel/slack-notification-channel package. For database or broadcast, add a toArray method.

Sending Something Else Entirely

Keyring dispatches an event for every notice, whether or not it's on. To do something other than email, set the type to null and listen for the event.

Laravel's Auth Events

Keyring also dispatches Laravel's Illuminate\Auth\Events\Failed, Lockout and PasswordReset events, so your existing listeners keep working. See Events.