Devices & Sessions
On this page
- Introduction
- Devices
- Trusted Devices
- New Device Sign Ins
- The "This Wasn't Me" Link
- Locations
- Device Names
- Your Own Device Model
- Listing and Revoking Devices
- Listing and Ending Sessions
- Is It Still Signed In?
- Hearing About Ended Sessions
- Sweeping Ended Sessions
- Remember Me
- A Cookie Used Twice
- Timeouts
- Inactivity and "Remember Me"
- Ending a Session With Its Level
- How Many Sessions
- Pages That Also Serve Guests
- For Administrators
- Pruning
- Keyring's Cookies
- The Session Middleware
- Your Own StartSession
- Writing a Driver
- Routes
- Events
- How It Works
- The Session Registry
- Requests That Overlap a Sign In
- A Contested Session
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 Rust 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:
config.section_mut::<laravel_keyring::KeyringConfig>().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, and everyone already on the browser moves to it. A sign in that proved a second factor gets a new token too. devices.limit (50) devices an account, a new one taking the place of the one seen longest ago, which is signed out everywhere. 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.trust_for (30 days) once the sign in proves two factors, and the challenge page's canTrustDevice says whether answering would earn it. Trust does nothing alone: a policy closure reads it from attempt.device(), and answering Requirement::aal1() for a trusted one skips the second factor there. 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. Where devices.limit leaves no room for a "remember me" sign in, UnrecordedDeviceSignedIn is dispatched instead.
The "This Wasn't Me" Link
The new-device email's button, and NewDeviceSignedIn::revoke_url(), is a link to /devices/{device}/report, signed relative to the site as Laravel signs it, for devices.report_link_for (7 days), so a link either side sends opens on the other. 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. A link that's refused is LinkRefused and a 403.
revoke_url() takes the days as an Option<u32> and returns a Result, as the link can't be signed without an APP_KEY.
Locations
devices.locator takes an Arc<dyn laravel_keyring::location::LocatesIps>, as the PHP package's devices.locator. location::HeaderLocator::cloudflare() reads Cloudflare's headers, and HeaderLocator::new([("country", "X-Country-Code")]) headers of your own:
use std::sync::Arc;use laravel_keyring::location::HeaderLocator; config.section_mut::<laravel_keyring::KeyringConfig>().devices.locator = Some(Arc::new(HeaderLocator::cloudflare()));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() gives a request's country, region, city, latitude and longitude as far as it knows them. 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"). The PHP package's Location::of() isn't public: a risk signal reads the location with Assessment::location().
Device Names
devices.describe_using() 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):
config.section_mut::<laravel_keyring::KeyringConfig>().devices.describe_using(|agent| { if agent.contains("AcmeApp/") { Some("The Acme app".to_owned()) } else { laravel_keyring::describe_user_agent(agent) }});Return None for one it can't name. describe_user_agent() is Keyring's own reading, to fall back on. One that panics is reported and gives no name, and a name is cut to 255 characters, so neither fails a sign in.
Your Own Device Model
Not available: there are no Eloquent models, so there's no useDeviceModel(). Devices are rows in keyring_devices. 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 the fresh check: 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 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, each by its handle (the PHP package's keyed hash of the record it started on), named after its browser and platform, with its device's ID.
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. Those happen whether or not the ones before them failed, as in the PHP package. Both are behind the fresh check and the keyring-session-changes limiter: limits.session_changes (six) a minute from one session and limits.session_changes_per_user (thirty) from all the user's together.
laravel-rust 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.
From your own code, laravel_keyring::Sessions<Users> wraps the same:
use laravel_keyring::Sessions; Sessions::<Users>::sign_out_everywhere(&user, None).await?; // every session, returns how many endedSessions::<Users>::sign_out_others(&user, &session, &request).await?; // all but this browser's let sessions = Sessions::<Users>::active(&user).await?;if let Some(found) = Sessions::<Users>::find(&user, handle).await? { Sessions::<Users>::revoke(&user, &found).await?;}list() gives the route's JSON, and current() the browser's own record. sign_out_everywhere() ends sessions as revoked, with no SessionsRevoked. There's no because(). revoke() says whether a session ended, and refuses one that isn't the user's.
Is It Still Signed In?
Sessions::<Users>::still_signed_in(&user, handle) says whether the session a handle names is still active, following it to whatever record it has moved to. It's given no session, so a user who followed their verification link, where registration hides who has an account, answers false.
Hearing About Ended Sessions
As in the PHP package's AnnouncingSessionRegistry: every record a revocation ends dispatches RegisteredSessionEnded, with its handles, the user, the guard, the device, when and why, and a sign-out of everyone dispatches EveryoneSignedOut. 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. Nothing in the crate revokes inside your database transaction, so there's no waiting for one to commit.
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.sweep_limit (1000, at most 10,000) of each a run. Keyring schedules it every sessions.sweep_every once that's set:
config.section_mut::<laravel_keyring::KeyringConfig>().sessions.sweep_every = Some(std::time::Duration::from_secs(5 * 60));Under a minute is a minute, over 12 hours is 12 hours, and zero is off. It runs on one server, with an overlap lock of twice the interval. With it set, every session that ends is announced at least once. The sweep is the database driver's alone: the cache driver has nothing for it to do.
Remember Me
"remember": true with the password (or a passkey) signs in with laravel-rust'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. When laravel-rust'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.remember_idle, 14 days) or ends with its level isn't brought back, nor is one with no cookie of Keyring's.
Two differences from the PHP package, from laravel-rust:
- A session your application signs in itself with
Auth::login(..).remember(true)is recorded, but not as remembered, since laravel-rust doesn't say its remember cookie was set. Its remember cookie brings nobody back. - Every sign-out uses
Auth::logout, which gives the user a new remember token, so any sign-out also stops "remember me" in the user's other browsers.
A Cookie Used Twice
As in the PHP package: a cookie used a second time, from another browser or after sessions.remember_grace (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). |
sessions.absolute |
30 days | This long after signing in, a session ends (expired). |
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. Activity is noted at most once a minute.
Inactivity and "Remember Me"
A remembered session's idle limit is sessions.remember_idle, 14 days, in place of sessions.idle, as in the PHP package.
Ending a Session With Its Level
With sessions.end_on_lapse 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), sessions someone is impersonating neither counting nor ending. None for no limit. When ending one fails, the sign in fails. On the database driver on the default connection, 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. Otherwise (a sessions.connection of its own included) its new record is deleted, and the sessions ended before the failure stay ended.
Pages That Also Serve Guests
sessions.continue_as_guest lists paths of your own pages that also serve guests, a trailing * matching the rest, where the PHP package names routes. A GET page visit there whose session ended is redirected to the URL it asked for (an Inertia visit gets a 409 with X-Inertia-Location), with Clear-Site-Data, the signed-out status flashed and no intended URL saved. JSON requests still get the 401. One that doesn't start with / is warned about at boot. The URL keeps its query string as the browser sent it, where Laravel sorts it.
For Administrators
cargo run -- keyring:sign-out 42cargo run -- keyring:sign-out taylor@example.comcargo run -- keyring:sign-out --allThe 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, with SessionsRevoked; or --all, asking first unless --force. It names a user by their mail_address() and ID, and only takes an ID made of digits. It warns when the default cache store is memory, 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, on every session driver.
From your own code, such as an admin screen:
use laravel_keyring::Sessions; Sessions::<Users>::sign_out_everywhere(&user, None).await?; // one userSessions::<Users>::sign_out_everyone().await?; // everyonelaravel_keyring::unlock(&user).await?; // let a locked-out user try againAs with any sign-out that isn't the browser's own, these take effect on a session's next request, where AuthenticateSession runs.
Pruning
keyring:prune deletes what Keyring no longer needs, as the PHP package's does: devices signed out longer ago than devices.keep_revoked_for or unseen for devices.keep_unseen_for, email changes that ended longer ago than email_changes.keep_ended_for, security log entries older than security_log.keep_for, sign-in changes that freeze nothing any more, 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.).
The provider schedules it every day at prune_at, 03:00 UTC, through laravel-rust's scheduler, so run your application's schedule:run every minute. Set prune_at to None to schedule it yourself. laravel_keyring::prune_devices(&config) prunes devices alone.
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 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.remember_cookie set names of your own.
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
laravel_keyring::http::AuthenticateSession checks each signed-in request, as the PHP package's does. The provider puts it at the end of the web group, followed by RequirePasswordChange, which does nothing until a user is held for a new password. Just ahead of StartSession it puts BlockSession, the session lock, and EndUnsavedSignIns. With sessions.middleware off, add AuthenticateSession and RequirePasswordChange yourself, and Keyring's own routes are a 500 naming AuthenticateSession until you do.
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, with the signed-out answer and Clear-Site-Data. It records a session your application signed in itself with Auth::login, and ends the record of one it signs out itself with auth.logout() once the handler returns. It runs risk signals that check every request.
AuthenticateSession tells a sign in by laravel-rust's remember cookie from one the application made by the session ID changing as it asks for the user, since laravel-rust doesn't say how the user was loaded. That only works while it's the first thing in the request to ask: keep any middleware that loads the user after it. Signed-in routes outside the web group don't get it, so keep them in the group.
Your Own StartSession
Keyring doesn't replace StartSession, as laravel-rust's Backend and Session::start/save are private (see Requests That Overlap a Sign In). If your application replaces laravel-rust's StartSession with a session middleware of its own, the provider has nothing to put BlockSession and EndUnsavedSignIns ahead of, so add them yourself, in the web group, just ahead of your session middleware.
Writing a Driver
sessions.driver is database (keyring_sessions, or sessions.table on sessions.connection) or cache (in sessions.store, with the PHP package's keys and fields), from KEYRING_SESSION_DRIVER. A driver of your own implements laravel_keyring::registry::SessionRegistry and is registered with sessions.extend():
use laravel_keyring::registry::{ PartialRevocation, SessionChanges, SessionEndReason, SessionOwner, SessionRecord, SessionRegistry,}; #[derive(Debug)]struct DynamoSessions; impl SessionRegistry for DynamoSessions { async fn save(&self, session: &SessionRecord) -> laravel::Result<()> { todo!() } async fn find(&self, id: &str) -> laravel::Result<Option<SessionRecord>> { todo!() } async fn for_user(&self, owner: &SessionOwner, now: i64) -> laravel::Result<Vec<SessionRecord>> { todo!() } async fn update(&self, id: &str, changes: &SessionChanges) -> laravel::Result<()> { todo!() } async fn revoke(&self, id: &str, reason: SessionEndReason, now: i64) -> laravel::Result<Option<SessionRecord>> { todo!() } async fn replace(&self, id: &str, successor: &SessionRecord, revoke: bool, now: i64) -> laravel::Result<bool> { todo!() } async fn revoke_all(&self, owner: &SessionOwner, except: Option<&str>, reason: SessionEndReason, now: i64) -> Result<Vec<SessionRecord>, PartialRevocation> { todo!() } async fn revoke_device(&self, owner: &SessionOwner, device_id: &str, reason: SessionEndReason, now: i64) -> Result<Vec<SessionRecord>, PartialRevocation> { todo!() } async fn revoke_everyone(&self, now: i64) -> laravel::Result<()> { todo!() } async fn prune(&self, now: i64) -> laravel::Result<u64> { todo!() }} laravel::Application::configure().with_config(|config, _| { let sessions = &mut config.section_mut::<laravel_keyring::KeyringConfig>().sessions; sessions.extend("dynamo", DynamoSessions); sessions.driver = "dynamo".to_owned();});Keep what the trait's docs promise, above all that a revocation sticks (a stale copy saved over a revoked record mustn't bring it back) and that of two calls revoking or replacing one record at the same moment, only one wins. A driver only stores and revokes: Keyring announces what it ends. Signing a user out everywhere, or off a device, calls revoke_all or revoke_device, then looks at for_user again and calls it again until nothing it meant to end is open, as it finds again on the database: a record another process moved to a new one while the driver revoked is ended too. Sessions still open after 64 rounds are an error, never a quiet success. Unlike the PHP package's, a driver is an instance rather than a closure for the manager, and is given the reason and the time with each call.
The cache driver keeps the PHP package's keys and fields, but laravel-rust's cache stores JSON where Laravel stores PHP-serialized arrays, so a PHP and a Rust application can't share a cache registry. The database driver's rows are shared. Keyring's migrations always create keyring_sessions on the default connection, so a sessions.table or connection of your own is yours to create.
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 the keyring-pages limiter, and its POST behind keyring. DELETE /user/sessions and DELETE /user/devices take the session lock.
Events
The events are the PHP package's, in laravel_keyring::events: NewDeviceSignedIn, UnrecordedDeviceSignedIn, DeviceRevoked, SessionsRevoked, SessionEnded, SessionContested, SessionResumed, RememberMeReused, RegisteredSessionEnded and EveryoneSignedOut. DeviceRevoked carries the device's ID and name, not its model. 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.
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. On the database driver, a move to a new record, and a sign in when sessions.max is set, also take the PHP package's row lock on the user (SELECT ... FOR UPDATE on their id in the table session_user_type names, on the default connection), 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, and past that the change fails. SQLite has no row locks, and a table that isn't there is skipped, with a warning logged once. It's looked for again each time, so one made later is locked without a restart. See Security.
Requests That Overlap a Sign In
Not available yet. The PHP package's sessions.overlapping_requests replaces Laravel's StartSession with one that doesn't save a session another request replaced after it was sent. laravel-rust has no public way to skip a session's save, so the crate behaves as the PHP package does with it off: a request that overlapped a sign in, step-up or sign-out can save the old session again. What laravel-rust would need is in Differences From PHP.
The session lock (BlockSession) still makes Keyring's own routes that spend session state take turns: POST /login, the passkey 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 keyed on the session's ID on every session driver, read from inside the cookie with the cookie driver. List routes of your own in sessions.block.
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.