Security Log & Emails
On this page
- Introduction
- The Security Log
- Without the Table
- Request IDs
- Times
- Refusals That Repeat
- Refused Links
- Showing Recent Activity
- Pruning
- What's Stored
- Severity
- Entry Types
- "Was This You?" Alerts
- Security Emails
- Email Types
- A Support Contact
- Emails a Flow Needs
- Your Own Templates
- Slack, SMS and Other Channels
- Sending Something Else Entirely
- Laravel's Auth Events
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 Features.SecurityLog, the PHP package's Features::securityLog():
| Setting | Default |
|---|---|
Features.SecurityLog |
true |
SecurityLog.ContextKey |
trace_id |
SecurityLog.Refusals, RefusalsPer |
20, one hour |
SecurityLog.Alerts |
The PHP package's: second_factor_failed, device_reported, email_change_reverted, clone_suspected, remember_me_reused and session_contested |
Set these one field at a time. Assigning a whole struct, such as cfg.Features = keyring.Features{Devices: true}, leaves SecurityLog false and turns the table off, and cfg.SecurityLog = keyring.SecurityLog{...} leaves Alerts empty and turns the alerts off.
What a row holds, and what it never holds, is the PHP package's, as its docs describe. Each entry is written in a savepoint of its own inside the caller's transaction. 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 WithoutProtection won't go past.
To write entries of your own, Keyring.Record, RecordOrFail and RecordRefusal take an Entry:
k := keyring.From[models.User](ctx) k.Record(ctx, keyring.Entry[models.User]{ Type: "acme.api_token_issued", User: user, Meta: keyring.Meta{{Key: "client", Value: "billing-service"}}, Severity: keyring.SeverityNotice,})Record returns the row the table kept, or nil. RecordOrFail returns the error of a write that failed, for an entry that mustn't go unlogged. RecordRefusal(ctx, entry, once, wait) counts the entry as a refusal. Meta keeps its fields in the order given, as a PHP array does, and is stored as the JSON PHP's json_encode() writes.
Without the Table
With Features.SecurityLog off, or for an entry the table won't take, each entry goes to the application's log: slog.Default(), which Laravel Go makes the application's logger, under a keyring group, with the PHP package's message (Keyring: {type}) and context. There's no security_log.channel, as Laravel Go has no named log channels a package can write to. slog has no notice or critical, so notice goes out at INFO and critical at ERROR, with the severity as a field.
While someone is impersonating a user, the requests are the impersonator's, so the user's own impersonation_started and impersonation_ended entries, and any other entry written on the user's account in those requests, have no IP address or user agent, as in the PHP package. The impersonator's own entries keep them.
Request IDs
A request's entries share a request_id: your application's own, from the log context under SecurityLog.ContextKey (trace_id, set with Laravel Go's log.With or log.WithHidden), or a UUID Keyring makes and keeps hidden in the request's context under keyring_request_id. Keyring notes every request in global middleware, so entries written from any route carry it. An empty ContextKey writes no request IDs, as the PHP package's null. See the PHP docs.
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. A PHP application sharing the database with another app.timezone would disagree on alert times. 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, impersonation_refused, and factor_failed for a name nobody has, or a password for an account without one) are written SecurityLog.Refusals times every RefusalsPer 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. See Differences From PHP.
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 are logged as link_refused when they're refused, with LinkRefused, as in the PHP package. The event's Link is the signed link's route name, such as keyring.devices.report, or password_reset, email_change_confirm, email_change_revert or sign_in_link, and its Reason says why. A sign-in link is logged with token only when its token isn't one Keyring made: one that has ended (used, replaced, expired) isn't, since mail scanners open links after they're used.
Showing Recent Activity
There's no Keyring::activity() yet. Read a user's most recent entries from keyring_events yourself, newest first. SecurityEvent is a row of the table, with db tags for each column:
events, err := db.Select[keyring.SecurityEvent](ctx, `select * from keyring_events where authenticatable_type = ? and authenticatable_id = ? order by id desc limit 25`, keyring.From[models.User](ctx).Config().AuthenticatableType, user.ID)Type is the type column, Factor, IP and Meta are pointers for the nullable columns, and Meta is the JSON as stored. Leave out impersonation_started and impersonation_ended if you turn Impersonation.ShowInActivity off, and any type of your own that's about a user without being something they did, in the query. Keyring.CountEntries(ctx, user, type, within, since) counts a user's entries of a type, and Keyring.AccountsFrom(r, type, within, except) counts the accounts that had entries of a type from the request's address, as the PHP package's count() and accountsFrom().
Pruning
keyring:prune deletes entries older than SecurityLog.KeepFor, 180 days by default. Zero is 180 days too, so a SecurityLog set whole doesn't delete the log. Keyring schedules it daily.
What's Stored
Entries keep the request's address and user agent, cut to one line of at most 500 characters as the PHP package's UserAgent::from cuts it. There's no recordIpsUsing() yet: the address kept is always r.IP(), in the log, the emails, the sessions and the devices. See Differences From PHP.
The table's addresses and user agents are the request's, which Trusted Proxies decides.
Severity
keyring.Severity is the PHP package's: SeverityInfo, SeverityNotice, SeverityWarning and SeverityCritical, the PSR-3 levels the column keeps, as its docs describe. keyring.SeverityOf(type) is the severity a type gets when an entry doesn't give one. A severity that isn't one of the four is the type's too.
Entry Types
The entry types are the PHP package's, with the same names and meta, as its list describes. keyring.SecurityLogTypes lists them. Any other type is your application's own.
"Was This You?" Alerts
As in the PHP package: after a successful sign in, Keyring flashes keyring.alerts to the session, the unseen SecurityLog.Alerts entries, each a keyring.Alert ({ "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.
An entry is marked seen only if it still wasn't, so two sign ins at once never both show the same alert. The PHP package can show it to both. See Differences From PHP.
To read them yourself, Keyring.PullAlerts(ctx, user, since) returns the unseen alerts, newest first, and marks them seen. To show a banner, share them from your Inertia middleware:
m.Web.Append(inertia.Middleware{ Share: func(r *web.Request) (inertia.Props, error) { alerts := r.Session().Get("keyring.alerts") if alerts == nil { alerts = []keyring.Alert{} } return inertia.Props{"keyringAlerts": alerts}, nil },})Security Emails
Keyring's emails are a keyring.SecurityNotice, a mail.Mailable, queued to the user with Laravel Go's mailer once any open transaction commits, with the PHP package's subjects and wording. Your user type implements mail.Recipient, whose MailAddress() says where they go. Without it, Keyring sends to the user's Email field. Laravel Go uses the database queue whenever DATABASE_URL is set, so run a queue worker, or set QUEUE_CONNECTION=sync, or nothing is sent.
Each type can be turned off with Notifications.Off, or every type replaced with an email of your own with Notifications.Mail:
keyring.New[models.User](func(cfg *keyring.Config) { // Not sent. cfg.Notifications.Off = []string{"new_device"}})Off is the PHP package's null for a type, and Register refuses a type the PHP package doesn't have. An email that can't be built or queued is reported, and the request carries on. An account gets each type Limits.Notices times every Limits.NoticesPer at most (5 an hour). With Features.EmailVerification on, a user gets none until their address is verified, but for password_changed after a reset, as in the PHP package. The emails have the PHP package's lines, without Laravel's notification layout, which Laravel Go hasn't got.
Email Types
The types are the PHP package's names. Keyring for Go sends new_device, password_changed, authenticator_added, authenticator_removed, recovery_codes_generated, suspicious_activity, email_changed and email_change_reverted. When each is sent is in the PHP table. email_changed and email_change_reverted also go to the other address, without the device and address.
second_factor_failed, recovery_code_used, account_locked and clone_suspected are accepted in Off but aren't sent yet. See Differences From PHP.
The SecurityNotice has Type, When (the time as text, in UTC), At, Device, IP, URL, Contact, Name and Reasons, and Subject(), Intro(), Action(), IfNotYou() and Build(), Keyring's own email.
A Support Contact
Set SupportContact, a URL or an address, and every security email ends with it, as in the PHP package:
cfg.SupportContact = "https://example.com/support"AuthenticatorsURL is your sign-in methods page, which authenticator_added and recovery_codes_generated link to. To send notices to another address, return it from your user's MailAddress().
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 your own. Where the PHP package takes a class for each in Keyring::notifications(), or toMailUsing() on Laravel's ResetPassword and VerifyEmail, Keyring for Go takes one function, Notifications.AccountMail, given a keyring.AccountEmail. Its Type says which:
Type |
What's in It |
|---|---|
reset_password |
URL, Token, Minutes (Passwords.ResetLinkFor) |
verify_email |
URL (the signed link), Minutes (VerificationLinkFor) |
already_registered |
URL (the login page), and ResetURL while password resets are on |
confirm_email_change |
URL, ExpiresAt, ExpiresIn |
email_change_notice |
Email (the new address, mostly hidden), RevertURL, URL when this address must confirm too, and Contact |
email_address_in_use |
Nothing |
The code an emailed code sends is a keyring.VerificationCode, given to EmailCodes.Mail instead. It has Code, Minutes, Enrolling, Contact, and URL, the sign-in link when emailed codes send one, else empty.
Keyring's VerificationCode puts the code in its body as one run of digits beside the word "code" (Your verification code is 48291374), 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. One that uses URL should show it as a button beside the code, and say it only signs in from the browser where the sign in started.
Build() on each is Keyring's own email, to start from:
cfg.Notifications.AccountMail = func(ctx context.Context, email keyring.AccountEmail) mail.Mailable { switch email.Type { case "reset_password": // An email of your own. return mail.Message{ Subject: "Reset your Acme password", Text: fmt.Sprintf("Reset it within %d minutes: %s", email.Minutes, email.URL), } case "already_registered": // Keyring's, under a subject of your own. message := email.Build() message.Subject = "You already have an Acme account" return message } return email}Don't set a recipient: Keyring addresses the email. The links, the counting, the throttles and what's stored stay as they are. These emails aren't queued, as Laravel doesn't queue them: they're sent with the mailer off the request's goroutine, never waited on for the answer, so no link or reset token is kept in the jobs table. The code goes out in the request, as in the PHP package. To link to a page of your own, use the reset Token: the page posts it back to POST /reset-password with the address. None of these can be turned off while their flow is on: Register refuses Off listing already_registered where registration hides addresses, or the email change emails with email changes on. Turn the flow off instead. Each link signs someone in, resets a password or moves an account, so keep it out of your logs. VerificationCode never prints its code.
Your Own Templates
To write every security notice's email your own way, set Notifications.Mail, as SecurityNotice::toMailUsing(). It's called for every type:
cfg.Notifications.Mail = func(ctx context.Context, notice keyring.SecurityNotice) mail.Mailable { device := notice.Device if device == "" { device = "Unknown" } return mail.Message{ Subject: notice.Subject(), Text: fmt.Sprintf("%s\n\nWhen: %s\nDevice: %s\n\n%s", notice.Intro(), notice.When, device, notice.IfNotYou()), }}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, as Laravel Go's views do. Notifications.Mail doesn't reach the emails a flow needs.
Slack, SMS and Other Channels
Not available: a replacement is always an email, since Notifications.Mail returns a mail.Mailable. To reach another channel, listen for the event behind the notice and send it yourself.
Sending Something Else Entirely
Turn the type off, and listen for the event behind it (see Events), as in the PHP package:
laravel.Options{ Packages: []laravel.Package{ keyring.New[models.User](func(cfg *keyring.Config) { cfg.Notifications.Off = []string{"new_device"} }), }, Listeners: []laravel.Listener{ laravel.Listen(func(ctx context.Context, e keyring.NewDeviceSignedIn[models.User]) error { // e.User, e.DeviceID, e.DeviceName, e.DeviceLocation ... return nil }), },}Laravel's Auth Events
Laravel Go's auth dispatches no events, so there's no Failed, Lockout, Login or Logout to listen to. Keyring dispatches its own instead, and its own Registered, Verified and PasswordReset, named after Laravel's but in the keyring package. Listeners built for Laravel's won't hear them. See Events.