# Security

Source: https://keyringauth.com/docs/0.x/go/security

## Introduction

Keyring for Go makes the PHP package's guarantees, held to the same routes, answers and status codes by the [contract suite](https://github.com/keyringauth/keyring/blob/main/contract/README.md), which runs the same HTTP tests against every port. This page goes through the [PHP security page](https://keyringauth.com/docs/0.x/security) section by section, and says where the Go port's guarantee differs, and why. Where a section says nothing more, the PHP page holds as written.

## Guarantees

### Signing In

As in the PHP package. A refused sign in takes at least `Config.Timebox` (500 ms), a wrong password and an unknown account get the same answer, and a password hash still runs for an unknown address. Passwords are put in NFC form before they're checked.

### Rate Limiting

The limits are the PHP package's `Throttle`, counted under the same keys: attempts a minute per address (shared, so a success only gives back its own attempt), per username as typed and per account; locks that double each time up to `Limits.LongestLock` (`Limits.LongestIPLock` for an address), counted for a day; failures in a row up to `Limits.Consecutive` (100), kept in `keyring_failure_counts`; and `Limits.LockAfter`. Browsers the account has signed in from count apart, so someone guessing elsewhere can only make `Limits.ConsecutiveElsewhere` (80) of them, once `Features.Devices` is on. A known browser's minute and failures under a name as typed count under `{factor}|account-known|typed:{name}` and `{factor}|consecutive-known|typed:{name}`, and the account's minute under `{factor}|account-known|{account}`, where any other browser's use `|account|` and `|consecutive|`, so no name can be typed to share a known browser's. Without devices no browser is known, so the whole cap is shared, as in the PHP package. A second factor's limits are counted under its own keys.

Laravel Go's `rate` limiter is a token bucket, so the throttle keeps its own counts in the default cache store, as Laravel's `RateLimiter` would count them, written outside any database transaction. The limiters on Keyring's other routes (`keyring`, `keyring-pages`, `keyring-login-options` and `keyring-session-changes`) are fields of `Limits`, not limiters you redefine. Guests' presses of Keyring's form buttons are counted apart from signed-in users', in `Limits.GuestForms`.

#### At the Cap

As in the PHP package: an authenticator that has failed `Limits.Consecutive` times in a row is refused until it's set up again, or for the password and the factors that start a sign in, until a reset or `Keyring.ClearAccount`. `Limits.LockAfter` never holds a factor that only comes second.

```go
if err := keyring.From[models.User](ctx).ClearAccount(ctx, user); err != nil {
    return err
}
```

`ClearAccount` starts the account's minute counts and locks over too, and the failures in a row on every factor that starts a sign in. It leaves the limits on addresses, on the names typed and on second factors. Call it from a support tool once the owner has proved who they are: nothing in it checks who asked. `Keyring.Unlock` does the same and also lifts a risk lock. There's no way yet to start one second factor's limits over.

#### Locking Until a Reset

`Limits.LockAfter` works as in the PHP package: the account's password is refused after that many locks in a day until a reset or `ClearAccount`.

#### Octane's Cache Store

There's no Octane here, but the same holds for Laravel Go's `memory` store: it's one process's alone, so with more than one process or server each keeps counts, locks and spent challenges of its own. Keyring warns once per process when the cache store is `memory`, outside `APP_ENV=testing`. Use a store every process shares. See [A Shared Lock Store](https://keyringauth.com/docs/0.x/go/security#a-shared-lock-store).

### Single-Use Codes

As in the PHP package: a TOTP code can't be reused (each authenticator keeps the last step it accepted, under a row lock), a recovery code works once, an emailed code works once and only for the authenticator it was sent to, and a passkey challenge is answered once, in the session and in the cache. Codes and challenges are in the default cache store.

Each cache keeps its values its own way, so a code a PHP application sent is checked only by that application, even on a store both share.

An emailed code's [sign-in link](https://keyringauth.com/docs/0.x/go/factors#signing-in-from-the-email) carries its code, encrypted with `APP_KEY` together with the sign in it was sent for, and nothing about the link is stored. It finishes only that sign in, only in the browser whose session holds it, by posting the code as typing it would, so it shares the code's single use, expiry, guess limit and rate limits. Anywhere else, its page finishes nothing and doesn't show the code. So a scanner opening it signs nobody in or keeps a working code, another device isn't signed in, and the owner can't approve from their inbox a sign in someone else started with the password. The link works once, for as long as its code does, and no longer than its sign in.

### Second Factors and Step-Up

As in the PHP package, with one tightening: `RequireAssurance[U]{Level: keyring.AAL1}` takes no recovery code alone, where the PHP package's `keyring:aal1` does. A recovery code stands in for a lost factor beside another one, never as the whole of what's asked.

`RequireAssurance`, `RequireFreshVerification` and `RequireEnrollment` fail closed: without the session, or without Keyring's `AuthenticateSession` ahead of them, they answer `500` rather than let the request through. A guest is turned away, as in the PHP package.

Nothing reaches AAL3 yet, as there are no attested keys. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#passkeys-and-attestation).

### Sessions and Devices

As in the PHP package, with these differences, each from Laravel Go:

- Ending another session ends its record, and `AuthenticateSession` signs that browser out on its next request. Its session data stays in the store until it expires.
- A new password signs out every other session, whatever `sign_out_others` says, as Laravel Go's guard signs a fingerprint of the password hash into every session.
- Requests that overlap a sign in, step-up or sign-out are kept from saving the old session again (`Sessions.OverlappingRequests`, on), on the web group's `StartSession`. A `StartSession` you add yourself isn't covered.
- A session record is ended only by its own user, stricter than the PHP package.

Signing out one browser keeps the user's remember token, as Laravel's `logoutCurrentDevice()` does. Only `POST /logout` gives the user a new one, and not while impersonating them.

### Account Changes

As in the PHP package, except that Laravel Go has no model events: the password, the address and `Config.Protected` only stay inside Keyring's flows where your user model's `Updating` hook calls `Keyring.GuardChanges`, which `Register` checks the user type has. See [Protected Attributes](https://keyringauth.com/docs/0.x/go/protected-changes#protected-attributes).

### Links and Headers

As in the PHP package: every Keyring response gets `Cache-Control: no-store, private`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and `Cross-Origin-Opener-Policy: same-origin-allow-popups`, with `Referrer-Policy: same-origin`, or `no-referrer` on pages that emailed links open, from the `SecurityHeaders` middleware. Signing out, and starting or stopping an impersonation, send `Clear-Site-Data`. An Inertia form on a page an emailed link opened that goes anywhere but back loads the next page in full.

A guest's redirect to log in from one of your signed-in routes carries these headers too, where the PHP package's doesn't.

#### Emailed Links

Links start at `APP_URL`, never the request's `Host` header. An app on several domains starts them elsewhere with `Config.LinkRoot`:

```go
keyring.New[models.User](func(cfg *keyring.Config) {
    cfg.LinkRoot = func(ctx context.Context) string {
        return tenantURL(ctx)
    }
})
```

`tenantURL` is yours. Links are signed relative to the site, so the same link opens wherever it's put, and one a PHP application signed with the same `APP_KEY` opens here.

#### Tokens in Emailed Links

As in the PHP package: the links' tokens and signatures are in the URL of the page they open, which changes nothing, and the page posts them in the body.

### Request Input

As in the PHP package: Keyring reads its fields from the body, as a form or as JSON, and ignores the query string. Every input but passwords is trimmed, as Laravel's `TrimStrings` does.

### Storage

As in the PHP package: secrets are encrypted with the application key, recovery codes, sent codes and session handles are keyed hashes, device tokens are kept as their SHA-256, and reset tokens as their bcrypt hash. Laravel Go's `crypt` reads and writes Laravel's encrypted payloads, so a secret either side encrypted decrypts on the other.

### Logging

As in the PHP package. The security log never holds a password, code, token, signature or session ID. Without the table, or with `Features.SecurityLog` off, entries go to `slog.Default()` under a `keyring` group.

## What Keyring Keeps

The tables are the PHP package's, so what Keyring keeps is what its [list](https://keyringauth.com/docs/0.x/security#what-keyring-keeps) says. There's no `recordIpsUsing()` yet, so addresses are kept as the request gives them.

## What Your App Must Provide

### HTTPS and HSTS

As in the PHP package: serve the whole app over HTTPS, redirect HTTP to it, and send `Strict-Transport-Security`.

### Trusted Proxies

Per-address limits go by the request's IP. Behind a load balancer or proxy, list it in `Middleware.Proxies`, or every request comes from the proxy's address and shares one count:

```go
laravel.Options{
    Middleware: func(m *laravel.Middleware, _ *config.Config) {
        m.Proxies = []string{"10.0.0.10"}
    },
}
```

Each entry is an IP address or a network such as `10.0.0.0/8`. `"*"` trusts every proxy, which is only safe when nothing can reach the app but through one. On Laravel Cloud it's `"*"` by default.

### Secure Cookies

Set `SESSION_SECURE_COOKIE=true` and an `https://` `APP_URL` in production. Keyring's cookies are `Secure` and `__Host-` or `__Secure-` prefixed over HTTPS, as in the PHP package. See [Keyring's Cookies](https://keyringauth.com/docs/0.x/go/devices-and-sessions#keyrings-cookies).

### A Content Security Policy

As in the PHP package: Keyring sends no `Content-Security-Policy`, so yours must include `frame-ancestors`.

### Headers on Your Other Responses

`SecurityHeaders` runs only on Keyring's routes. Send `X-Content-Type-Options: nosniff` on your whole app, and decide your own `Referrer-Policy` and `Cache-Control` for pages that show account details.

### Bot Checks

As in the PHP package: Keyring has no CAPTCHA. Add one of your own where you need it.

### A Shared Lock Store

The default cache store has to support locks and be shared by every server, as it holds what Keyring has to see the same everywhere: the session lock, the locks on each user's sessions and sign-in methods, the sign-in rate limits and their marks, the `keyring-session-changes`, `keyring-login-options`, `keyring` and `keyring-pages` limits, the session IDs replaced for overlapping requests, the passkey challenges already answered, the single sign-on states already used, the codes a code factor sent with their guesses and the codes already used, the enrollments and freeze proofs already used, the records a risk step-up moved sessions to, the claim on each impersonation's end, the counts that keep the security log's refusals and the security emails to a few an hour, and the scheduler's locks that keep `keyring:sweep` to one runner and one run at a time. Risk locks go in `Risk.Store`, and identity providers' discovery documents and keys in `SSO.Store`, each the default store when empty.

The `memory` store is one process's alone. The contract app uses the `database` store (`CACHE_STORE=database`). Where the PHP package splits these between `cache.limiter`, `risk.store` and `session.block_store`, the Go port keeps them in the default store, apart from `Risk.Store` and `SSO.Store`. A `Risk.Store` that isn't configured panics at the first lock, a `500`, as Laravel Go can't say whether a store exists without using it.

Every change to a user's sessions, password and sign-in methods runs under a cache lock keyed on the user, and the changes that need it also lock the user's row as the PHP package does: `FOR NO KEY UPDATE` on PostgreSQL, so inserts that reference the user don't wait for it, and `FOR UPDATE` on MySQL. So a PHP application sharing the database is kept out too. The row is waited for 5 seconds at most, where the PHP package waits as long as the database does. Past that the change fails with a `500` rather than going ahead without the lock. SQLite has no row locks, so there the cache lock alone keeps two changes apart.

## Cryptography

The Go port adds no cipher or hash of its own. Everything belongs to Laravel Go or Go's standard library, chosen to make the PHP package's values, so the two read each other's.

### Keys

| Key | Used For |
|---|---|
| `APP_KEY` (and `APP_PREVIOUS_KEYS`) | Encrypting pending logins, authenticators' secrets, flashed results and Keyring's cookies, as Laravel encrypts them. Keys derived from it (HKDF) for recovery codes, sent codes, session handles, reserved addresses and passkey user handles. Signing verification and "this wasn't me" links, as Laravel signs them. |

Use the PHP side's `APP_KEY` when the two share a database.

### Algorithms

| Algorithm | Where |
|---|---|
| Laravel's encryption, through Laravel Go's `crypt` | Secrets, pending logins, flashed results, cookies. |
| HMAC-SHA256 | Recovery codes, sent codes, session handles, reserved addresses, signed links, reset tokens. |
| SHA-256 | Device tokens, `sso` credential IDs. |
| bcrypt, through Laravel Go's `hash` | Passwords, reset tokens. |
| ES256, EdDSA, RS256 (Keyring's `webauthn` package) | Passkeys. |
| RS256, PS256, ES256, EdDSA (Keyring's `jose` package) | Identity providers' ID tokens. |
| HMAC-SHA1, SHA-256, SHA-512 | Authenticator app codes, as each was set up. |

Unlike the Rust crate, Ed25519 passkeys are checked, so `EdDSA` is offered by default, as in the PHP package.

### Random Values

Every random value comes from the operating system's generator, through Go's `crypto/rand`.

### Changing an Algorithm

Not available: there's no hasher to swap, as Laravel Go only hashes passwords with bcrypt, and passwords aren't rehashed on sign in. An Argon2 hash a PHP application made can't be checked here.

### Peppering Passwords

Not available, as in the PHP package, for the reasons its [docs](https://keyringauth.com/docs/0.x/security#peppering-passwords) give.

## What a Request Costs

As in the PHP package's [table](https://keyringauth.com/docs/0.x/security#what-a-request-costs): bcrypt on a sign in, a reset and a password change, Have I Been Pwned on a new password in production and with `BreachedPassword`, and an identity provider's endpoints on single sign-on, each behind a rate limit. The password actions run with a deadline inside the owner's lock, and the breach checks fit within it.

## Standards

The Go port keeps the PHP package's standards, as its [page](https://keyringauth.com/docs/0.x/security#standards) lists them, and [OWASP ASVS and NIST SP 800-63B](https://keyringauth.com/docs/0.x/go/owasp-asvs) goes through where the Go port stands.

## Known Limitations

### Where Keyring Departs From a Standard

As in the PHP package, plus:

- **`RequireAssurance` at AAL1** is stricter than the PHP package's, not looser: no recovery code alone.
- **`sign_out_others: false`** can't be honoured on a password change, so every other session ends. This is stricter, not looser.

### Other Limits

The PHP package's [other limits](https://keyringauth.com/docs/0.x/security#other-limits) hold. These are the Go port's own:

- **Ended sessions' data.** An ended session's data stays in the store until it expires, as Laravel Go can't destroy another browser's session.
- **No attested keys.** Security keys and attestation aren't ported yet, so nothing reaches AAL3.
- **Four security emails** (`second_factor_failed`, `recovery_code_used`, `account_locked` and `clone_suspected`) aren't sent yet. The log entries are written.
- **Reserved lookalikes** in scripts beyond Latin, Greek and Cyrillic only match themselves, and a reservation for such an address isn't found by the other side.
- **Lock timeouts.** A request that waits the full 10 seconds for the session lock gets a `500`, not a `423`.
- **Risk locks** a PHP application placed aren't seen here, and the other way round, as the two write cache values differently.

See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences) for everything else.
