Account SecurityDevices & Sessions

Devices & Sessions

On this page

Introduction

Keyring keeps a record of every signed-in session in its own registry, keyring_sessions, and, with devices on, of every browser in keyring_devices, as the PHP package does. The rows are the PHP package's, so a PHP and a Go application sharing a database see each other's sessions and devices, and a user can end a session the other side started.

Devices

Devices are the PHP package's DeviceManager, behind Features.Devices, off by default as in the PHP package's config:

Go
cfg.Features.Devices = true

A sign in gives the browser the known_device cookie, holding a 40-character token the table keeps as its SHA-256. A browser the account hasn't signed in from gets a device and a token of Keyring's own making, never one it sent. A sign in that proved a second factor gets a new token too, so a copy of the cookie made before carries nothing. Devices.Limit (50) devices an account, a new one taking the place of the one seen longest ago. Zero is no limit. With devices off, no device is recorded or found, and their routes aren't there.

Trusted Devices

As in the PHP package: "trust": true with the password, or with any answer on the challenge page, marks the device trusted for Devices.TrustFor (30 days) once the sign in proves two factors, and the challenge page's canTrustDevice says whether answering would earn it. It's never earned on the confirm page.

Trust does nothing alone. A policy reads it from the attempt's Device(), nil for a new browser, and answering keyring.AAL1.Requirement() for a trusted one skips the second factor there:

Go
k.Require(func(ctx context.Context, user *models.User, attempt keyring.Attempt) keyring.Requirement {	if device := attempt.Device(); device != nil && device.IsTrusted(ctx) {		return keyring.AAL1.Requirement()	} 	return keyring.AAL2.Requirement().IfEnrolled()})

A fresh verification asks the policy about a browser nothing is known of too, so trust never lowers it. Signing out everywhere else, a new password and taking an authenticator off stop trusting devices.

New Device Sign Ins

A sign in from a browser the account hasn't used dispatches NewDeviceSignedIn, and sends the new_device security email with its "this wasn't me" button. The email goes through the queue once the transaction commits, as the PHP package's ShouldQueueAfterCommit: run a queue worker, or set QUEUE_CONNECTION=sync. Laravel Go uses the database queue whenever DATABASE_URL is set, so an application without a worker sends nothing.

Where Devices.Limit leaves no room for a "remember me" sign in, UnrecordedDeviceSignedIn is dispatched instead.

The new-device email's button is a link to /devices/{device}/report, signed relative to the site as Laravel signs it, for Devices.ReportLinkFor (7 days), so a link either side sends opens on the other. It starts at LinkRoot, which is APP_URL unless you set it, never the request's host. GET answers the device-report page and changes nothing. Its button POSTs expires and signature in the body, and signs the device out whoever is signed in: its sessions end (device_reported), it stops being trusted, its owner gets a new remember token, and DeviceRevoked says so, with Reported true. A link that's refused is LinkRefused and a 403.

There's no revokeUrl() on the event: the email makes the link itself.

Locations

Devices.Locator takes a keyring.LocatesIPs, as the PHP package's devices.locator. keyring.CloudflareLocator() reads Cloudflare's headers, and a HeaderLocator reads headers of your own:

Go
cfg.Devices.Locator = keyring.CloudflareLocator() cfg.Devices.Locator = keyring.HeaderLocator{Headers: []keyring.LocationHeader{	{Field: "country", Header: "X-Country-Code"},}}

Warning

Anyone can send these headers. Only use HeaderLocator when every request reaches your application through the proxy that sets them, and the origin can't be reached directly. On Cloudflare, CF-IPCountry is always sent, but the city, region and coordinates only with the "Add visitor location headers" Managed Transform turned on.

A locator of your own implements LocatesIPs, whose Locate(r *web.Request) (keyring.Location, error) gives a request's country, region, city, latitude and longitude as far as it knows them, in a keyring.Location:

Go
type Locator struct{} func (Locator) Locate(r *web.Request) (keyring.Location, error) {	country, err := lookUpCountry(r.IP()) // your GeoIP database or API	if err != nil || country == "" {		return nil, err	} 	return keyring.Location{{Key: "country", Value: country}}, nil}

It's asked once per request, so it may call an API. An error is reported, and the location is unknown for that request. A sign in keeps where the request was on its device, which GET /user/devices lists and description names ("near London"). A risk signal reads the location from its assessment.

Device Names

Devices.Describe names a browser from its user agent your own way, as Keyring::describeDevicesUsing(), wherever Keyring names one (a device, the sessions list, the security log, the security emails and SessionFingerprintChanged). The contract app names its own client and falls back on Keyring's reading, useragent.Describe:

Go
import "keyringauth.com/go/useragent" cfg.Devices.Describe = func(agent string) string {	if strings.Contains(agent, "AcmeApp/") {		return "The Acme app"	} 	return useragent.Describe(agent)}

Return "" for one it can't name.

Your Own Device Model

Not available: there are no Eloquent models, so there's no useDeviceModel(). Devices are rows in keyring_devices, and an event or a policy sees one as a keyring.Device (ID, Name, Location, TrustedUntil, with Description() and IsTrusted(ctx)). k.FindDevice(r, user) is the device of the browser that sent r. See Differences From PHP.

Listing and Revoking Devices

GET /user/devices lists the user's devices that haven't been signed out, most recently seen first, each { "id", "name", "description", "ip", "location", "lastActiveAt", "trusted", "current", "sessions" }. DELETE /user/devices/{device} signs one out, behind ChangesMiddleware: its sessions end (device_revoked), it stops being trusted, the user gets a new remember token, and DeviceRevoked says so. Signing out this browser's device answers device-revoked with page login. Someone else's device, one signed out, or one that never existed is a 404 ({"message":"Not Found"}, where the PHP package names its model) and AccessRefused. DELETE /user/devices signs out everywhere else, as DELETE /user/sessions does.

Listing and Ending Sessions

GET /user/sessions lists the user's sessions as the PHP package does, most recently active first, each by its handle (the PHP package's keyed hash of the record it started on), with name (its browser and platform), ip, device, remembered, signedInAt, lastActiveAt, expiresAt, current, impersonated and impersonator. A session someone is impersonating the user in has no name, address or device, and names who by impersonator.name. See The Sessions List.

DELETE /user/sessions/{session} ends one by its handle (200 session-revoked; 404 for someone else's, one that has ended, or anything not shaped like a handle; ending this browser's is signing out, a 204). DELETE /user/sessions ends every other one (200 sessions-revoked), which also gives the user a new remember token, stops trusting their devices, stops their browsers counting as known until each signs in again, cancels a waiting email change, and moves this browser to a new session ID and record. Both are behind ChangesMiddleware, and DELETE /user/sessions behind the keyring-session-changes limit: Limits.SessionChanges (six) a minute from one session and Limits.SessionChangesPerUser (thirty) from all the user's together.

Laravel Go has no way to destroy another browser's session by its ID, so ending one ends its Keyring record, and AuthenticateSession signs that browser out on its next request. Its session data stays in the store until it expires.

Keyring for Go has no public API yet to list or end sessions from your own code, as the PHP package's Sessions and SessionRegistry do. See Differences From PHP.

Is It Still Signed In?

Not available yet. The PHP package's Sessions::stillSignedIn() has no Go counterpart. See Differences From PHP.

Hearing About Ended Sessions

As in the PHP package's AnnouncingSessionRegistry: every record that ends dispatches RegisteredSessionEnded, with its Handle and Handles, UserID, UserType, Guard, DeviceID, EndedAt and Reason. A record that moved to a new one isn't announced: its session carried on there. A sign out of everyone (keyring:sign-out --all) dispatches one EveryoneSignedOut in place of a RegisteredSessionEnded for each session. See Events.

A listener that fails is reported and stops nothing. The record counts a failed try and waits five minutes, then twice as long each time, for the sweep to try again, which gives up after a day.

A session that ends is announced straight away, or, when it ended while the user's sessions were locked, once the lock is let go, so no listener runs under it.

Sweeping Ended Sessions

keyring:sweep ends the sessions that timed out with no request to end them (expired or idle), and announces again those whose announcement was lost, Sessions.SweepLimit (1000, at most 10,000) of each a run. Keyring schedules it every Sessions.SweepEvery once that's set:

Go
cfg.Sessions.SweepEvery = 5 * time.Minute

Under a minute is a minute, over 12 hours is 12 hours, and zero is off. The sweep warns of an interval over 12 hours each time it runs, and logs it once a day. It runs on one server, with an overlap lock of twice the interval, at least ten minutes and at most six hours. With it set, every session that ends is announced at least once. A session that ended in the last five minutes is left for the next run, in case it's still being announced, and one still unannounced a day after it ended is given up on. Zero Sessions.SweepLimit is 1000.

Remember Me

"remember": true with the password (or a passkey) signs in with Laravel Go's remember cookie, records the session as remembered, and gives the browser remembered_session, naming the session's record for as long as it lasts. The guard's cookie is cut to Sessions.Absolute, as the PHP package does, from Laravel Go's 400 days. When the guard's cookie signs the browser back in, Keyring's says which session it carries on: one still good moves to a new record, at no level, and SessionResumed says so. A session that ended, timed out (Sessions.RememberIdle, 14 days) or ends with its level isn't brought back, nor is one with no cookie of Keyring's.

Laravel Go doesn't say when its guard signed a browser in from its cookie, so Keyring tells by the session ID changing. A session your application signs in itself with auth.Login(r, user, true) gets Keyring's cookie too, and its record is marked remembered once the request is done.

Signing out a browser on its own, as when its session ends, keeps the user's remember token, as the PHP package's logoutCurrentDevice() does, so the user's other remembered browsers stay. Only POST /logout uses auth.Logout, which gives the user a new token and so stops "remember me" in their other browsers too, but on a browser that's impersonating someone, where it signs that browser out alone. See Differences From PHP.

A browser can't carry "remember me" between a PHP and a Go application sharing a database: Laravel Go's guard cookie is JSON named remember_web, where Laravel's is id|token|hash under remember_web_<sha1>. Keyring's own remembered_session cookie reads the same on both.

As in the PHP package: a cookie used a second time, from another browser or after Sessions.RememberGrace (10 seconds), ends the session for both holders and says so (RememberMeReused, reused). The browser's other requests sent alongside the one that used it join its session.

Timeouts

Setting Default
Sessions.Idle 2 hours Unused this long, a session ends (idle). Zero is no limit.
Sessions.Absolute 30 days This long after signing in, a session ends (expired). It can't be turned off.
Sessions.Levels.AAL2 1 hour idle, 24 hours absolute When AAL2 lapses.
Sessions.Levels.AAL3 15 minutes idle, 12 hours absolute When AAL3 lapses.

Each level lapses on its own clock, as the PHP package's SessionAssurance::touch() and lapse() have it: what was proved counts toward a level for its Absolute, and going unused past its Idle lapses it, and the levels above, until every factor for it is proved again. A zero limit is the session's own. Activity is noted at most once a minute.

Set the fields one at a time. Assigning cfg.Sessions or cfg.Sessions.Levels whole leaves the rest zero:

Go
cfg.Sessions.Levels.AAL2.Idle = 30 * time.Minute

Inactivity and "Remember Me"

A remembered session's idle limit is Sessions.RememberIdle, 14 days, in place of Sessions.Idle, as in the PHP package.

Ending a Session With Its Level

With Sessions.EndOnLapse on, a session ends (idle or expired) once the level it signed in at has lapsed, as in the PHP package.

How Many Sessions

Sessions.Max (100): a sign in beyond it ends whichever of the account's sessions has gone unused longest (session_limit). Zero is no limit. When ending one fails, the sign in fails. On PostgreSQL and MySQL, where the sign in holds the user's row, it all rolls back, the new record and the sessions it ended, as the PHP package's does. SQLite has no row locks. Sessions someone is impersonating neither count nor end.

Pages That Also Serve Guests

Sessions.ContinueAsGuest names the routes of your own pages that also serve guests, by name as web.Request.RouteIs takes them, with * as a wildcard, as the PHP package names them:

Go
cfg.Sessions.ContinueAsGuest = []string{"welcome", "docs.*"}

A GET page visit there whose session ended is redirected to the URL it asked for (an Inertia visit is told to load it in full), with Clear-Site-Data, the signed-out status flashed and no intended URL saved. JSON requests still get the 401. Register refuses an empty name. The URL keeps its query string as the browser sent it, where Laravel sorts it.

For Administrators

Terminal
go run . keyring:sign-out 42go run . keyring:sign-out taylor@example.comgo run . keyring:sign-out --all

The command is the PHP package's, with its names, options and exit codes: one user by ID or username (--id for an ID alone, and a name that could be two people signs out neither), as signing out everywhere else does (signed_out_everywhere), with SessionsRevoked; or --all, asking first unless --force, with one EveryoneSignedOut. It names a user by their Config.Username column and ID, and only takes an ID made of digits. It warns when the default cache store is Laravel Go's memory or discard store, whose locks don't keep the web server's requests out. Keyring still looks for the user's sessions again until none is left open. It reads the sessions from the database's writer, not a read replica.

As with any sign-out that isn't the browser's own, it takes effect on a session's next request, where AuthenticateSession runs.

From your own code, such as a support tool, Unlock lets a locked-out user try again, and ClearAccount clears the account's sign-in limits alone:

Go
k := keyring.From[models.User](r) err := k.Unlock(r, user) // lifts a risk lock, and clears the limits as a password reset doeserr = k.ClearAccount(r, user) // the sign-in limits alone

Neither checks who asked: check that first. There's no public way yet to sign a user out everywhere from your own code, only keyring:sign-out. See Differences From PHP.

Pruning

keyring:prune deletes what Keyring no longer needs, as the PHP package's does: devices signed out longer ago than Devices.KeepRevokedFor (30 days) or unseen for Devices.KeepUnseenFor (365 days), email changes that ended longer ago than EmailChanges.KeepEndedFor (30 days), security log entries older than SecurityLog.KeepFor (180 days), sign-in changes that freeze nothing any more (neither the sign-in method change nor the first password inside EstablishedAfter), ended session records nothing is left to announce for, and password holds lifted over a year ago. It names each table rather than each model (Pruned 3 [keyring_devices] records.).

A zero keep-for setting is its default, so setting cfg.Devices or another struct whole doesn't delete the whole table. Register refuses a negative one.

Keyring schedules it every day at PruneAt, 03:00 UTC, through Laravel for Go's scheduler, so run your application's schedule:run every minute. Set PruneAt to "" to schedule it yourself.

Keyring's Cookies

The cookies are the PHP package's, with the same names and prefixes: the device cookie (known_device), the "remember me" cookie (remembered_session), and, with devices off, the known-browser cookie (known_browser). Over HTTPS (APP_URL starts with https://, or the session cookie is always Secure) they're Secure and named __Host-..., or __Secure-... when the session cookie is shared with subdomains or kept to a path, as the PHP docs describe. They're encrypted as Laravel encrypts cookies, HttpOnly, SameSite=Lax, with the session cookie's path and domain. Devices.Cookie and Sessions.RememberCookie set names of your own, used exactly as given. Devices.CookieLifetime (400 days) is how long the browser keeps the device cookie.

A browser that still holds the device cookie under its plain name from before the app moved to HTTPS is found by it, and given its token back under the new name, as in the PHP package.

The Session Middleware

AuthenticateSession[U] checks each signed-in request, as the PHP package's does. Keyring appends it to the web group, followed by RequirePasswordChange[U], which does nothing until a user is held for a new password. It runs Laravel Go's auth.Session[U] itself, inside it, so it can read which record the session is on before the guard empties the session or a remember cookie signs it in. Don't add auth.Session to the web group yourself.

With Sessions.Middleware off, add both yourself, AuthenticateSession in place of auth.Session, around every route that signs anyone in:

Go
cfg.Sessions.Middleware = false
Go
Middleware: func(m *laravel.Middleware, _ *config.Config) {	m.Web.Append(keyring.AuthenticateSession[models.User]{}, keyring.RequirePasswordChange[models.User]{})},

Every route that runs auth.Session (or any other guard) has to run it inside AuthenticateSession. One before it would sign the session in or out before Keyring checks its record, so AuthenticateSession answers every request it finds one on with a 500. One on routes AuthenticateSession doesn't run on at all, in a group beside its own, can't be caught: its remember cookie signs the browser in on a session with no record, which Keyring then records as a new sign in. Keep signed-in routes in the web group. Laravel Go's test client's ActingAs is fine.

On each signed-in request, it signs the user out if the record was revoked, has expired, idled out or can't be found, or the account may no longer sign in (AllowSignInWhen), with the signed-out answer and Clear-Site-Data. It records a session your application signed in itself with auth.Login, once the request is done, and ends the record of one it signs out itself with auth.Logout (logged_out). A session auth.Session lets go of because the user is gone or their password changed is ended as logged_out too. It runs risk signals that check every request.

Your Own StartSession

Keyring places the session lock and the wrapper for overlapping requests around the web group's StartSession. A StartSession your application adds to another group, or lists on a route, isn't covered: Laravel Go runs a package's middleware changes before the application's. A session store of your own is covered when it's registered by name (laravel.Options.SessionStores) and named in SESSION_DRIVER. One given to a StartSession that replaces the web group's keeps the lock but not the wrapper, which is reported once.

Writing a Driver

Not available. Keyring for Go keeps the registry in keyring_sessions on your application's default database. The PHP package's sessions.driver, sessions.table, sessions.connection and sessions.store aren't ported, and there's no cache driver or driver of your own. See Differences From PHP.

Routes

Method URI Does
GET /user/sessions Lists the user's sessions.
DELETE /user/sessions Signs out every other session.
DELETE /user/sessions/{session} Ends one session.
GET /user/devices Lists the user's devices.
DELETE /user/devices Signs out every other session.
DELETE /user/devices/{device} Signs a device out.
GET, POST /devices/{device}/report The "this wasn't me" page and its button.

The device routes are there while Features.Devices is on. GET /devices/{device}/report is behind Limits.Pages (sixty a minute from one IP address), counted before the signature is checked, and its POST behind Limits.GuestForms or Limits.Forms. DELETE /user/sessions and DELETE /user/devices take the session lock and share the keyring-session-changes counts.

Events

The events are the PHP package's, each generic over the user type: NewDeviceSignedIn, UnrecordedDeviceSignedIn, DeviceRevoked, SessionsRevoked, SessionEnded, SessionContested, SessionResumed, RememberMeReused, and RegisteredSessionEnded, which isn't generic. DeviceRevoked carries the device as a keyring.Device, not a model. There's no EveryoneSignedOut. See Events.

How It Works

The Session Registry

As in the PHP package: every signed-in session gets a record with a 40-character ID kept in the session and never sent anywhere, holding the user, device, level, address, user agent, whether "remember me" was ticked, and timestamps. A session moves to a new record on every rotation, and the old record names its successor. Keyring checks the registry on every request, so a revoked session is signed out on its next request.

SessionUserType is what the record keeps as the user's type, connection:table, such as pgsql:users, as the PHP package's RegisteredSession::typeOf() writes it. It starts as DB_CONNECTION, or the PHP name of DATABASE_URL's driver, and users. Set it to what the PHP side writes when the two share a database.

Every change to a user's sessions runs under a cache lock keyed on the user, as the PHP package's Sessions::holding() runs them under a row lock, so it needs a cache store with locks that every server shares. Keyring warns once per process when the default store is Laravel Go's memory store. A move to a new record, signing out everywhere, ending a session and Sessions.Max also take the PHP package's row lock on the user (FOR NO KEY UPDATE on PostgreSQL, FOR UPDATE on MySQL), so they wait for a sign out everywhere or a sign in the PHP side is running, and those wait for them. The row is waited for 5 seconds at most, where PHP waits as long as the database does, and past that the request answers 500. SQLite has no row locks. See Security.

Requests That Overlap a Sign In

As in the PHP package, with Sessions.OverlappingRequests on (the default): a request sent before a sign in, step-up or sign-out gave the session a new ID doesn't save the old session again or send its cookies, so the browser keeps the new one, and one sent with the old ID after a few seconds more starts on a fresh, empty session. A double click no longer signs a browser out. Laravel Go has no hook around StartSession, so Keyring wraps the web group's session store, and takes the cookies off such a request's answer. See Differences From PHP and Your Own StartSession.

The session lock (BlockSession) makes Keyring's own routes that spend session state take turns: POST /login, POST /login/{factor} and the login options routes, the challenge and confirm routes, DELETE /user/sessions, DELETE /user/devices, PUT /user/password, POST /email-changes/{change}/confirm, single sign-on's redirects and callback, the impersonation routes, and the authenticator routes but the proof options. It's a cache lock keyed on the session's ID, taken ahead of the web group's StartSession, so the second request reads the session only once the first has saved it. A request that can't take it within 10 seconds fails with a 500. List it on routes of your own:

Go
route.Post("/settings/email", settings.UpdateEmail).Middleware(keyring.BlockSession{})

It works on routes in the web group alone. A route that lists it where the lock can't be taken fails with a 500 rather than running unlocked.

A Contested Session

As in the PHP package: when a rotation finds another request holding the same session has already moved the record on, the session ends for both (contested), and SessionContested is dispatched and logged as session_contested. See the PHP docs.