session

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT, MIT Imports: 41 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Session

Overview

The Session repository is designed to handle the management of user sessions, including authorization, storage, and expiration. It provides a framework for managing sessions across different databases and supports multiple login types.

Features

  • Session Management: Efficient handling of user session creation, storage, and expiration.
  • Database Support: Seamless integration with multiple databases.
    • PostgreSQL
    • Google Cloud Spanner
  • Auth Sessions: One session that every sign-in method can establish, with users, explicit identity links, pending confirmation and MFA. See the "Auth sessions (multiple sign-in methods)" section.
  • Sign-in methods of the Auth session, each in its own package:
    • Username/Password (session.PasswordSignIn)
    • Microsoft Entra ID (Azure) OIDC (session/azure), admitting one tenant, several, any tenant or Microsoft personal accounts, with role synchronization from the token's roles and provider-initiated logout (see the "Microsoft Entra ID OIDC" section)
    • Google Workspace OIDC (session/google), admitting one Workspace, several, any Workspace or any Google account, with role synchronization from Google Groups (see the "Google Workspace OIDC" section)
    • WorkOS SSO: built and tested, but under internal in v0.13.0 until its review; it returns to the public API in v0.13.1
  • The second factor: every session carries one when the sign-in policy asks (signin.RequireMFA): the attestation a sign-in's connection makes, by evidence in the token (Entra's amr) or by the application's declaration of a directory it administers (Attesting()), or else the library's own factor, a one-time code mailed to the user's address, with the browser remembered afterwards as a trusted device and an administrator's reset. See "The second factor" under the Auth session.
  • Invitations, email addresses and sign-up: an invitation mailed to an address, carrying the roles its acceptance grants, accepted only by the account it was sent to (an account with no address, by the link); a user's email address in two states, unverified and verified, the person proving it by a mailed link; and self-service sign-up with a password when the application opens it. See "Users and their email address", "Invitations" and "Sign-up" under the Auth session.
  • Mail: one interface the invitation, verification, sign-up and sign-in code flows send through (session/mail), with the Google Workspace SMTP relay as the first driver (session/mail/workspace). See the "Sending mail" section.
  • Preauth: trust-the-caller stepping-stone sessions (session.NewPreauth).
  • Custom Session Data: App-defined data attached to each session, resolved atomically at session creation and available to every request. See the "Custom session data" section.
  • Custom User Data: App-defined durable data attached to the user record — it survives logout, expiry, and regeneration, and dies with the user. See the "Custom user data" section.
  • Login Refusal Codes: A refused sign-in returns the browser to the login page with a code, never with text; the page maps the code to a sentence it holds itself. See the "Login refusal codes" section.
  • Attempt limiting: The password method limits failed attempts per name, known or not, in memory and in the store, and refuses an attempt past the limit with too_many_attempts and the wait; an after-sign-in hook is told of every session a sign-in establishes. See the "Attempt limiting and the after-sign-in hook" section.
  • Machine outlets and bearer tokens: a URL space of the application a program calls with a bearer token the Auth issued, never a cookie; the tokens a signed-in person issues for a program of their own, and the access and refresh tokens a command-line client obtains through the device flow (RFC 8628) with the person's approval, and the session/deviceflow package a command-line program signs in with. See the "Machine outlets and bearer tokens" section.

Every session type is generic over two data axes, custom session data and custom user data: Auth[SessionData, UserData, Tx] (Tx is the storage's transaction type, inferred from the store) and Preauth[SessionData] (Preauth has no user record, so no user-data axis). An application that uses neither axis instantiates with the NoCustomData sentinel: session.NewAuth[session.NoCustomData, session.NoCustomData](store, cookieKey).

Schema

The DDL for every table the library owns ships as golang-migrate files under schema/spanner/ and schema/postgresql/, one set per starting point: migrations (the base set: sessions and users), auth (Auth sessions on the base set: the sessions' users, identity links, auth events and pending sign-ins) and impersonation. Which sets a group applies is in "Storage and schema" below.

Time columns are the database's. Every column that records when something happened (a session's CreatedAt, UpdatedAt and AuthenticatedAt, a user's CreatedAt and LastSignInAt, an auth event's OccurredAt, an impersonation record's StartedAt and EndedAt, an identity link's CreatedAt and LastUsedAt, a pending sign-in's CreatedAt and ConsumedAt, a factor code's and a trusted device's time columns, the OIDC user anchor's CreatedAt and UpdatedAt) is written with the database's time, never the application's: Spanner's commit timestamp, PostgreSQL's transaction time (now()). A host clock that runs ahead of the database's therefore cannot be refused, and the rows one write stores carry one time. On Spanner the columns carry allow_commit_timestamp = true: the shipped sets mark them (a CommitTimestamps migration in each), and a table created by hand or named per group needs the same option before a v0.13 driver writes to it, since a write to a column without it fails:

ALTER TABLE Sessions ALTER COLUMN CreatedAt SET OPTIONS (allow_commit_timestamp = true);
ALTER TABLE Sessions ALTER COLUMN UpdatedAt SET OPTIONS (allow_commit_timestamp = true);

A deadline (ExpiresAt) is the application's and is written as given. An auth event the application hands the library (sessioninfo.AuthEvent) carries a zero At when it happens now, and the database stamps it; an earlier event carries its time, stored as given.

The users table carries the user-management columns. SessionUsers has, beside the username, the password hash and Disabled, the password change mark PasswordChangeRequired and the time columns CreatedAt and LastSignInAt (see "Users and the forced password change"). The shipped 000002_SessionUsers migration creates them; a users table named per group takes the same DDL under its name. The auth set adds the email address columns Email, NormalizedEmail and EmailVerifiedAt (SessionUserEmail), the mail links table (SessionMailLinks) and the second factor's tables (SessionFactorCodes, SessionTrustedDevices); see "Users and their email address" for the two shapes the address columns take.

PostgreSQL time columns are timestamp with time zone. The driver writes time.Time values as instants, which timestamptz stores faithfully whatever zone the host runs in. Earlier revisions of the DDL declared timestamp without time zone, which keeps the wall clock and drops the zone: a deployment on that type stays correct as long as every process writing to it runs in UTC, and such a deployment does not need to migrate. To migrate anyway, convert the columns and restart the application in the same window — pgx caches the parameter types of its prepared statements, so a live pool keeps writing wall-clock values (and fails one cached read per connection) until its connections are recycled:

-- Repeat for every time column created from the DDL (OIDCUsers CreatedAt and
-- UpdatedAt, the impersonation table's StartedAt/ExpiresAt/EndedAt).
-- 'UTC' names the zone the writing processes ran in.
ALTER TABLE "Sessions"
    ALTER COLUMN "CreatedAt" TYPE timestamptz USING "CreatedAt" AT TIME ZONE 'UTC',
    ALTER COLUMN "UpdatedAt" TYPE timestamptz USING "UpdatedAt" AT TIME ZONE 'UTC';

Auth sessions (multiple sign-in methods)

Auth[SessionData, UserData, Tx] is one session that any registered sign-in method can establish: password, Microsoft Entra ID (Azure), Google Workspace, WorkOS SSO and any OpenID Connect provider known by its issuer. An application mounts one cookie, one session table and one middleware chain, and every session belongs to a user, a SessionUsers record, by its ID. The password method checks the user's password; an external method produces a verified identity that is linked to a user through the identities table, keyed by (method, connection, subject) and never by email. Tx is the storage's transaction type (pgx.Tx or *spanner.ReadWriteTransaction); NewAuth infers it from the store, and the rules the application gives the Auth and its methods are typed to it.

Each redirect-based method is its own package (session/azure, session/google; session/workos waits under internal until v0.13.1), built on the session/signin contract and the shared session/oidc machinery, which also holds the generic OpenID Connect method for a provider with nothing vendor-specific about it; an application imports the packages of the methods it offers and registers each with its SignIn function and Config.

Method Registration → handlers Identity key (connection, subject) Login parameters Roles
password PasswordSignIn(auth, options...) → *PasswordMethod: Login, ChangeUserPassword user ID JSON {"username", "password"} —
azure azure.SignIn(auth, name, rule, &azure.Config{...}) → *azure.Method: Login, Callback, FrontChannelLogout (tid, oid) ?returnUrl=, ?prompt=select_account signin.RoleSync(manager) or signin.DisableRoleSync()
google google.SignIn(auth, name, rule, &google.Config{...}) → *google.Method: Login, Callback (the Workspace the Workspaces slot selects, sub) ?returnUrl=, ?login_hint=, ?prompt=select_account google.RoleSync(...) or google.DisableRoleSync()
oidc oidc.SignIn(auth, name, rule, &oidc.Config{...}) → *oidc.Method: Login, Callback (Config.Connection, the issuer URL by default; sub) ?returnUrl=, ?login_hint=, ?prompt=select_account signin.RoleSync(manager) (the roles claim) or signin.DisableRoleSync()
workos (internal until v0.13.1) workos.SignIn(auth, name, rule, &workos.Config{...}) → *workos.Method: Login, Callback (connection_id, idp_id) ?organization= (required), ?returnUrl= never synchronized

name identifies the registration on the Auth and must be unique there: one method may be registered several times under different names, so one Auth offers two Entra tenants as two registrations, each with its own configuration and rules. The password registration is named password. rule is the application's own account rule for an identity that is not linked to any user yet, and nil is the usual value: the Entra and Google methods apply a standard account rule (Config.Accounts) to a first sign-in (see "Storage and schema").

Storage and schema

Each auth group owns ten tables: sessions and users (the base migrations, schema/*/migrations), identities, auth events, pending sign-ins, sign-in attempts, mail links, factor codes and trusted devices (the auth migrations, schema/*/auth/migrations, which also add UserId, AuthenticatedAt, ProviderSessionId and ProviderSessionIssuer to the sessions table and the email address columns to the users table), and impersonations (schema/*/impersonation/migrations) if you use it. A new group applies the base set, then the auth set.

The schema keeps its own integrity: a session belongs to an existing user (UserId, null only for a role-principal impersonation), and deleting a user deletes its sessions, their auth events and its identity links; your custom data tables cascade from the session and user rows likewise. Sessions are marked expired, never deleted, by the library: retention is the application's policy, and auth events last exactly as long as their session rows.

An application whose groups are named applies the sets under the group's names and tells the Auth them: WithSessionTableName, WithUserTableName, WithIdentitiesTableName, WithPendingSignInsTableName, WithSignInAttemptsTableName, WithMailLinksTableName, WithFactorCodesTableName and WithTrustedDevicesTableName on NewAuth, and NewAuthEventsTable(name) / NewImpersonationTable(name) on the store. A table name must be a plain identifier (a letter or underscore, then up to 127 letters, digits or underscores): the store refuses any other, and the constructor reports it under the option's name, so a name never reaches SQL unchecked. Name the users table's unique indexes after the table as the shipped DDL does (<UsersTable>_NormalizedUsername_idx and <UsersTable>_NormalizedEmail_idx on PostgreSQL, <UsersTable>ByNormalizedUsername, <UsersTable>ByUsername and <UsersTable>ByNormalizedEmail on Spanner): the drivers read a username or an address conflict by those names. Build the storage with NewSpannerAuth / NewPostgresAuth. The application's rules are given to the Auth and to each method, typed to the storage's transaction (*spanner.ReadWriteTransaction or pgx.Tx) so they can read and write the application's own rows in the sign-in's transaction; a rule written for the other driver's transaction does not compile. On Spanner a rule may run more than once when the transaction retries, so it must not have side effects outside it, and a row it writes with a mutation is buffered until the commit, invisible to a later read in the same transaction: write with DML what a later rule must read.

  • The sign-in policy (signin.Policy[Tx]) is optional. Without one, a sign-in is decided by the library's own checks: the user exists and is enabled, the identity is linked or resolved, roles reconcile. An application with rules of its own sets them with auth.SetSignInPolicy(rule) after NewAuth and before serving; the rule answers for every method, and for a session the application starts for a user it authenticated itself (StartAuthenticatedSession), once the user is known, with signin.Allow(), signin.Deny(code) or signin.RequireMFA(factors...). The factors are the methods the step may record when it completes the sign-in: the library's own, sessioninfo.MethodEmailCode, or the application's ("totp"); the pending status and the PendingHook report them, and CompletePending refuses any other; none accepts any. A RequireMFA is satisfied without a step by a second factor the sign-in already carries: the attestation its connection makes, or a trusted device of the user; see "The second factor". An application whose users belong to tenants sets the library's tenant policy (signin.TenantPolicy), with its own rule chained after it when it has one; see "The tenant policy".

  • The account rules decide an identity's first sign-in: an identity that is not linked to any user yet. A linked identity signs in by its link and never consults them. Each Entra and Google registration declares a standard rule in Config.Accounts, which the library applies inside the sign-in's first transaction:

    • signin.MembersOfDirectory (the default): every member of the directory gets an account under their sign-in name, the user principal name on Entra and the verified email on Google. A user the application pre-created is linked instead, found by the username first and then by the address: the user under that name, matched without regard to case, or else the user who holds the identity's address verified, when the method verified the address (Google does, Entra does not), since a person is one user whichever way they sign in. The link is made after a password confirmation when the user has a password, outright when the user has none and signs in through no other connection yet. An address a user holds unverified is a reservation, not a match: the person is provisioned as a stranger, and the new account holds no address until they verify one, the reserved address staying with the account it was entered for. A registration's own rule that provisions a new user for an identity whose verified address another user holds verified is refused (identity_rejected): never a second user for one person.
    • signin.InvitedUsersOnly: the same matching, and no provisioning; a person no user was created for is refused (not_invited), unless the sign-in carries an invitation, which is then the account the rule asks for. The application creates the users under their sign-in names, with or without a password, before they sign in.
    • signin.OpenSignUp: anyone who signs in gets an account under their sign-in name. It is for public applications and refused on a registration that serves one organization.

    In a tenanted application the tenants' declarations decide a stranger first. With auth.SetDirectoryAdmission(directoryLookup, userManager, seatHook) (see "The tenant policy"), a person no user was created for, from a directory some tenant declares, is decided by that tenant's declaration before the registration's rule is reached. A person who already holds a membership under the sign-in name in a declaring tenant, or as the application's staff, is that tenant's person, seated ahead of their first sign-in, and is provisioned under the sign-in name. A declaration naming a default seat admits a stranger, who is provisioned and seated with it in every tenant naming one, through the hook, in the transaction that creates the account. A seat the invitation the sign-in consumes names too (the same role in the same tenant) is given once, by the invitation, and is left out of what the hook is handed. A declaration naming none admits strangers by invitation only, the invitation the sign-in carries being the account as under signin.InvitedUsersOnly, and without one the sign-in is refused (invitation_only) and nothing is written. A directory no tenant declares falls to the registration's rule as above.

    Every standard rule writes nothing for a guest of the directory (an Entra B2B guest, refused with guest_account: a guest's preferred username is an address the directory did not verify), for a token asserting no application role when the method synchronizes roles (no_roles), or for an identity without a sign-in name (no_email). The tenant key on the link is the organization the registration names for the account (Identity.Organization): on Entra the tenant id, or the name azure.NamedTenant gives it; on Google the Workspace's name, the account's domain under any Workspace, google.AnyAccountConnection under any Google account.

  • A registration's own rule (azure.AccountRule, google.AccountRule; required on WorkOS, which has no standard rule) is given to its SignIn function and runs first, for what the standard rule cannot know: it receives the method's own identity type (*azure.Identity, *google.Identity), decoded from the verified claims with the raw claims on it, and answers signin.Reject(code), signin.Link(userID, trusted), signin.Provision(newUser, onProvisioned), signin.Confirm(userID) or signin.Standard(), which leaves the identity to the standard rule once the rule's own checks have passed; signin.Tenant(key) on any of the last four stores the application's tenant key on the link. A Link is the rule's own evidence, and the library asks for more when it can: a user who has a password must confirm with it (Confirm) unless the link is trusted; a user without a password cannot confirm, so an identity from another connection than the ones that user already signs in through is refused unless the link is trusted. Never choose the user by an email or another claim the provider does not verify.

A sign-in runs in two transactions, the same on Spanner and PostgreSQL:

  1. User resolution (external methods): a linked identity is its user's; otherwise the account rules run, the registration's own first and then the standard one, and the outcome is applied: the link, or the new user, its link and the rows Provision's onProvisioned writes. A link decision holds the user against another link decision until the transaction ends (PostgreSQL: a transaction-scoped advisory lock keyed by the user, which holds neither session inserts nor a rule's own reads of the user; Spanner: the transaction is serializable), so two racing sign-ins from two connections cannot both link a password-less user. A transaction the database ends to break a deadlock or a serialization failure runs once more.
  2. Decision and session: the user is read (a disabled one is refused), the sign-in policy runs, and the session row is inserted with its auth events and custom session data.

Each transaction commits unless a hook or the storage returns an error. A Reject, Confirm, Deny or RequireMFA answer is not an error: it commits the hook's own writes (a record of a refused sign-up, an audit row) and writes no session. Because the resolution has committed by the time the policy runs:

  • the policy (and the custom session data resolver) reads the user a sign-in just provisioned and the rows onProvisioned wrote, on both backends;
  • req.User (*sessioninfo.SignInUser) tells them which user was resolved and how: Source is UserNamed (password), UserExistingLink, UserNewLink or UserProvisioned (req.User.Provisioned()), with the link's Tenant;
  • a user a rule provisioned stays, linked, when the policy then denies the sign-in or holds it for MFA; the next sign-in goes through the link and the policy decides again. Return signin.Reject from a custom rule when the user must not be created at all. A hook error rolls back its own transaction only: an onProvisioned failure leaves no user, while a policy error leaves a provisioned user in place.
// The application's rules, typed to the store's transaction.
func signInPolicy(ctx context.Context, tx *spanner.ReadWriteTransaction, req *sessioninfo.NewSessionRequest) (*signin.Decision, error) {
    if req.User.Provisioned() { // a first sign-in through SSO: the MFA step enrolls the person
        return signin.RequireMFA("email-otp"), nil
    }

    return signin.Allow(), nil
}

// Optional: the application's own rule for an Entra identity's first sign-in. The
// standard rule in Config.Accounts handles the usual case; this one refuses what the
// standard rule cannot know and leaves the rest to it.
func entraAccountRule(ctx context.Context, tx *spanner.ReadWriteTransaction, identity *azure.Identity) (*signin.Resolution, error) {
    partner, ok, err := partnerOfTenant(ctx, tx, identity.TenantID) // the application's own rows
    if err != nil {
        return nil, err
    }
    if !ok {
        return signin.Reject("not_a_partner"), nil
    }

    return signin.Standard(signin.Tenant(partner)), nil
}

events, err := sessionstorage.NewAuthEventsTable("SessionAuthEvents")
store := sessionstorage.NewSpannerAuth(client, sessionstorage.WithAuthEvents(events))

auth, err := session.NewAuth[MyData, session.NoCustomData](store, cookieKey,
    session.WithCookieName("partner_auth"),
    session.WithIdentityLinked(notifyLinked), // called after every identity link
    session.WithPendingHook(onPending),       // called when a sign-in becomes pending
    session.WithPendingTimeout(10*time.Minute),
    session.WithPendingCookieName("auth-pending"),
)
auth.SetSignInPolicy(signInPolicy) // optional: without it the library's checks decide

// Register the sign-in methods before serving; each returns its own handlers.
password := session.PasswordSignIn(auth) // *session.PasswordMethod
sso := azure.SignIn(auth, "entra", entraAccountRule, &azure.Config{ // *azure.Method; nil leaves first sign-ins to Accounts alone
    Tenants: azure.Tenant(cfg.EntraTenantID), ClientID: cfg.EntraClientID, ClientSecret: cfg.EntraClientSecret,
    RedirectURL: cfg.SSORedirectURL, RoleSync: signin.DisableRoleSync(), LoginURL: "/login",
    Accounts: signin.InvitedUsersOnly, // the standard rule: pre-created users only
})

NewAuth refuses the OIDC-only storage features (WithOIDCUsers, the custom user data login hook).

The tenant policy

The tenant policy is the library's sign-in rule for an application whose users belong to tenants: a person signs in when one of their tenants admits the way they signed in. It is built from two things the application gives it and set like any other policy:

auth.SetSignInPolicy(signin.TenantPolicy(userManager, tenantDeclaration))
  • The person's memberships, read through userManager, the access library's user manager (signin.UserRoleManager, the same store role synchronization reconciles through). The person's tenants are the domains where they hold a role; a role held in the global partition or in every tenant domain makes the person the application's own staff.
  • Each tenant's declaration, read through tenantDeclaration, a signin.DeclarationReader[Tx] the application writes over its own tenant record, typed to the store's transaction like the other hooks and run in the sign-in's: func(ctx, tx, tenant accesstypes.Domain) (*signin.TenantDeclaration, error). A declaration names the directories the tenant admits its people through (signin.Directory: a method and the connection its identities carry, which is the Entra tenant id, the name the registration gives a Google Workspace, or a WorkOS connection id) and whether its people come through those only (DirectoryOnly). A tenant that declares nothing (a nil declaration) admits its people by password and through no directory.
  • A first sign-in through a directory by a person no user was created for is decided before the policy, by the account rules, and in a tenanted application by the tenants' declarations first, through auth.SetDirectoryAdmission(directoryLookup, userManager, seatHook). directoryLookup, a signin.DirectoryReader[Tx], reads every tenant's declaration of the directory the identity came through, each with its default seat (signin.DeclaredDirectory: the tenant and the role, "" for none), in the sign-in's first transaction; userManager is the role store above, read for the memberships the person already holds; seatHook, a session.DirectorySeatedHook[Tx], seats the person with the seats the declarations name (signin.DirectorySeat), inside the transaction that creates the user, which it is handed, so the account is made and seated together or neither is, under the contract the invitation hook has (see "Invitations"). A declared directory belongs to its tenant. A person who already holds a role in a declaring tenant, or as staff, is admitted as that tenant's person, seated ahead of their first sign-in. A default seat admits and seats a stranger, so rule 3 below then finds the membership. A stranger who carries an invitation into the tenant that names the default seat's role is given it once, by the invitation hook: the two hooks write in one transaction and neither reads what the other wrote, so the seat hook is handed only the seats the invitation does not name, and is not called for none. A declaration naming none refuses a stranger by invitation only (invitation_only), with no account created, unless the sign-in carries an invitation. A directory no tenant declares falls to the registration's account rule. Without the three, a stranger is the registration's rule's alone, and an open-sign-up registration gives them an account holding nothing.

The rules, in order, once the user is known:

  1. A person holding a role in the global partition or in every tenant domain is the application's staff and is admitted on the library's own checks; so is a sign-in whose method synchronizes roles, since the directory names the person's roles and the synchronization, which runs once the session stands, refuses a person with none. The application's own directories are admitted by the registration's organization slot already.

  2. A person who is a member of no tenant is refused (no_tenant), unless the policy was built with signin.AdmitWithoutTenant(), which the self-service shape of an application needs: a stranger signs in, then creates their organization and its first membership, and until then the session reaches no tenant.

  3. A sign-in through a directory (Entra, Google, WorkOS) is admitted when one of the person's tenants declares the directory it came through, and refused otherwise (connection_not_in_tenant).

  4. Any other sign-in, a password or a session the application starts for a user it authenticated itself, is admitted when one of the person's tenants admits its people other than through its directories, and refused when every one of them is directory only (directory_only): nothing would be reachable.

  5. Otherwise the sign-in is allowed. signin.Policy.Then chains the application's own rule after the tenant policy, for what the tenant policy cannot know; it is asked after an Allow and never after a Deny or a RequireMFA:

    auth.SetSignInPolicy(signin.TenantPolicy(userManager, tenantDeclaration, signin.AdmitWithoutTenant()).Then(ownRule))
    

The policy decides what the session may be and never writes. Which of the person's tenants the session then reaches is decided again, tenant by tenant, where the application computes the session's tenant list: signin.TenantDeclaration.Admits(method, connection) is the same decision over one tenant, with no transaction and no reads, and the session says how it was established through sessioninfo.DataFromCtx(ctx).EstablishedBy(), its first auth event, whose method and connection are the sign-in's (sessioninfo.AuthMethod.ThroughDirectory tells a sign-in through a directory from the application's own). So a person in a directory-only tenant and a password-admitting tenant signs in by password and reaches the second; a member of two tenants with two directories reaches the one whose directory they came through. A refusal is a sessioninfo.LoginRefusal with its code, and errors.Is matches signin.ErrSignInDenied and the rule's own cause (signin.ErrNoTenant, signin.ErrConnectionNotInTenant, signin.ErrDirectoryOnly); a role store or reader error fails the sign-in (internal_error).

Registering sign-in methods

A sign-in method is registered on the Auth, and its registration returns the method's own handlers; routes are wired from that value. The handler is the proof of registration: a method that was not registered has no handlers to wire, and each method is its own type, so a handler exists only on the method it belongs to (FrontChannelLogout only on *azure.Method). A registered method with no route is harmless.

Registration is refused, with a panic, in one place, the way http.ServeMux refuses a duplicate pattern: these are wiring mistakes, found when the application starts.

  • A registration name used twice on one Auth, by the same method or another, or a registration without a name.
  • A registration name that cannot name its state cookie. Each registration keeps its own state cookie, OIDC-<session cookie name>-<name>, so the name is letters, digits and hyphens (lakeside-entra): two registrations of one method, logins with different providers in one browser, and two Auths on one host with a registration of the same name never read each other's state, and a callback completes only the login its own registration began.
  • A method registered once the Auth is in use: after it has served a request through any of its handlers or middleware, or read its methods to check or hash a password through its API (CreateSessionUser before PasswordSignIn(auth, HashAlgorithm(...)) would have hashed with the default). Register every method, then build the router and serve.
  • A registration without an account rule: a WorkOS registration with a nil rule (WorkOS has no standard rule), or a registration naming a standard rule that does not exist.
  • A registration that synchronizes roles beside any other method, in either order of registration. Role authority is the Auth's, not a registration's: the Auth is one users table, one role file and one administration surface, so when a directory writes the roles it writes them for everyone in the table, and a second way in would be a second authority over the same people (a person it provisions holds nothing at their first sign-in, and the administration surface refuses to seat them because the directory will not). A registration with RoleSync stands alone on its Auth; two populations with two authorities are two Auths. The refusal names the two ways out: an Auth of its own for the registration, or DisableRoleSync so the application assigns the roles.
  • A misconfigured method: Azure or Google without its role sync slot, or with a slot missing its manager (or, for Google, its group prefix or lookup); an Azure registration without its Tenants, a tenant id that is not a GUID, Microsoft's consumer tenant listed as a tenant, a tenant listed twice or a name used twice, or an Authority that is not a base URL; a Google registration without its Workspaces, a Workspace without a name or a domain, a value that is not a domain name, a name used twice or a domain in two Workspaces; role synchronization with other than one tenant or one Workspace; open sign-up (signin.OpenSignUp) on a registration that serves one or several named organizations; members of the directory with any tenant, personal accounts, any Workspace or any Google account and no rule of the application's own; a generic OpenID Connect registration without an Issuer, with one that is not an absolute URL, or without its role sync slot; cookie or session options passed to PasswordSignIn instead of NewAuth.
Routes
// A machine outlet and the device flow's public endpoints sit outside StartSession:
// a bearer token is the credential there, no cookie is read or written.
droids := session.RegisterMachineOutlet(auth, "droids")
r.Route("/api/droids", func(r chi.Router) {
    r.Use(droids.ValidateToken)
    // …the outlet's routes
})
r.Post("/api/oauth/device/authorize", auth.Device().Authorize()) // client_id, outlet
r.Post("/api/oauth/token", auth.Device().Token())                // grant_type device_code | refresh_token

r.Use(auth.StartSession, auth.SetXSRFToken)
r.Get("/api/user/authenticated", auth.Authenticated())
r.Get("/api/user/sso/login", sso.Login())       // ?organization=…&returnUrl=…
r.Get("/api/user/sso/callback", sso.Callback())
r.Get("/api/user/pending", auth.Pending().Status())
r.Get("/api/user/methods", auth.Methods(&session.MethodList{ // what the login page offers
    Methods: []session.AdvertisedMethod{
        {Name: "password", Label: "Password", Path: "/api/user/session"},
        {Name: "workos", Label: "Single sign-on", Path: "/api/user/sso/login"},
    },
    Pending: session.PendingRoutes{
        Status: "/api/user/pending", Confirm: "/api/user/pending/confirm", Cancel: "/api/user/pending/cancel",
        SendCode: "/api/user/pending/code", VerifyCode: "/api/user/pending/code/verify", EnrollEmail: "/api/user/pending/email",
    },
    Invitation: session.InvitationRoutes{Open: "/api/user/invitation", Accept: "/api/user/invitation/accept", SignUp: "/api/user/invitation/sign-up"},
    Email:      session.EmailRoutes{Add: "/api/user/email", Verify: "/api/user/email/verify"},
    SignUp:     session.SignUpRoutes{Start: "/api/user/sign-up", Open: "/api/user/sign-up/open", Complete: "/api/user/sign-up/complete"},
}))
r.Group(func(r chi.Router) {
    r.Use(auth.ValidateXSRFToken)
    r.Post("/api/user/session", password.Login())
    r.Post("/api/user/pending/confirm", auth.Pending().ConfirmWithPassword())
    r.Post("/api/user/pending/cancel", auth.Pending().Cancel())
    r.Post("/api/user/pending/code", auth.Pending().SendCode())          // mails the sign-in code
    r.Post("/api/user/pending/code/verify", auth.Pending().VerifyCode()) // {"code", "rememberDevice"}
    r.Post("/api/user/pending/email", auth.Pending().EnrollEmail())      // {"email"}: a user without an address gives one
    r.Post("/api/user/mfa", app.CompleteMFA) // an MFA step of the application's own: checks its code, then auth.API().CompletePending
    r.Post("/api/user/logout", auth.Logout())
    r.Post("/api/user/password", password.ChangeUserPassword()) // validates the session itself
    r.Post("/api/user/invitation", auth.Invitation().Open())          // {"token"}: sets the invitation cookie
    r.Post("/api/user/invitation/sign-up", auth.Invitation().SignUp()) // {"password", "username"}: the invited person's account
    r.Post("/api/user/sign-up", auth.SignUp().Start())                 // {"email"}: mails the sign-up link (OpenSignUp)
    r.Post("/api/user/sign-up/open", auth.SignUp().Open())             // {"token"}
    r.Post("/api/user/sign-up/complete", auth.SignUp().Complete())     // {"token", "password", "username"}
    r.Group(func(r chi.Router) {
        r.Use(auth.ValidateSession)
        r.Post("/api/user/invitation/accept", auth.Invitation().Accept()) // the signed-in person accepts
        r.Post("/api/user/email", auth.Email().Add())                     // {"email"}: mails the verification link
        r.Post("/api/user/email/verify", auth.Email().Verify())           // {"token"}
        r.Get("/api/user/tokens", auth.ApplicationTokens().List())        // the person's tokens
        r.Post("/api/user/tokens", auth.ApplicationTokens().Create())     // {"name", "outlet", "expiresIn"}: the secret, once
        r.Post("/api/user/tokens/revoke", auth.ApplicationTokens().Revoke()) // {"id"}
        r.Get("/api/user/device", auth.Device().Lookup())                 // ?userCode=: which client asks, for which outlet
        r.Post("/api/user/device/approve", auth.Device().Approve())       // {"userCode"}
        r.Post("/api/user/device/deny", auth.Device().Deny())             // {"userCode"}
        // …protected routes
    })
})

The invitation, email and sign-up handlers are described under "Invitations", "Users and their email address" and "Sign-up" below, and the sign-in code's under "The second factor"; the groups that send mail (Email(), SignUp(), the pending handlers SendCode(), VerifyCode() and EnrollEmail()) panic at wiring on an Auth without WithMail. The machine outlet, the token page and the device flow are described under "Machine outlets and bearer tokens" below.

The pending handlers and the API's pending methods read the pending identity StartSession found, so they must run behind it; the POSTs belong behind ValidateXSRFToken like the password login. The session read (Authenticated), the logout and the password change sit outside ValidateSession: they validate the session on their own, and they are what a user who must change their password reaches (see "Users and the forced password change"). The methods list names the password change route (ChangePassword) whenever it lists the password method.

What the login page is told

The login page renders from the server, so the browser bundle is the same in every environment and a method that is not registered has no button. auth.Methods(list) is the public route that tells it: for each method the application lists, its name, the method behind it, how it starts, its label and its path, in the list's order, the pending sign-in routes when the list names them, and the password change route when the password method is listed.

{
  "methods": [
    {"name": "password", "method": "password", "kind": "password", "label": "Password", "path": "/api/user/session"},
    {"name": "workos", "method": "workos", "kind": "redirect", "label": "Single sign-on", "path": "/api/user/sso/login"}
  ],
  "pending": {"status": "/api/user/pending", "confirm": "/api/user/pending/confirm", "cancel": "/api/user/pending/cancel",
              "sendCode": "/api/user/pending/code", "verifyCode": "/api/user/pending/code/verify", "enrollEmail": "/api/user/pending/email"},
  "changePassword": "/api/user/password",
  "usernameIsEmail": true,
  "invitation": {"open": "/api/user/invitation", "accept": "/api/user/invitation/accept", "signUp": "/api/user/invitation/sign-up",
                 "standing": {"email": "pat@lakeside.edu", "tenant": "", "expiresAt": "2026-10-31T20:00:00Z", "usernameIsEmail": false, "methods": ["workos"],
                              "accountExists": false, "hasPassword": false}},
  "email": {"add": "/api/user/email", "verify": "/api/user/email/verify"},
  "signUp": {"start": "/api/user/sign-up", "open": "/api/user/sign-up/open", "complete": "/api/user/sign-up/complete"}
}
  • kind is how the method starts: password is a form that posts {"username", "password"} to path and reads the JSON answer of the password login; redirect sends the browser to path (a GET, with ?returnUrl= naming the page to come back to) and the method's callback brings it back. The kinds are signin.KindPassword and signin.KindRedirect.
  • name is the registration's name on the Auth, method the method behind it (password, azure, google, workos, oidc), for a page that shows a provider's mark.
  • label is the application's wording for the method.
  • path, the pending paths and changePassword are the application's: the list is written where the routes are wired, so the paths the page is told are the paths the router serves. A registered method the list leaves out is not offered. The pending block's sendCode, verifyCode and enrollEmail are the sign-in code's routes, named together or not at all (PendingRoutes); a page told them runs the library's second factor (see "The second factor") when a sign-in waits for it.
  • changePassword is the path of the password method's ChangeUserPassword handler, which the page posts {"oldPassword", "newPassword"} to when a sign-in finds the user must change their password (the session read's passwordChangeRequired). It is present whenever the password method is listed.
  • usernameIsEmail is present, and true, when the listed password method declares the username as the email address (UsernameIsEmail): the page then asks for the address where it would ask for a username, and a sign-up takes none.
  • invitation, email and signUp are the paths of the invitation, email address and sign-up handlers, each block present when the list names it (MethodList.Invitation, Email, SignUp). The invitation block's signUp is named exactly when the password method is listed; the sign-up block needs the password method listed and registered with OpenSignUp. The page opens a link it was sent to with ?invitation=, ?verify= or ?signUp= by posting the token to the block's open (or verify) path; see "Invitations", "Users and their email address" and "Sign-up".
  • invitation.standing is the live invitation the browser carries, present when the invitation cookie that open set still names an invitation that stands: the address it was sent to, its tenant ("" for the application's global surface), when it stops being accepted, whether an account created from it takes the address as its username, and the names of the listed external registrations that could admit the address (methods, empty when none could), as Invitation().Open() answered them; the page hides the methods not named. accountExists says an account already holds the invited address and hasPassword that it signs in with a password, so the page offers that account's password form, and offers to create an account only where none holds the address; the link holder may know it, since following the link proved they own the address. A page that arrives without the mailed link's token, as it does when an external sign-in was refused and sent the browser back with ?code=, reads the invitation from here and keeps showing it. The block is absent when the browser carries no cookie, or its invitation is dead (used, revoked or expired).

Methods is called after every method is registered and panics on a wiring mistake, as a registration does: an empty list, a method that is not registered on the Auth, a name listed twice, a method without a label or with a path that is not a canonical path in the application, a pending block with some of its paths, the password method without its change route or that route without the method, an invitation, email or sign-up block with some of its paths, or a sign-up block for a password method that does not offer sign-up. Route it beside the login routes: behind StartSession, before ValidateSession, no XSRF token.

The redirect and response contract

A sign-in ends in one of three ways. External methods answer with a redirect; the password login and the pending handlers answer JSON. <LoginURL> is the method's Config.LoginURL (default /login).

Outcome External Callback() password.Login()
Session established (new session ID) 302 <returnUrl> (default /) 200 {"mfaIsRequired": false}
Waits for the user's password 302 <LoginURL>?pending=confirmation[&returnUrl=<path>], or the pending hook's URL —
Waits for the application's MFA 302 <LoginURL>?pending=mfa[&returnUrl=<path>], or the pending hook's URL 200 {"mfaIsRequired": true[, "redirectUrl"]}
Refused 302 <LoginURL>?code=<code> 401 {"message", "code"} (403 for a forbidden cause)
Refused: the name's failed attempts reached the limit — 429 {"message", "code": "too_many_attempts", "retryAfter": <seconds>} with the Retry-After header (see "Attempt limiting and the after-sign-in hook")
  • returnUrl is only ever a path in the application, in canonical form: one leading / (not // or /\), printable ASCII, no backslash anywhere (raw or %5C), no empty, . or .. path segment (raw or percent-encoded), and a path made of RFC 3986 path characters; its query and fragment pass through (/settings/sso?test=done, /reports#x). An external Login() whose returnUrl breaks any of these is refused with 400, and the callback sanitizes it again, falling back to /. The callback writes the Location header with exactly that value. Percent-encode a non-ASCII path before passing it. A WorkOS Login() without organization is also 400, and its callback refuses a profile from another organization than the login requested (organization_mismatch).

  • prompt=select_account on a Google or Entra Login() asks the provider for its account chooser (its prompt=select_account), so a provider holding one signed-in account does not sign that account in again without asking. The login page sends it after a refusal, so a person refused with the wrong account picks another instead of being sent round the same loop, and under "Use a different account"; it sends nothing on an ordinary visit, where the single-account person is signed in without a click. Any other prompt value is refused with 400. A provider that reports an error on the callback instead of a code (error=access_denied when the person canceled at its chooser or consent screen) is refused token_exchange_failed without an exchange, after the state check, so the page is always reached with a code and a login page that forwards to the provider on its own can never loop.

  • pending is the login page's routing marker. The page reads the pending identity from Pending().Status(): 200 {"reason", "email", "expiresAt", "returnUrl"[, "factors"][, "emailCode"]}, 404 when there is none, 401 {"code": "pending_expired"} once it has expired or been used. emailCode is the sign-in code's state, present for an MFA wait that may take it on an Auth that sends mail (see "The second factor").

  • Confirmation (reason confirmation): the page asks for the existing user's password and posts {"password"} to Pending().ConfirmWithPassword(): 200 {"mfaIsRequired": false} (linked, the hook called, signed in; go to returnUrl), 200 {"mfaIsRequired": true} (linked, but the policy wants MFA: the pending identity remains with reason mfa), 401 for a wrong password (the pending identity remains), 409 when the pending identity waits for MFA instead.

  • MFA (reason mfa): the page runs the library's step, the sign-in code (Pending().SendCode(), VerifyCode(); see "The second factor"), or the application runs its own and calls auth.API().CompletePending(ctx, w, sessioninfo.AuthEvent{Method: "totp"}), which starts the session (the user is resolved afresh and must be the one it waited on, and the policy decides again with the step's events on the request, so a tenant disabled or switched to require SSO during the wait is honored: a RequireMFA the events satisfy proceeds, a Deny refuses, a RequireMFA for another factor holds again) and records the sign-in's events followed by the step's. The pending identity always names its user (UserID, Username), including one the sign-in has just provisioned, which exists by then.

  • Pending().Cancel() discards the pending identity.

  • The pending hook (WithPendingHook) runs when password.Login(), an external Callback() or Pending().ConfirmWithPassword() has just held a sign-in, after the pending identity is stored and its cookie set. It receives the *sessioninfo.PendingIdentity (reason, user, the identity with its email, expiry, return path), so the application can send its MFA code and choose the next page:

    func onPending(ctx context.Context, w http.ResponseWriter, r *http.Request, p *sessioninfo.PendingIdentity) (string, error) {
        if p.Reason != sessioninfo.PendingMFA {
            return "", nil // the default: <LoginURL>?pending=confirmation
        }
        if err := mfa.SendCode(ctx, p.UserID.UUID); err != nil {
            return "", err // the pending identity is discarded and the sign-in fails
        }
    
        return "/user/mfa", nil
    }
    

    The callback redirects to the URL it returns, and the JSON handlers answer it as "redirectUrl"; an empty URL keeps the default. The hook may instead write the response itself, and nothing more is written. An error discards the pending identity and fails the sign-in (?code=internal_error on a redirect). The hook changes nothing about the pending identity (its cookie, its timeout; the session ID is regenerated when it completes). The URL is the application's own: never build it from request input. The AuthAPI methods never call the hook: CompletePending and ConfirmPendingWithPassword return a *signin.PendingSignInError instead.

  • The codes are the sessioninfo.LoginRefusalCodes of the "Login refusal codes" section, including the resolver's and policy's own; text never travels.

What a pending identity is

A pending identity is a verified identity waiting for its confirmation or MFA. It is a row of the SessionPendingSignIns table (migration 000002 of the auth schema) holding everything the sign-in carried: the identity and its claims, the registration it came through, the user it waits on, the steps so far, the role names the method asserted, the factors the policy accepts, the return path and when it expires. The browser holds only the auth-pending cookie, encrypted and authenticated with the cookie key, carrying an opaque 32-byte token; the row keeps the token's SHA-256. A pending identity is accepted only while its row is live: not expired and not consumed. Completing, canceling or replacing it consumes the row by a conditional update, before the completion signs in, so the token is single-use: of two completions racing on a copied cookie, one proceeds and the other answers pending_expired. No session row exists until the sign-in completes, so nothing of a pending identity ever validates as a session. Expired and consumed rows stay for audit; delete them by ExpiresAt on your own schedule.

The second factor

Every session carries a second factor when the sign-in policy asks for one: the policy answers signin.RequireMFA(sessioninfo.MethodEmailCode) for every sign-in (or RequireMFA(), which accepts any factor), and the library satisfies it one of three ways, in this order, before it holds the sign-in. The requirement is the policy's, so an application that wants no second factor sets none, and one whose rule varies by person or tenant writes the rule; what a connection can vouch for is the registration's, below, since it is a property of the sign-in method, not of the tenant the person reaches.

  1. The connection attests. A sign-in's connection says what it can about a second factor (sessioninfo.Identity.Attestation), and the Auth records it as the session's second auth event, right after the sign-in's, under the same connection:
    • By evidence: the token's amr claim names mfa (RFC 8176), which Microsoft Entra asserts after its own multifactor authentication. The event is attested-by-evidence, with the amr values. Google puts no such evidence in its tokens.
    • By declaration: the registration declares the directory as one that enforces a second factor, because the application administers it and knows it does (a Workspace's 2-Step Verification enforcement, a tenant's Conditional Access policy): google.Workspace("ccc", "example.com").Attesting(), azure.Tenant(id).Attesting(). The event is attested-by-declaration. The declaration is for named Workspaces and listed tenants only; AnyWorkspace, AnyGoogleAccount, AnyTenant and PersonalAccounts admit organizations the application does not administer and are refused with it, so name the administered one beside the open entry: google.Workspaces(google.Workspace("ccc", "example.com").Attesting(), google.AnyGoogleAccount()). An attested sign-in satisfies any RequireMFA, the application's own factors included, and is never held. A password never attests.
  2. The browser is a trusted device. A person who entered the code may ask for the browser to be remembered (rememberDevice): the Auth keeps a row in the trusted devices table with the hash of an opaque token, and the browser the encrypted auth-trusted cookie with the token, for WithTrustedDevicePeriod (30 days). A sign-in from that browser by that user satisfies a RequireMFA that accepts the email code (no factor named, or MethodEmailCode among them) and records a trusted-device event in the step's place; a RequireMFA for the application's own factors alone is the application's step to run. The cookie holds one entry per user, keyed by the user's id inside the encrypted value, so two people who share a browser, or one person with two accounts, are each remembered: a sign-in reads the signing-in user's entry alone, and a sign-in held for the code drops that user's entry alone (it named a dead device, or none), leaving the others' as they are. A browser holds at most five entries; remembering one more drops the oldest. A cookie of the one-token shape earlier releases wrote is still read and is rewritten in this shape at the next remembering.
  3. The sign-in code. Otherwise the sign-in waits as a pending identity with reason mfa and the policy's factors, and the login page runs the step when the factors include the email code: Pending().Status() reports emailCode with the masked address the code goes to (codeEmail, p•••@example.com), whether a code stands (codeSent, codeExpiresAt) and whether the user must first give an address (enrollEmail); the page posts to Pending().SendCode(), which mails the user a six-digit code good for WithEmailCodeTimeout (10 minutes), then {"code", "rememberDevice"} to Pending().VerifyCode(), which completes the sign-in as CompletePending does with an email-code event, in a new session. A wrong code is 401 {"code": "invalid_code"} and the code stands with one fewer attempt; the fifth wrong code kills it, as its expiry does, and a code entered while none stands (none sent, or the one sent died) is 401 {"code": "code_expired"}, so the page asks for a new one, which replaces the old. An address is sent five codes within fifteen minutes that go unused, and the sixth is refused with too_many_emails and the wait, as a link is; a code that is used resets the count, so a person who signs in with each code sent never meets the limit. The code goes to the address the user holds, verified or not: an address an operator entered is proven by the code as a link would prove it, and the user holds it verified once the code is entered. A user who holds no address gives one at the step (Pending().EnrollEmail(), {"email"}), which is written on the user verified when its code is entered; an address another account holds is answered as sent and told so by mail to that address, as the add-address step does, so the screen reveals nothing. The AuthAPI offers the same as SendEmailCode, EnrollEmail and VerifyEmailCode.

A code mailed to the mailbox of the account that just signed in adds little against a stolen password that opens that mailbox too: for a directory, the attestation is the answer, and the code is for the password method and for directories the application neither administers nor gets evidence from.

The administrator's reset. AuthAPI.ResetFactors(ctx, userID) forgets every browser the person asked to be remembered, so their next sign-in from any of them asks for the factor; a signed-in person forgets their own browser with ForgetTrustedDevice, which revokes the session user's device and takes their entry out of the cookie, leaving the browser remembered for anyone else it was. The email code itself has nothing to reset: a person who lost their mailbox is given a new address by an operator (SetSessionUserEmail), unverified, and the next code proves it. Recovery codes are not offered. Live sessions are not touched by the reset; DestroyUserSessions ends them.

What the tables hold. A code is a row of SessionFactorCodes: the pending sign-in it was sent for, the address, the code's hash salted by the pending sign-in, the wrong attempts, and when it was created, expires and was consumed; one code stands for a pending sign-in at a time, and the codes go with the pending sign-in. A trusted device is a row of SessionTrustedDevices: the user, the token's hash, and when it was created, expires, was last used and revoked; the devices go with the user. Expired and consumed rows stay for audit; delete them by ExpiresAt on your own schedule.

Every session
  • The session ID is regenerated at every sign-in, confirmation and MFA completion: the cookies are written only once the session row, its auth events and role synchronization have succeeded.
  • The user is loaded by UserId on every request. ValidateSession refuses a session with no user or whose user is missing or disabled; the user is sessioninfo.UserFromCtx(ctx). The session's user, authentication time and auth events are on the context's *sessioninfo.SessionData (sessioninfo.DataFromCtx(ctx)): UserID, AuthenticatedAt, AuthEvents.
  • Custom session data is resolved in the transaction that inserts the session, after the user resolution has committed: the resolver reads the user (one just provisioned included) and the application's rows, and req.User says how the user was found. A pending identity has no session row, so it has no custom data.
  • Each session records how it was authenticated in SessionAuthEvents: the sign-in method (with its connection and the IdP's amr), the attestation its connection makes (attested-by-evidence, attested-by-declaration), then any link-confirmation, trusted-device and MFA steps (email-code, or the application's own). AuthAPI.StartAuthenticatedSession(ctx, w, userID, events) starts a session the application authenticated itself, recording its events; it is decided like a login: the sign-in policy answers, a Deny refuses it and a RequireMFA holds it as a pending identity. No session start skips the policy; a support session is an impersonation.
  • Role synchronization (Azure, Google) reconciles the roles of the user the identity resolved to, from the roles the provider asserted at sign-in, whenever such a sign-in establishes a session (including after a confirmation or MFA). A sign-in whose asserted roles the application recognizes none of is refused (no_roles) before anything is resolved or written, so an invitation it carried stands; a role store that fails once the session stands expires the session.
  • Impersonation works as on the other types. A user principal's session belongs to the impersonated user; a role principal's belongs to none. The session records an impersonation event whose connection is the actor.
  • A request on a machine outlet is bound to the person whose bearer token it carries the same way: the user is loaded on every request and refused when missing or disabled, the session data's ID is the token's, its one auth event is token with the token's kind as its connection, and sessioninfo.TokenFromCtx(ctx) names the token. See "Machine outlets and bearer tokens".
  • User management is by ID: ChangeSessionUserPassword, SetSessionUserPassword, ResetSessionUserPassword, DeactivateSessionUser and DeleteSessionUser destroy the user's sessions by UserId; DeleteSessionUser deletes its identity links with it; UnlinkIdentity refuses a user's last means of sign-in. See "Users and the forced password change".
  • Failed password attempts are limited per name, known or not, and an attempt past the limit is refused with too_many_attempts and the wait before anything is read or hashed; the after-sign-in hook (SetSignedInHook) is told of every session a sign-in establishes. See "Attempt limiting and the after-sign-in hook".
  • Provider-initiated (front-channel) logout is keyed by the issuer of the token the sign-in verified and the provider's session id, since a provider's session id is unique only within its issuer: an Azure sign-in records the ID token's sid claim on its session row with that issuer (ProviderSessionId, ProviderSessionIssuer), a pending sign-in carries them to the session it completes, and a regenerated session keeps them. A registration declares the issuers its tokens may come from (signin.Registration.Issuers; an Entra registration declares its one tenant's issuer, or the issuer of every tenant its Tenants slot admits), and a round trip from any other issuer is refused (internal_error). azure.Method.FrontChannelLogout() ends every live session under a declared issuer and the sid the request names, impersonations started from it included (their records end Logout), and answers 200. Entra sends the sid alone: a registration with one issuer scopes the request to it, and one serving several to whichever of its issuers live sessions carry the sid under (a provider's session id is unique within the provider, and every issuer a registration declares is the provider's). A request naming an iss is scoped to it, and refused with 400 when the registration does not declare it; a request without a sid is 400. The handler reads nothing from the browser, since Entra calls it in a frame, and a known sid under a declared issuer is its only credential. A session recorded with an id but no issuer (a session from before the issuer was recorded) is out of its reach until the person signs in again. Register its route as the application's front-channel logout URL in Entra, outside ValidateSession. An app registration takes one such URL, and the handler reaches the sessions of its own Auth: an application whose several Auths should all end at Microsoft's sign-out registers one Entra application per Auth. Sessions of the same user under another sid, or signed in by a method that reports no session id (password, Google, WorkOS), are not touched.
Users and the forced password change

The Auth has no user-management handlers of its own: an application, or a library over it, manages users through auth.API() and guards the callers. The API reads users as the store holds them (sessionstorage.SessionUser: the username, Disabled, the password hash, nil for a password-less user, PasswordChangeRequired, CreatedAt and LastSignInAt, nil before the first sign-in) and writes them by ID:

Call What it does
Users(ctx) Every user, by username.
User(ctx, id), UserByUsername(ctx, username) One user; the username is matched without regard to case.
CreateSessionUser(ctx, &CreateUserRequest{Username, Password, Disabled, PasswordChangeRequired, Email}) A user, password-less when Password is nil. PasswordChangeRequired marks a password an operator set (needs a Password).
ChangeSessionUserUsername(ctx, id, username) Renames the user and its live sessions.
ChangeSessionUserPassword(ctx, w, id, &ChangeSessionUserPasswordRequest{OldPassword, NewPassword}) The user's own change: the old password must match and the new one differ. Clears the mark, destroys the sessions and continues in a new one. PasswordMethod.ChangeUserPassword() is this over HTTP.
SetSessionUserPassword(ctx, id, password) A password the user chose through a flow of the application's own that proved who they are (a reset link, an enrollment). Clears the mark, destroys the sessions.
ResetSessionUserPassword(ctx, id, temporary) A temporary password an operator chose. Sets the mark, destroys the sessions.
HashPassword(password) The hash of a password as the users table's PasswordHash column holds it, made by the password method's hasher, for a caller that writes the column in a transaction of its own (the generated user management). An empty password is refused. SignInAttemptName(username), a package function, is the key of the name's row in the sign-in attempts table, for the same caller clearing the count beside the password.
DeactivateSessionUser, ActivateSessionUser, DeleteSessionUser, DestroyUserSessions As named; the first and the third destroy the sessions first.
Identities(ctx, id), UnlinkIdentity(ctx, identityID) The user's identity links; unlinking a password-less user's last link is refused (Conflict).
UserByEmail(ctx, email), SetSessionUserEmail(ctx, id, email) The user holding an address, verified or not; an operator's entry of an address, unverified, or its removal (nil). See "Users and their email address".
Invite(ctx, &InvitationRequest{Email, Tenant, RoleNames, InvitedBy}), Invitations(ctx), RevokeInvitation(ctx, id) An invitation mailed to an address; the invitations that stand; one withdrawn. See "Invitations".
PrepareInvitation(ctx, &InvitationRequest{…}) An invitation checked and made, and neither stored nor mailed: Row() is the mail links row for a caller that stores it in a transaction of its own (InvitationRow, whose comment says how each column is written), and Send(ctx) mails the link once that transaction has committed; a message that could not be sent withdraws the invitation. The token, the message and the sender stay in the library. Invite is the two in the Auth's own storage.

The forced password change. A password an operator set, at creation (PasswordChangeRequired) or by a reset, is temporary: the user changes it before anything else is served. While the mark is set, ValidateSession (and AuthAPI.ValidateSession) refuses every request with 403 and {"message", "code": "password_change_required"}; the session read answers, with "passwordChangeRequired": true, and the logout and the password change go through, since they validate the session on their own, which is why the three sit outside ValidateSession in the wiring above. A login page that reads the mark from the session read posts the change to the methods list's changePassword path before it opens the application. The change clears the mark, regenerates the session and records a password event; an impersonated session is the actor's and is not held to the user's mark. The seed user of a new application and every user an operator creates with a password carry the mark; the password a user chose through ChangeSessionUserPassword or SetSessionUserPassword clears it. A password-less user has nothing to change, so the mark without a password is refused.

Users and their email address

A user may hold one email address, in two states. Verified before trusted: an address is trusted for nothing until the person has proven they read it by following a link sent to it, and the user record carries the time that happened (SessionUser.EmailVerifiedAt, UserInfo.EmailVerified()). Code that sends a link may use an unverified address; code that relies on one (linking a social identity, a recovery) requires the time. No address is required of any user: an account without a verified address has no mail-based recovery, and multi-factor authentication can serve instead. The address is unique among every address held, verified or not, matched without regard to case (NormalizedEmail), so an address is held by one account at a time.

How an address gets onto a user:

  • The person adds and verifies their own, signed in: Email().Add() takes {"email"} and mails the address a link; nothing is written until the person follows it and the page posts the token to Email().Verify(), which writes the address verified, replacing whatever the user held. The link counts only for the account that asked for it, so following a link never attaches an address to an account the follower does not control. A directory's claim (Entra's user principal name, Google's address) is offered as a prefill of that step through the session read's emailHint, and never stored by it. Add answers {} whatever the address's state, so the screen reveals nothing: an address another account holds is told so by mail to that address, and an address the user already holds verified gets no mail. A mailbox is sent at most five links within fifteen minutes that go unused; the sixth is refused with too_many_emails and the wait. A link that is followed resets the count, as a sign-in code that is used does.
  • An operator enters one, unverified: CreateUserRequest.Email or SetSessionUserEmail. The entry reserves the address within the auth: a later sign-up with it is pointed at this account by mail, and the person verifies it through the same add step. An entry over a verified address leaves it unverified.
  • Google writes its own: a Google sign-in writes the address Google verified onto the user, verified at the time of the sign-in, when the user holds no verified address yet and no other user holds it (any method that asserts Identity.EmailVerified does the same; Entra does not, so an Entra user's address stays a prefill until the person verifies it). The other way round, a first Google sign-in by a person whose address a user already holds verified is that user's: the standard account rules match the user by the address once no user is under the sign-in name (see "Storage and schema" above).
  • An invitation or a sign-up proves it: the account an invited person creates, or an existing account that accepts an invitation while holding no verified address, takes the invitation's address verified; a sign-up's account is created with its address verified.

Two shapes. An application declares on the password method whether the username is the email address (session.UsernameIsEmail()), and the users table takes the matching shape:

  • Apart (the default): the username is chosen, the address is added and verified separately, and sign-in is by username. The auth set's SessionUserEmail migration creates the columns as plain columns.

  • One value (UsernameIsEmail()): the address is the username, derived from it by the database so the two cannot diverge. The login page asks for the address, a sign-up's username is the address, renaming a user is refused (ChangeSessionUserUsername: Conflict) as is an operator's entry of an address, and a person who verifies a new address is renamed to it with their live sessions, as the rename does; an application that keys anything by the username, role memberships above all, is told of that rename through auth.SetUserRenamed(func(ctx, userID, from, to) error) and moves what it holds. The store is told the shape when the method registers. The users table is created with the address columns generated from the username, in place of the migration's first two statements:

    -- Spanner
    ALTER TABLE SessionUsers ADD COLUMN Email STRING(MAX) AS (Username) STORED;
    ALTER TABLE SessionUsers ADD COLUMN NormalizedEmail STRING(MAX) AS (NORMALIZE_AND_CASEFOLD(Username)) STORED;
    -- PostgreSQL
    ALTER TABLE "SessionUsers" ADD COLUMN "Email" character varying GENERATED ALWAYS AS ("Username") STORED;
    ALTER TABLE "SessionUsers" ADD COLUMN "NormalizedEmail" character varying GENERATED ALWAYS AS (casefold(normalize("Username"))) STORED;
    

    EmailVerifiedAt, the unique index on NormalizedEmail and the index by username, which carries the address, are as the migration has them. Sign-in by address when the two are apart is not offered.

The session read (Authenticated) reports email, emailVerified and, for a user without an address, emailHint.

Invitations

An invitation is a mailed link that brings a person into the application, or into one of its tenants, with the roles it carries. It reaches anyone by address, and the actor's request is the same whether an account already holds the address or not: only the invitee's path differs, and the actor does not learn which. It is accepted only by the account it was sent to: a directory sign-in as another address, a password sign-in by an account that holds another address, and the acceptance by hand of a person signed in as such an account are refused (invitation_address), nothing consumed and the invitation left standing for the invited account. A password account that holds no address, and a sign-up with a password, accept by the link: the person proved they read the mailbox, and the account takes the address.

  • Sending: auth.API().Invite(ctx, &session.InvitationRequest{Email, Tenant, RoleNames, InvitedBy}) stores the invitation and mails the link; it stands for MailSettings.InvitationTimeout (seven days). Invitations(ctx) lists those that stand; RevokeInvitation(ctx, id) withdraws one. The tenant and the roles are the application's, opaque to the library.
  • Opening: the login page, sent to with ?invitation=<token>, posts the token to Invitation().Open(), which answers {"email", "tenant", "expiresAt", "signUp", "usernameIsEmail", "methods", "accountExists", "hasPassword"} and sets an encrypted cookie holding the token, so the sign-in that follows carries the invitation, an external round trip included. The page then offers the sign-in methods, and, when signUp is true (the password method is registered), an account with a password. methods names the listed external registrations that could admit the invitation's address, by the names the methods listing advertises them under ([] when none could; the password method is never among them), so the page hides the buttons that would refuse the invitee; accountExists and hasPassword say whether an account already holds the address and signs in with a password, so the page offers that account's password form, and offers to create an account only where none holds the address. While the cookie names an invitation that stands, the methods listing (auth.Methods) reports it as invitation.standing, so the page shows the invitation again when it comes back without the token, as after a refused external sign-in; see "What the login page is told".
  • Accepting: a sign-in that carries an invitation accepts it once the user is known, before the sign-in policy decides, so the policy sees the membership. The sign-in is first held to the address: the one it asserts, the directory's for an external identity and the account's own for a password one, must be the invited one, compared without regard to case, or the sign-in is refused before anything is read or written (invitation_address, the login page naming the invited address), the invitation standing for the account it was sent to; a password account with no address passes. The acceptance by hand of a person signed in (Invitation().Accept()) is held the same way, answered 403 with the sentence. Then the invitation is consumed, the user takes its address when they hold no verified one, and the application's hook grants what it names. Only a sign-in the resolution admitted consumes it: one the account rules refuse or hold for a confirmation, one the directory's roles refuse (no_roles), or a disabled user's leaves the invitation standing with nothing granted, and the person may sign in another way; once accepted, a sign-in the policy then denies leaves what the acceptance granted in place. The hook is set with auth.SetInvitationAccepted(func(ctx, tx, userID, username, inv) (committed func(ctx), err error)) and runs inside the transaction that consumes the invitation, which it is handed (for an external identity, the resolution's own, the one that provisions a user the invitation admits): the invitation is spent and its roles given together, or neither. The hook reads and writes through tx alone, since the Spanner emulator allows one read-write transaction at a time and a second one, or a read through another client, inside the hook waits on the transaction it runs in; a user the transaction provisioned is buffered and not readable in it, so the hook writes under the username it is given. committed, nil for none, is what the library runs once the transaction has committed and before the policy decides (the word to a permission engine that its rows changed), once, for the run of the transaction that committed. A hook that fails fails the transaction and ends the sign-in with its error: the invitation stands, and a user the sign-in would have provisioned is not created. An account Invitation().SignUp() created stays, since it is created before the sign-in that accepts the invitation. Under the invited-users-only account rule the invitation is the account the rule asks for: a stranger who carries one is provisioned under their sign-in name, and so is a stranger from a directory a tenant declares with no default seat (SetDirectoryAdmission). A person already signed in accepts with Invitation().Accept() (behind ValidateSession); an invited person creates an account with a password through Invitation().SignUp() ({"password", "username"}), which creates the user with the invitation's address verified and signs them in, the invitation accepted on the way. NewSessionRequest.Invitation carries it to the policy, with Accepted saying whether this sign-in accepted it.
  • A dead invitation (used, revoked or expired) is skipped by a sign-in the person was admitted to anyway, which goes on without a grant, and refuses one the invitation alone admitted (invitation_expired), provisioning nothing. A hook that fails ends the sign-in with its error and writes no session; the invitation stays consumed and a user it provisioned stays, so the person's next attempt at the link finds it dead and an administrator invites again.

An invitation is refused before anything is stored or mailed when no sign-in method the login page offers could admit the address, so the sender learns it now rather than the invitee at the sign-in: Invite answers a bad request reading No sign-in method of this application accepts an address at <domain>. The password method, when it is listed to Methods, admits any address, since the invited person creates an account with a password; a Google registration admits an address at a domain of its named Workspaces, any domain but gmail.com and googlemail.com under AnyWorkspace, and any under AnyGoogleAccount; a Microsoft Entra registration refuses only a personal account's address (outlook.com, hotmail.com, live.com, msn.com) unless it admits PersonalAccounts, since a tenant is not a domain; WorkOS and a method of your own that sets no signin.Method.AdmitsAddress cannot tell, which admits. Google puts the Workspace's primary domain in the hd claim, so an invitation to an address at a secondary domain of a Workspace whose primary domain alone is named is refused here although Google would admit the sign-in: name the secondary domain on the Workspace too.

Sign-up

When the password method is registered with session.OpenSignUp(), anyone may create an account: the person gives their address to SignUp().Start() ({"email"}), which mails a link standing MailSettings.LinkTimeout (a day); the login page, sent to with ?signUp=<token>, posts the token to SignUp().Open() for {"email", "usernameIsEmail"} and then, with the password the person chose (at least eight characters) and the username when the two are apart, to SignUp().Complete(), which creates the account with the address verified and signs the person in, answering as the password login does. Start answers {} whatever the address's state: an address an account already holds is pointed at that account by mail, and the screen says nothing. OpenSignUp needs mail (WithMail), and the sign-up routes are offered only with it; without OpenSignUp the handlers answer 404 and Methods refuses the block.

Attempt limiting and the after-sign-in hook

The password method limits failed attempts itself. Five wrong passwords on a name within fifteen minutes lock the name for fifteen minutes, whether a user exists under the name or not; an attempt during the lock is refused with too_many_attempts and the wait, before the user is looked up or the password hashed; the right password resets the count. The thresholds are an option of PasswordSignIn:

password := session.PasswordSignIn(auth, session.AttemptLimit(5, 15*time.Minute, 15*time.Minute))

AttemptLimit(failures, window, lock) reads: failures failed attempts on a name within window lock the name for lock. The default is the line above. The limit is at least one failure within a positive window and lock; any other panics at registration, as a misregistered method does.

What counts, and against what. Every password check the library makes is held to the limit: the login (PasswordMethod.Login()), the API's ValidateCredentials, and a pending identity's password confirmation (Pending().ConfirmWithPassword(), ConfirmPendingWithPassword), under the name the attempt names, as the users table normalizes usernames (Pat@Lakeside.edu and pat@lakeside.edu are one name). A wrong password, an unknown name and a password-less user all count, and all answer the same 401 {"message": "Invalid Credentials"} in the same time: a name with no user or no password is compared against a dummy hash the method's hasher made, so timing no longer tells an existing name from an unknown one. A matching password resets the name, as do an MFA completion (CompletePending) and a password change of any kind (ChangeSessionUserPassword, SetSessionUserPassword, ResetSessionUserPassword). Nothing locks a user an operator must unlock: the lock passes on its own, and a password change lifts it. An operator who will not wait clears it: the name's row deleted from the sign-in attempts table (the key is SignInAttemptName(username)), as the generated user management's unlock method does in a transaction of the application's, lifts the lock on every instance within five seconds, since no instance trusts what it remembers of a name for longer.

The three layers. The name's count is durable: a row of the sign-in attempts table (SessionSignInAttempts, keyed by the name, never a column on the user row), written on failures and locks only and read through a per-instance cache that trusts a record, a lock included, for five seconds, so every instance refuses a locked name and a lock cleared in the table is gone from every instance within that time. Over it, each instance holds three kinds of key in memory, in a bounded table: the name, the client's address and the login's XSRF cookie token, the cookie the XSRF guard reads (a POST without it never reaches the handler). During a name's lock every attempt on it is refused the moment it arrives, from memory, with the same answer and the remaining wait: nothing is written or hashed, and the name's row is read at most once in five seconds per instance. An early retry during a wait counts against the client's address and cookie, never against the name, so a script that ignores the wait extends its own lock while the name's stays as it was, and a person who waits is not locked out by someone hammering their name. The client's keys are each allowed ten times the name limit's failures, across names, within the window; past that the client is locked for the lock period and every retry extends it. The address is the one a proxy reports (True-Client-IP, X-Real-IP, the first X-Forwarded-For entry) or the connection's; it is a throttle, not a security boundary, since the headers are the client's to forge, and a client cycling cookies is held by the name and the address, one cycling addresses by the edge's own throttle. The cookie carries no state and nothing new is written to it. In front of it all sits the edge: a per-address throttle on the sign-in route, outside the library.

The answer. A locked name, and a held client, get 429 {"message", "code": "too_many_attempts", "retryAfter": <seconds>} with the standard Retry-After header, and nothing about the name; ValidateCredentials and ConfirmPendingWithPassword return a *sessioninfo.LoginRefusal carrying RefusedTooManyAttempts, whose wait sessioninfo.RetryAfterOf(err) reads. A login page that reads code from a refusal's body shows its sentence for too_many_attempts (and may show the wait); the external methods are not limited, since the provider checks their passwords.

The after-sign-in hook. One function per Auth, set once like the sign-in policy, is called once for every session a sign-in establishes, after the transaction that inserted it has committed: a password or external sign-in, a password confirmation, an MFA completion, a session the application started (StartAuthenticatedSession). It receives the session, its user and the auth events the session recorded, and never hears of a refused sign-in or one held for confirmation or MFA. An error from the hook is logged; the session stands. A regenerated session (a password change) and an impersonation are not sign-ins and are not reported.

auth.SetSignedInHook(func(ctx context.Context, s *session.SignedIn) error {
    return audit.SignedIn(ctx, s.UserID, s.Username, s.SessionID, s.Reason, s.Events)
})

A nil hook, a second hook, or a hook set once the Auth is in use panics, as SetSignInPolicy does: set it after NewAuth and before serving.

Machine outlets and bearer tokens

A machine outlet is a URL space of the application whose requests carry a bearer token the Auth issued, never a session cookie: the surface a command-line tool or an integration calls. The Auth issues the tokens two ways, and one middleware binds each request on the outlet to the token's person the way ValidateSession binds a browser request to its user. The outlet names the application chooses, the pages that issue and approve tokens and what each outlet serves are the application's; the library issues, stores, validates and revokes.

Registering an outlet. session.RegisterMachineOutlet(auth, name) registers the outlet and returns it; tokens are issued only for registered outlets, and a token is accepted only on the outlet it was issued for. Register every outlet after NewAuth and before serving, as sign-in methods are registered: a name that is empty or not an identifier (letters, digits, hyphens, underscores), a name registered twice, or an outlet registered once the Auth is in use panics. Route the outlet outside StartSession and wire outlet.ValidateToken on it (see "Routes").

What ValidateToken does. It reads Authorization: Bearer <token>, finds the token by its hash, requires it live (not expired, not revoked), of a bearer kind (an application or access token, never a refresh token) and issued for this outlet, loads its person as ValidateSession loads a session's user (missing or disabled: refused; under the password change mark: 403 with password_change_required, as everywhere), and binds the request: sessioninfo.UserFromCtx, sessioninfo.DataFromCtx (the session data's ID is the token's id, AuthenticatedAt its issue, AuthEvents one token event whose connection is the token's kind, Token the *sessioninfo.TokenInfo), sessioninfo.PrincipalFromCtx through the Auth's principal resolver as for a session, and sessioninfo.TokenFromCtx for the token itself. The request's log entry, every line logged within it and its span carry token.id, token.kind and token.name (an application token) or token.client (an access token), beside username and enduser.id. A refusal is 401 with WWW-Authenticate: Bearer realm="<outlet>", and error="invalid_token" when a token was presented (RFC 6750). No cookie is read or written and no XSRF token is checked: a bearer token is nothing a browser sends on its own. The token's LastUsedAt moves at most once a minute.

Application tokens are what a signed-in person issues for a program of their own. auth.ApplicationTokens() has the page's handlers, behind ValidateSession and ValidateXSRFToken: Create() takes {"name", "outlet", "expiresIn"} (expiresIn in seconds, optional, at most the Auth's application token lifetime) and answers {"id", "token", "name", "outlet", "expiresAt"} where token is the secret, shown this once and stored only as its hash; List() answers the person's live tokens, newest first, as [{"id", "kind", "name", "outlet", "clientId", "createdAt", "expiresAt", "lastUsedAt"}] (the application tokens and the device grants' tokens, never a secret); Revoke() takes {"id"} and revokes that token of theirs, a device grant's with its family (404 when the token is not theirs or not live). The API has CreateApplicationToken, Tokens, RevokeToken and RevokeUserTokens (every live token of a person, for an operator taking their access away; a disabled person's tokens are refused on their next request anyway, since the person is loaded on every request, and a deleted person's are deleted with them).

The device flow (RFC 8628) is how a command-line client obtains tokens with a person's approval and no password of its own. The client posts client_id and outlet to auth.Device().Authorize() (form-encoded or JSON; public, outside StartSession) and is told {"device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in", "interval"}; it shows the person the user code (XXXX-XXXX, letters only) and the verification URI, and polls auth.Device().Token() with grant_type=urn:ietf:params:oauth:grant-type:device_code and the device_code every interval seconds. The person, signed in to the application as always, opens the verification page (WithDeviceVerificationURL, default /device; the application's page, which reads ?userCode=), which asks auth.Device().Lookup() (?userCode=, behind ValidateSession) which client asks for which outlet and posts {"userCode"} to Approve() or Deny() (behind ValidateSession and ValidateXSRFToken); one decision stands. The next poll answers {"access_token", "token_type": "Bearer", "expires_in", "refresh_token"}, once; until then, and otherwise, it answers 400 with the RFC's codes: authorization_pending, slow_down (polled before the interval passed), access_denied, expired_token, invalid_grant (unknown, redeemed, rotated or revoked), invalid_request, unsupported_grant_type. The two public endpoints speak the RFC's wire format (snake_case, Cache-Control: no-store), so a standard client library drives them.

The access token is what the client presents on the outlet; when it expires the client posts grant_type=refresh_token with the refresh_token to the token endpoint and receives the next pair. A refresh rotates: the pair presented is revoked and the next is issued in the same family, for the same person, outlet and client. A refresh token presented again after its exchange is a reuse (a stolen copy, or a client that lost the answer): the whole family is revoked, so the holder of the current pair loses it too, and the answer is invalid_grant; the client signs in again. The API has StartDeviceAuthorization, RedeemDeviceCode, RefreshTokens, PendingDevice, ApproveDevice and DenyDevice.

Lifetimes and storage. WithTokenLifetimes(access, refresh, applicationMax) (default an hour, thirty days, a year), WithDeviceCodeLifetime(lifetime, pollInterval) (default ten minutes, five seconds) and WithDeviceVerificationURL(path) (default /device, a path in the application). Tokens and device authorizations live in SessionTokens and SessionDeviceCodes (the shipped migrations 000007 on Spanner and 000006 on PostgreSQL; WithTokensTableName, WithDeviceCodesTableName), keyed by the hash of the secret, with the person, the outlet, the kind, the family, the name or client, the issue, expiry, last use and revocation (revoked, rotated, reuse, user); a person's rows go with the person.

From a command line

A command-line program signs in to an outlet with the session/deviceflow package and calls the outlet as the person who approved it: Login runs the device flow once, Client calls the outlet, Logout forgets the sign-in.

cfg := &deviceflow.Config{
    Server: "https://app.example.com", // the application, as a browser reaches it
    Outlet: "droids",                  // the machine outlet
    Prefix: "/api",                    // where its public endpoints sit: /api/oauth/device/authorize, /api/oauth/token (default "/" + Outlet)
    Client: "corral",                  // the program's name, shown to the person who approves it
}
if err := deviceflow.Login(ctx, cfg); err != nil { // "Open https://app.example.com/device?userCode=BCDF-GHJK and approve the code BCDF-GHJK."
    …                                              // errors.Is: deviceflow.ErrDenied, deviceflow.ErrExpired; a *deviceflow.Error otherwise
}
client, err := deviceflow.Client(cfg) // an *http.Client: Authorization: Bearer … on every request
resp, err := client.Do(req)           // errors.Is(err, deviceflow.ErrSignedOut): nothing stored, or the refresh refused; Login again
_ = deviceflow.Logout(cfg)

Login asks the application for a device authorization, tells the person which address to open and which code to approve (Config.Prompt; by default two sentences on standard error, the address with the code filled in and when the code expires), polls the token endpoint at the interval the application names, five seconds longer after each slow_down, until the person decides, and stores the pair: ErrDenied when they deny it, ErrExpired when the code expires first, a *deviceflow.Error with the code and description for any other refusal. The pair is kept in tokens.json under Config.Dir, by default the program's own directory in the person's configuration directory (os.UserConfigDir() joined with Client: ~/.config/corral on Linux), the directory 0700 and the file 0600, keyed by server and outlet, so one program keeps its sign-ins to several applications in one place. Client returns an http.Client that puts the stored access token on every request, refreshes the pair first when the token expires within a minute, and, when the outlet refuses the token with invalid_token, refreshes and sends the request once more if its body can be sent again (none, or GetBody set). Every refresh holds tokens.lock beside the tokens file, and a process that finds the pair already rotated by another uses what it finds: a refresh token is presented once, never twice, since a second presentation revokes the grant. A request with no stored pair, or whose refresh the application refuses, fails with ErrSignedOut; the program calls Login again. Logout forgets the stored pair and calls nothing on the application: the person revokes the grant on their token page when they want it gone there too.

Sending mail

The library sends mail for the flows that need a link or a code in someone's mailbox: the invitation a tenant's administrator sends to an address, the link that verifies an address a person adds or changes, the link a password sign-up starts from, and the sign-in code of the second factor. It writes to one interface, mail.Sender (session/mail), and knows nothing of the mail system behind it; an application configures a driver and hands it to the Auth. A message is plain text with one link in it (mail.Message: the recipient, the subject and the body), and every message is from the one address the driver is configured to send as. A message reads as instructions: what the person did, the link to open and how long it is good for (LinkTimeout or InvitationTimeout, said as a duration such as "6 hours", since the person knows when the message reached them), then, under headings of their own, what to do if it was not them and a word to keep the link to themselves. Tests use mail.Recorder, a sender that keeps what it was asked to send.

The first driver is the Google Workspace SMTP relay, session/mail/workspace. Google Cloud has no outbound mail service of its own and blocks port 25 from every compute product, so a mail server of our own is not an option there; the relay is Google's own route. The driver submits each message to smtp-relay.gmail.com on port 587 over TLS, which Cloud Run allows, logged in as one mailbox of the organization's Workspace domain with an app password, and Google carries delivery, reputation and signing from there. The mailbox is the From address of every message, a no-reply address as a rule; where the no-reply address is an alias of a real account rather than a mailbox of its own, the account logs in and From names the alias, since Google issues no login to an alias while the relay accepts any From address in the organization's domains once the login is a real account.

sender, err := workspace.New(&workspace.Settings{
	Mailbox:     "ops@example.com",        // the Workspace account the relay is logged in to
	From:        "no-reply@example.com",   // the address every message is from; empty is the mailbox
	AppPassword: settings.MailAppPassword, // the account's app password, from the secret store
	Name:        "Harbor",                 // the display name beside the address
})

What the Workspace side needs, once per organization:

  1. The mailbox, a Workspace user such as no-reply@example.com, or a real account with no-reply@example.com as one of its alias addresses, with two-step verification turned on and an app password generated for it (the account's security settings, under two-step verification). Google issues app passwords only to accounts with two-step verification; the password stands in for the account's at the relay's login and carries no second step, which is what a service needs. Two-step verification itself protects interactive sign-ins to the mailbox and the driver never meets it.
  2. The relay service, in the admin console under Gmail routing: the SMTP relay service accepting mail from addresses in the organization's domains, with SMTP authentication required and TLS required.
  3. The secret: the app password goes into the deployment's secret store as a pinned version (bedrock refuses a release where the pin is missing). Rotating it is generating a new app password and pinning the new version; nothing in the application changes.

The Auth is given the sender with WithMail, with the application's name and the absolute URL of its login page, where every mailed link leads (?invitation=<token>, ?verify=<token>, ?signUp=<token>):

auth, err := session.NewAuth[session.NoCustomData, session.NoCustomData](store, cookieKey,
	session.WithMail(sender, session.MailSettings{Application: "Harbor", LoginURL: "https://harbor.example.com/login"}))

In development mail.Log{} stands in for a driver: it writes each message to the log, link included, and sends nothing, so the link is followed from the log. It is never configured for a deployed environment, where the links are secrets.

The relay allows a sending address ten thousand messages a day, counted apart from the mailbox's own sending. A refused login comes back in the relay's words after the driver's sentence saying what the login takes; a refused recipient and a refused message likewise. A send is given thirty seconds (Settings.Timeout), dialing included. An organization that forbids app passwords has the relay's IP allowlist (a fixed outbound address per environment) or the Gmail API with domain-wide delegation as its alternatives; neither is built.

OIDC role synchronization

Role synchronization reconciles a user's application roles to the identity provider's authorization signal on every OIDC login: role names sourced from the IdP are assigned (where a role of that name exists), roles the user holds that are NOT among them are removed, and the login is rejected unless at least one recognized role results. It is designed for organizations that manage roles centrally in the directory. The role names come from the provider's native mechanism — Azure delivers them in the token's roles claim (App Role ↔ group assignments); Google has no such claim, so the Google sign-in derives them from Google Groups membership at login (see the "Google Workspace OIDC" section). See the azure.SignIn and google.SignIn godoc for the full semantics.

A membership is written where the role is held. A global role is held in the global partition, and a domain role is held in every tenant domain, so one membership reaches every tenant, the ones that exist today and the ones created later; the sync keeps no list of tenants. A membership the directory does not name is removed wherever it is held, a membership in one tenant domain included, so an application that writes its own memberships (a tenant-specific role, say) runs with role synchronization disabled.

On an Auth session the slot is in the method's configuration, required for the two methods that synchronize: azure.Config.RoleSync takes signin.RoleSync(manager) or signin.DisableRoleSync(), and google.Config.RoleSync takes google.RoleSync(manager, groupPrefix, lookup) or google.DisableRoleSync(). session.RoleSync and session.DisableRoleSync are the same functions under the root package's name. A registration without its slot is refused (see "Registering sign-in methods").

A registration that synchronizes roles stands alone on its Auth: no password method and no other registration beside it, in either order of registration, or the Auth refuses the registration. The directory is then the authority for everyone the Auth holds, and the first sign-in through it seats the person in the roles the directory names, with nothing to seed. An application whose people come in two ways with two authorities (staff on the directory's groups, members the application seats) keeps two Auths, one per population.

entra := azure.SignIn(auth, "azure", nil, &azure.Config{
    Tenants: azure.Tenant(tenantID), ClientID: clientID, ClientSecret: clientSecret, RedirectURL: redirectURL,
    RoleSync: signin.RoleSync(userRoleManager), // or signin.DisableRoleSync(); one tenant is the shape it runs with
})

session.UserRoleManager is the role store surface the sync needs, and the access package's UserManager satisfies it. Each method names where a membership is held with an accesstypes.PolicyScope: accesstypes.GlobalPolicyScope() is the global partition and accesstypes.EveryDomainPolicyScope() is every tenant domain, the two places the sync writes. UserRoles called with no scopes lists every membership the user holds, keyed by where each is held, which is how the sync finds a stale membership in one tenant domain. ResolveRole finds the role a place holds under a name, matched without regard to case, and answers it in the spelling the store holds: a Google group is an email address and the groups lookup lowercases what it reads, so the directory names pilot where the role file spelled Pilot, and the sync compares, adds and removes in the store's spelling. A store that holds two roles differing only in case cannot answer such a name, and the access library refuses to create the pair. ResolveRole errors must be returned, never flattened to "role missing": the sync removes what the directory does not name, so a swallowed store error would delete a valid membership on a transient fault.

Migrating from the shape that took a domains provider (session.RoleSync(manager, domainsFn) and session.GoogleRoleSync(manager, domainsFn, ...)): drop the provider, since the sync no longer keeps a list of tenants, and give the manager the accesstypes.PolicyScope signatures above. Older code that passed the manager straight to NewOIDCAzure wraps it in session.RoleSync(manager), and session.DisableUserRoleManagement() becomes session.DisableRoleSync(), which also disables the at-least-one-role login gate. session.GoogleRoleSync is now google.RoleSync, in the session/google package.

Generic OpenID Connect

A provider with nothing vendor-specific about it, an identity gateway, Okta or Keycloak, is a method of the Auth session too, registered with oidc.SignIn(auth, name, rule, &oidc.Config{...}) from the session/oidc package. The Entra and Google methods exist because their tokens carry a tenant or a Workspace the method must check against the registration's slot; this one checks the issuer alone, which discovery reads the provider's configuration from and every ID token must carry. The round trip is the same authorization code flow with PKCE the other methods share.

gateway := oidc.SignIn(auth, "gateway", nil, &oidc.Config{
    Issuer:       "https://id.example.com", // discovery at Issuer/.well-known/openid-configuration; every token carries it
    ClientID:     "lanterns",
    ClientSecret: "",                       // a public client: PKCE alone, the client ID in the request body
    RedirectURL:  "https://lanterns.example.com/api/user/gateway/callback",
    Connection:   "gateway",                // the connection every link carries; the issuer URL when empty
    RoleSync:     signin.DisableRoleSync(), // or signin.RoleSync(manager), reconciled to the token's roles claim
    Accounts:     signin.InvitedUsersOnly,  // members of the directory by default
})
r.Get("/api/user/gateway/login", gateway.Login())
r.Get("/api/user/gateway/callback", gateway.Callback())

The identity is keyed by the registration's Connection and the token's sub. Its sign-in name is the preferred_username claim, or the email claim when the provider sends none, so the standard account rules provision and match users under it. The provider is the directory: whoever it authenticates is a member of it, so a first sign-in takes signin.MembersOfDirectory by default, and a registration that admits only pre-created users says signin.InvitedUsersOnly. The login route forwards ?login_hint= to the provider as its login_hint, which a gateway reads as the account to sign in, and ?prompt=select_account as its prompt. A provider that enforces a second factor at every sign-in is declared so with Attesting: true, and a sign-in through it carries the attestation by declaration; a token whose amr claim names mfa attests by evidence whatever the declaration (see "The second factor"). There is no provider-initiated logout: Logout destroys the local session only. Under the skipAuth build tag the method is simulated like the others: the callback signs in APP_<NAME>_USERNAME with the roles APP_<NAME>_ROLES names, APP_USERNAME and APP_ROLES when those are unset, under a sub derived from the username.

Microsoft Entra ID OIDC

Microsoft Entra ID sign-in is a method of the Auth session, registered with azure.SignIn(auth, name, rule, &azure.Config{...}) from the session/azure package (see "Registering sign-in methods" above). The identity is linked to its user by the tenant and the object id, the tid and oid claims, under every shape below. Its sign-in name is preferred_username, the user principal name, so the standard account rules (Config.Accounts) provision and match users under it. A guest of the tenant (a B2B guest, whose idp claim names another provider than the issuer or whose name carries #EXT#) is marked on the identity (Identity.Guest) and refused by the standard rules (guest_account); a rule of the application's own decides for itself.

Login accepts ?returnUrl= (a path in the application) and ?prompt=select_account, passed to Microsoft as its prompt so it shows its account chooser even when it holds one signed-in account it would otherwise take without asking; the login page sends it after a refusal and under "Use a different account". Any other prompt value is refused with 400.

Which accounts may sign in

Config.Tenants is required and says which Microsoft Entra tenants' accounts a registration admits. The verified ID token's tid claim selects the entry at the callback, before the account rules run, so an account the slot does not admit never reaches a row (unlisted_tenant, or personal_account for a Microsoft personal account under a work or school shape). The entry also decides the organization the standard rules store as the tenant key of the links they make (Identity.Organization); the link's connection is the tenant id under every shape.

  • One tenant, azure.Tenant("<tenant id>"): the application that belongs to one organization, as a single-tenant app registration serves it. The registration reads its provider configuration at the tenant's own endpoint, whose document names the tenant's issuer, so every token is held to it. azure.NamedTenant(id, "lakeside") gives the tenant the application's own name, stored as the tenant key in place of the id. This is the only shape role synchronization runs with, since a token's application roles are asserted by the tenant that issued it.
  • Listed tenants, azure.Tenants(azure.Tenant(...), azure.NamedTenant(...)): the tid claim selects the entry, and a tenant outside the list is refused. A tenant id is listed once and a name is used once.
  • Any tenant, azure.AnyTenant(): the work or school account of any Microsoft Entra tenant, and no personal account. The tenant key is the tenant id; name the tenants you know beside it (azure.Tenants(azure.NamedTenant(...), azure.AnyTenant())) and theirs is the name.
  • Personal accounts, azure.PersonalAccounts(): Microsoft personal accounts (outlook.com, hotmail.com, Xbox), which Microsoft issues from one consumer tenant (azure.ConsumerTenantID), alone or beside any tenant or listed tenants.
  • A tenant that attests, azure.Tenant(id).Attesting(): the application administers the tenant and declares that it enforces a second factor at every sign-in, so a sign-in through it carries the attestation by declaration and is never held for the library's code; a token whose amr names mfa attests by evidence under every shape. The declaration is for listed tenants; see "The second factor".

Several tenants, any tenant and personal accounts are served through Microsoft's shared endpoints (organizations, consumers or common, as the shape calls for), whose discovery documents name their issuer with a placeholder; the app registration must then admit accounts in any organizational directory, and personal accounts when the slot does. A shared document cannot hold a token to an issuer, so this library checks the token's issuer against the token's tenant itself, <Authority>/<tid>/v2.0, and the tenant against the slot, in the verifier and again in the method, before any user is resolved; the signature, audience and expiry are checked as always.

A first sign-in through an open entry (any tenant, personal accounts) cannot take members of the directory, which would sign up the world: the registration takes signin.InvitedUsersOnly, signin.OpenSignUp or a rule of the application's own. Open sign-up, in turn, is refused on a registration that lists its tenants only.

Config.Authority is the Microsoft identity platform the tenants live on, https://login.microsoftonline.com when empty; Azure Government tenants live at https://login.microsoftonline.us. There is no issuer setting: a tenant's issuer is <Authority>/<tenant id>/v2.0, and azure.TenantOfIssuer reads a v0.12 issuer into the authority and the tenant it names.

Provider-initiated logout

Entra calls the application's front-channel logout URL (FrontChannelLogout) with sid and iss when the person signs out of Microsoft. The handler ends every session whose sign-in carried that sid under that issuer, impersonations started from them included, and refuses an issuer of no tenant the registration admits. A registration serving one tenant supplies its issuer when the request names none; one serving several needs the iss Entra sends. See "Every session" for the design.

Google Workspace OIDC

Google Workspace sign-in is a method of the Auth session, registered with google.SignIn(auth, name, rule, &google.Config{...}) from the session/google package (see "Registering sign-in methods" above). It is the counterpart of the Azure method: the same session machinery, custom data axes and role-reconciliation semantics, built on Google's identity model instead of Entra's. The mental-model difference that drives every API difference: an Entra app registration is an authorization surface (App Roles are declared on the app, assigned to groups, and delivered in the token's roles claim), while a Google OAuth client is authentication only — the ID token says who the user is (email, sub) and which Workspace org they belong to (hd), and nothing about what they may do. Authorization signals therefore come from the directory itself (Google Groups), fetched at login.

There is no issuer or authority setting — Google operates a single issuer for all orgs; tenancy is the hd claim, not the issuer. The identity is linked to its user by its connection and the sub claim: sub is globally unique among all Google identities and never reused, and the connection is what the registration's Workspaces slot selects for the account (below). The sign-in events carry it too, so a policy tells Workspaces apart by connection and, within one, domains apart by the identity's HostedDomain.

The identity's sign-in name is the verified email claim (email_verified is enforced), so the standard account rules (Config.Accounts) provision and match users under it. Google has no end_session_endpoint and issues no sid claim, so there is no Google-initiated logout: Logout destroys the local session only. The RoleSync slot is google.RoleSync(manager, groupPrefix, lookup) or google.DisableRoleSync() (see "The group naming convention").

Which accounts may sign in

Config.Workspaces is required and says which Google accounts a registration admits. The verified ID token's hd claim, the domain of the account's Workspace, selects the entry at the callback, before the account rules run, so an account the slot does not admit never reaches a row (not_workspace_member). The entry also decides the connection written on the identity link:

  • One Workspace, google.Workspace("lakeside", "lakeside.edu", "lakeside.org"): the application that belongs to one organization. The name is the application's own name for the Workspace, written as the connection of every link made through it, since Google puts no stable organization id in the token and one Workspace answers for every domain it owns; the domains are checked against the hd claim. This is the only shape role synchronization runs with, since the group lookup reads one Workspace's directory.
  • Listed Workspaces, google.Workspaces(google.Workspace(...), google.Workspace(...)): the hd claim selects the Workspace whose domains contain it, and that Workspace's name is the connection. A domain belongs to one Workspace, and a name is used once.
  • Any Workspace, google.AnyWorkspace(): any hd claim is admitted and none is refused. The connection is the account's domain, lowercased, since the registration names no Workspace; name the Workspaces you know beside it (google.Workspaces(google.Workspace(...), google.AnyWorkspace())) and their members share one connection across their domains.
  • Any Google account, google.AnyGoogleAccount(): a token with or without an hd claim. An account outside the named Workspaces carries the connection google.AnyAccountConnection. The OAuth client's consent screen must be External and published for accounts outside your own Workspace to reach the callback; Internal restricts it to your Workspace.
  • A Workspace that attests, google.Workspace("ccc", "example.com").Attesting(): the application administers the Workspace and declares that it enforces a second factor at every sign-in (2-Step Verification enforcement), so a sign-in through it carries the attestation by declaration and is never held for the library's code. Google puts no evidence of a second factor in its tokens, so the declaration is the only way a Google sign-in attests; it is for named Workspaces, and the one to name beside an open entry. See "The second factor".

A first sign-in through an open entry (any Workspace, any Google account) cannot take members of the directory, which would sign up the world: the registration takes signin.InvitedUsersOnly, signin.OpenSignUp or a rule of the application's own. Open sign-up, in turn, is refused on a registration that names its Workspaces only.

The connection is a key. Renaming a Workspace, or moving from any Workspace (where the domain is the connection) to a named one, makes every sign-in from it arrive as an unknown identity until the links are re-keyed:

UPDATE SessionIdentities SET "Connection" = 'new' WHERE "Method" = 'google' AND "Connection" = 'old'

Two layers restrict an application to your own organization: the OAuth client's Internal consent screen (Google refuses users outside the org with an org_internal error before they reach the callback) and the one-Workspace slot, the trusted backstop even with the consent screen in place.

Skipping Google's account chooser

With one Workspace on one domain the authorization request hints that domain, and Google skips its account chooser when exactly one signed-in account is in it; with several domains, several Workspaces or any Workspace it hints any Workspace account, and the chooser appears whenever more than one Workspace account is signed in; with any Google account it hints nothing. Login accepts ?login_hint=<email> beside returnUrl and passes it to Google as login_hint: Google picks that account when it is signed in and pre-fills the sign-in form otherwise, so an identifier-first login page (the person types their email, the page picks the registration) skips the chooser whatever the registration's shape. It is a hint and is never read back; the identity comes from the verified token. A hint longer than 254 characters, or carrying spaces or control characters, is refused with 400.

The opposite is wanted after a refusal: Google holding one signed-in account of the hinted domain signs it in again without asking, so a person refused with the wrong account (not_invited, say) would be sent round the same loop on every press of the button. Login accepts ?prompt=select_account and passes it to Google as its prompt, which makes Google show its account chooser whatever it holds; the login page sends it after a refusal and under "Use a different account", and nothing on an ordinary visit. Any other prompt value is refused with 400. A person who cancels at the chooser comes back to the callback with error=access_denied, which is refused token_exchange_failed before any exchange (see "The redirect and response contract").

The group naming convention

google.RoleSync derives candidate role names from group emails: a group whose local part is the configured prefix followed by a role name maps to that role, everything else is ignored. With prefix app-myapp-:

Group email Candidate role
app-myapp-admin@example.com admin
app-myapp-viewer@example.com viewer
team-eng@example.com — (no prefix)
app-otherapp-admin@example.com — (other app)

The candidates then flow through the same reconcile logic as Azure's token roles: names for which a role exists are assigned, held roles not among them are removed, and the login is rejected unless at least one recognized role results. Group emails are lowercase, so the candidate names are lowercase; the store resolves each without regard to case (ResolveRole) and the sync writes the role in the store's spelling, so the application's roles keep whatever spelling they have.

Membership is read at login through Google's Cloud Identity Groups API, with the signing-in person's own access token. An access token is the credential that lets the application call a Google API as that person. The library gets it by asking for one extra OAuth scope, in addition to openid, email and profile: https://www.googleapis.com/auth/cloud-identity.groups.readonly. A scope names one permission the application asks the person for. The token is used for the lookup once and never stored. No administrator credential is involved: no service account (a Google user for software rather than a person), no domain-wide delegation (a setting that lets such a user act as anyone in the organization), and no admin role.

The last argument of google.RoleSync is a google.GroupLookup, which sets how far the lookup reaches. It has two values:

  • google.DirectGroups() (the default): one call. Only the groups the person is directly assigned to count, however the directory is nested (role groups should then hold people, not other groups — matching Entra's direct-only App Role resolution).
  • google.NestedGroups(): the groups those groups are in count too, level by level, up to 10 levels. Each level is one round of calls to Google, so a deeply nested directory makes login slower. DirectGroups restores the one call.

google.ParseGroupLookup(value) reads the setting from configuration: direct or nested, in any letter case, with surrounding space ignored. An empty value means DirectGroups. Any other value is an error, so a misspelled setting stops the application when it constructs its auth.

Google returns only the groups whose member list the person may view. A group whose member list the person may not view is hidden: Google leaves it out, so that one membership does not count. A hidden group never fails the lookup; the login goes ahead with the groups Google returned. Two rules follow for your organization's groups:

  • A group grants a role only if its who can view members setting includes the group's members.
  • With NestedGroups, a hidden group hides everything above it, because the lookup cannot pass through it to the groups it is in.

A groups-lookup failure fails the login — the same posture as a role-store error.

The simulated sign-in (skipAuth)

Built with the skipAuth build tag, the Azure and Google methods contact no provider: the login route sends the browser straight to the callback, and the callback signs in the person the environment names, with the roles it names. APP_USERNAME is the person (the Azure preferred_username, the Google verified email) and APP_ROLES the roles, comma-separated (the Azure roles claim, the Google groups the simulated lookup answers). A registration reads its own pair first, APP_<NAME>_USERNAME and APP_<NAME>_ROLES, with the registration's name upper-cased and every character outside letters and digits written as an underscore (lakeside-entra reads APP_LAKESIDE_ENTRA_USERNAME), and the shared pair when its own is unset. An application with one registration sets the shared pair alone; one with several in one process (a console's google beside a portal's directory) gives each its own person. The tag is for development: a skipAuth binary admits whoever the environment names.

Login refusal codes

A refused redirect-based sign-in (an Auth session's Azure, Google or WorkOS method) returns the browser to the login page with the reason as a code, never as text: <LoginURL>?code=<code>; the password login and the pending handlers answer the same codes in JSON (see "The redirect and response contract"). The page maps the code to a sentence it holds itself and shows nothing for a code it does not know, so nothing that arrives in the URL is ever displayed. LoginURL is the method's Config.LoginURL; its Login() and Callback() redirect there, and code is the only query key a refusal writes.

The codes are typed constants in sessioninfo (sessioninfo.LoginRefusalCode), and the table is the wire contract:

Code Constant Produced when
internal_error RefusedInternalError A fault the module does not classify: the authorization URL could not be built, the claims payload would not decode, the role store or session store failed, or a resolver error is neither a LoginRefusal nor a client message.
login_refused RefusedByApplication The application's custom session data resolver refused the login with an httpio client message and no code. The message goes to the log.
no_oidc_cookie RefusedNoOIDCCookie The callback arrived without the cookie the login route set.
invalid_state RefusedInvalidState The callback's state does not match the login this browser started.
invalid_pkce RefusedInvalidPKCE The login cookie carries no usable PKCE verifier.
token_exchange_failed RefusedTokenExchange The provider refused to exchange the authorization code for tokens.
no_id_token RefusedNoIDToken The token response carried no id_token.
verify_id_token_failed RefusedIDTokenVerification The ID token failed signature, issuer, audience, or expiry verification; under an Entra shape served through a shared endpoint, a token whose issuer is not its tenant's or that names no tenant.
parse_claims_failed RefusedClaimsParse The verified ID token's claims would not decode.
not_workspace_member RefusedNotWorkspaceMember Google: the user is outside the Workspace domain logins are restricted to.
unlisted_tenant RefusedUnlistedTenant Entra: the token's tenant is outside the registration's Tenants slot.
personal_account RefusedPersonalAccount Entra: a Microsoft personal account under a registration that admits work or school accounts only.
email_not_verified RefusedEmailNotVerified Google: the user's email address is not verified.
organization_mismatch RefusedOrganizationMismatch WorkOS: the profile belongs to another organization than the login requested.
no_roles RefusedNoRoles The directory asserted no role the application recognizes: refused before anything is resolved or written, or by role synchronization once the session stood, for a method that cannot tell beforehand.
no_email_claim RefusedNoEmailClaim Google: the ID token carries no email claim.
identity_rejected RefusedIdentityRejected Auth: the account rule rejected the identity (its own code wins when it sets one), linked a user that has a password without confirmation, a password-less user who signs in through another connection was matched or linked without trust, provisioned a new user for an identity whose verified address another user holds verified, or the identity resolved to another user than it waited on.
not_invited RefusedNotInvited Auth: under the invited-users-only account rule, no user was created for the identity's sign-in name.
invitation_only RefusedInvitationOnly Auth: a stranger from a directory a tenant declares with no default seat (SetDirectoryAdmission), carrying no invitation; nothing is written.
invitation_expired RefusedInvitationExpired Auth: under the invited-users-only account rule, the invitation the sign-in carried, which alone admitted the person, had expired or been used by the time the sign-in accepted it; nothing is provisioned.
invitation_address RefusedInvitationAddress Auth: a sign-in or an acceptance by hand carried an invitation mailed to another address than the one it asserts (the directory's, or the account's own); refused before anything is read or written, the invitation left standing. An account that holds no address accepts by the link. The login page names the invited address and asks for a sign-in with that account.
guest_account RefusedGuestAccount Auth: the identity is a guest of its directory (an Entra B2B guest), which the standard account rules refuse.
policy_denied RefusedByPolicy Auth: the sign-in policy denied the sign-in (its own code wins when it sets one).
user_disabled RefusedUserDisabled Auth: the sign-in resolved to a disabled user.
pending_expired RefusedPendingExpired Auth: a confirmation or MFA step arrived after its pending identity expired or was used.
no_email RefusedNoEmail The external identity carries no email address where one is required: an application's rule asks for one, or a standard account rule found no sign-in name to use as the username.
password_change_required RefusedPasswordChangeRequired Auth: the signed-in user must change a password an operator set; answered with 403 by ValidateSession on every request but the password change, the session read and the logout, until the change (see "Users and the forced password change").
no_tenant RefusedNoTenant Auth, the tenant policy: the person is a member of no tenant, and the policy was not built with signin.AdmitWithoutTenant().
connection_not_in_tenant RefusedConnectionNotInTenant Auth, the tenant policy: the sign-in came through a directory (its method and connection) that no tenant of the person declares.
directory_only RefusedDirectoryOnly Auth, the tenant policy: a sign-in that is not through a directory (a password, a session the application started itself) by a person whose every tenant admits its people through their directories only.
too_many_attempts RefusedTooManyAttempts Auth: a password attempt on a name whose failed attempts reached the limit, or from a client held for its own; answered with 429, the wait in seconds as retryAfter and the Retry-After header, until the lock passes (see "Attempt limiting and the after-sign-in hook").
too_many_emails RefusedTooManyEmails Auth: a sixth sign-in code or link asked for one address within fifteen minutes while the five before it went unused (a code or link that is used resets the count); answered with 429, the wait in seconds as retryAfter and the Retry-After header, until the lock passes.
invalid_code RefusedInvalidCode Auth: the sign-in code entered is not the one sent; the code stands with one fewer attempt (see "The second factor").
code_expired RefusedCodeExpired Auth: a sign-in code entered while none stands: none was sent, or the one sent expired, was used or took its last attempt; the page asks for a new one.

The resolver rule. A custom session data resolver's error decides the code by its shape. A sessioninfo.LoginRefusal (sessioninfo.NewLoginRefusal(code, cause)) answers its code, and the code may be the application's own — LoginRefusalCode("not_provisioned") — as long as the application's login page holds text for it. An httpio client message with no code answers login_refused, and its text stays in the log. Any other error answers internal_error. LoginRefusal unwraps to its cause, so the log handler still sees the client message's status and errors.Is still matches the cause.

func resolve(ctx context.Context, txn *spanner.ReadWriteTransaction, req *sessioninfo.NewSessionRequest) (*SessionClaims, error) {
    member, err := lookUpMember(ctx, txn, req.Username)
    if err != nil {
        return nil, errors.Wrap(err, "lookUpMember()") // internal_error
    }
    if member == nil {
        return nil, sessioninfo.NewLoginRefusal("not_provisioned", httpio.NewForbiddenMessage("member is not provisioned"))
    }

    return &SessionClaims{...}, nil
}

The page authors all text. A login page reads code and renders the sentence it holds for it; it never renders the parameter. Angular applications get the mapping from @impulseframework/resource-angular: LOGIN_MESSAGES holds a sentence for every code above, UiCoreService.loginMessage(code) looks one up (empty for an unknown code) and publishLoginError(code) raises it as a notification, and provideLoginMessages({...}) in the application's providers adds the application's own codes or rewords a default.

Custom session data

Custom session data attaches app-specific values to a session — a selected tenant, a role snapshot, an impersonation context. The values live in a table you own (one row per session), are written when the session is created, and are available to every request for the life of the session.

How it works:

  • One struct declares your data. Each tagged field of your struct T maps to a column in your table (spanner:"TenantId" / db:"TenantId"). The library reflects over T once at startup to derive the columns — there is no hand-written decoder and no column list to maintain.

  • A resolver writes it — once, at creation. Your resolver runs inside the same transaction that inserts the session row (login, external auth, session regeneration) and returns the *T to store, committed atomically with the session. If it returns an error, the login fails: no session, no cookies. For an Auth sign-in it runs after the user resolution has committed (see "Auth sessions"); a pending identity has no session row, so nothing is resolved until it completes.

  • Every request reads it — automatically. Session validation fetches the custom row together with the session (a single LEFT JOIN query) and your handlers get a typed T back with auth.API().CustomData(ctx). No second round-trip, no manual decoding.

  • Mid-session changes are deliberate. UpdateCustomSessionData is a transactional read-modify-write: a typed callback mutates the current row and the full row is written back. It exists for changing state mid-flight (a tenant switcher) — never for initial population.

  • Everything is checked at startup. The session type is generic over the same struct (Auth[MyData, ...]), and construction verifies the storage's custom data configuration was built for it. Misconfiguration is a boot failure, not a request-time surprise; a resolver typed to the other driver's transaction does not compile.

  • Cleanup is the database's job. Sessions are marked expired in place; your ON DELETE CASCADE foreign key removes the custom row whenever a session row is deleted. Regeneration (e.g. a password change) re-resolves fresh — updates don't carry over.

That is the whole model: declare with tags, resolve once, read typed, update deliberately. Everything below is reference detail.

One boundary before the details: this is session data — born with the session, reset when the session is regenerated, gone when the session dies. Durable facts about the person (profile fields, provisioning state) belong with the user record — see the "Custom user data" section below and docs/data-storage-guidance.md.

Schema requirements

You create the table. The contract:

  • A primary-key column named SessionId that is a foreign key to the session table's primary key with ON DELETE CASCADE.
  • Never tag a field SessionId — it is implied and reserved.
  • The resolver (or per-call data) writes the full row from T, so every tagged field is always written — plan NOT NULL constraints accordingly.
  • Columns that can hold NULL must map to nullable Go types (Spanner: spanner.NullString and friends, or pointers; Postgres: pointer fields). Scanning a NULL into a non-nullable field is a request-failing error.
-- Spanner
CREATE TABLE SessionCustomData (
    SessionId STRING(36) NOT NULL,
    TenantId  STRING(36),
    RoleId    STRING(MAX),
    CONSTRAINT FK_SessionCustomData_Sessions FOREIGN KEY (SessionId)
        REFERENCES Sessions(Id) ON DELETE CASCADE,
) PRIMARY KEY (SessionId);
The struct-tag contract

The library never introspects your schema. The same identifiers must agree in two places:

  1. Your DDL — the physical columns.
  2. T's struct tags — the spanner:"..." (Spanner) or db:"..." (Postgres) tag on each exported field names its column. An untagged exported field uses the field name; a - tag skips the field; embedded structs contribute their promoted fields.

The derived columns drive the SELECT c.<name> list on every read and the INSERT columns at creation. Names are validated for shape at construction (letter/underscore start, ≤128 chars), but whether they exist in your table is discovered by the database — a mismatch surfaces as a query error.

Configuration — Auth

An Auth store takes one custom session data configuration. The struct, the table name and the resolver are declared together with NewCustomSessionData; T and the store's transaction type are inferred from the resolver, and the transaction type selects the driver and the tags that name the columns (db:"..." for PostgreSQL, spanner:"..." for Spanner). The configuration is attached with the store's WithCustomSessionData, which takes only a configuration typed to that store's transaction: one built for the other driver does not compile there. The session type is built for the same T:

type MyData struct {
    TenantID string `db:"TenantId"`
    RoleID   string `db:"RoleId"`
}

sessionData, err := sessionstorage.NewCustomSessionData(
    "SessionCustomData",
    func(ctx context.Context, tx pgx.Tx, req *sessioninfo.NewSessionRequest) (*MyData, error) {
        // Runs ONCE per session creation, inside the transaction that inserts the
        // session, after the user resolution: req.UserID is the user (one the
        // resolver just provisioned included) and req.User says how it was found.
        member, err := loadMember(ctx, tx, req.UserID)   // reads are tx-consistent
        if err != nil {
            return nil, err                             // aborts the sign-in
        }
        return &MyData{TenantID: member.TenantID, RoleID: member.RoleID}, nil
    },
)
if err != nil { /* non-struct T, no persistable fields, invalid identifier, reserved SessionId, ... */ }

store := sessionstorage.NewPostgresAuth(pool, sessionstorage.WithAuthEvents(events)).
    WithCustomSessionData(sessionData)
auth, err := session.NewAuth[MyData, session.NoCustomData](store, cookieKey, signInPolicy)

With a nil resolver, name both types: NewCustomSessionData[MyData, pgx.Tx]("SessionCustomData", nil); session creation then performs a plain insert, and custom data comes only from per-call values (below) or UpdateCustomSessionData. A Spanner store takes a resolver over *spanner.ReadWriteTransaction and reads spanner:"..." tags; a struct tagged for both drivers serves either.

Reading the data in handlers
data, err := auth.API().CustomData(ctx)                    // returns MyData
// or, without the session type in scope:
data, err := sessioninfo.CustomDataFromCtx[*MyData](ctx)   // note: pointer type

The context stores a *T (pointer to the config's struct type), so CustomDataFromCtx must be instantiated with the pointer type; API().CustomData hides this and returns the value. Because the read is a LEFT JOIN, a session with no custom row still loads — it yields a zero-value T, not an error.

Per-call custom data

When the values come from the request rather than from config-time logic, pass the row directly at session creation — written atomically with the insert, and the configured resolver is skipped for that creation (per-call data wins):

// Auth: a session the application authenticated itself, by user ID, recording how
// (decided like a login: the sign-in policy answers when one is set):
sessionID, err := auth.API().StartAuthenticatedSession(ctx, w, userID,
    []sessioninfo.AuthEvent{{Method: "api-key"}},
    &MyData{TenantID: tenantID, RoleID: roleID},
)

// Preauth (trust-the-caller):
sessionID, err := preauth.API().Login(ctx, w, username,
    &MyData{TenantID: tenantID},
)

At most one value may be passed — it is the complete custom data row. Per-call data requires a custom session data configuration on the storage (the config may have a nil resolver). Passing data with no configuration attached is an error before anything is inserted.

Mid-session updates

Some session state legitimately changes while the session is alive — the canonical case is a tenant switcher: the resolver records the user's default tenant at login, and the user later selects a different one. That is what UpdateCustomSessionData is for:

err := auth.API().UpdateCustomSessionData(ctx, sessionID, func(data *MyData) error {
    data.TenantID = newTenantID

    return nil
})

It is available on every session API: AuthAPI and PreauthAPI.

Semantics to know:

  • It is a transactional read-modify-write. The current row is read (zero-value T when the session has no row yet), your callback mutates it, and the full row is written back — fields you don't touch are preserved, because they ride along in data. A callback error aborts the transaction with nothing written. Concurrent updates are serialized by the transaction; last committed callback wins.
  • It takes effect on the next request — the per-request read picks up the new values; requests already in flight see the old ones.
  • The library does not authorize the change. The resolver established what the user was granted at login; before writing a switch, your handler must verify the user is allowed the new value (e.g. is a member of the target tenant).
  • Updates do not survive regeneration. A password change re-resolves fresh and the selected value reverts to the resolver's answer (see Session regeneration).
  • Expired sessions are rejected; a custom data configuration must be attached.

The rule of thumb for choosing the verb: resolve for identity-derived state (what the user is at login), update for user-chosen context within already-granted options (which tenant they're looking at), and regenerate/destroy for privilege changes — if a user's rights change, kill their sessions rather than patching them (DestroyUserSessions on Auth); the next login re-resolves.

Never use UpdateCustomSessionData for initial population — that belongs in the creation transaction (resolver or per-call data), which is atomic with the session insert.

Session regeneration

A password change destroys all of the user's sessions and starts a fresh one for the caller (session-fixation protection). Custom session data is resolved fresh for the new session — the resolver runs again with Reason: ReasonRegeneration — and values previously written via UpdateCustomSessionData do not carry over. If losing a value on regeneration feels like data loss, it was user data, not session data — see docs/data-storage-guidance.md.

Where failures surface
Misconfiguration / failure Surfaces as
Non-struct T, no persistable fields, invalid tag identifier, reserved SessionId, duplicate columns Error from the config constructor, at startup
Session type's T doesn't match the storage config's T (or no config attached) Error from the session-type constructor, at startup
Wrong-backend config on a storage constructor Compile error
Resolver returns an error Session creation aborts atomically: no session row, no custom row, no cookies; login fails (OIDC: redirect to the login page with a refusal code, see "Login refusal codes")
Per-call data with no config attached, or more than one per-call value Error before any insert
Column name not in your DDL Database error from the creation transaction (aborts atomically) or from the per-request query
NULL column scanned into a non-nullable field The request fails (401) — map nullable columns to nullable Go types
UpdateCustomSessionData callback returns an error Transaction aborts; nothing written
UpdateCustomSessionData on an expired session Rejected (bad request); the row is not written
Session has no custom row Not a failure: reads yield a zero-value T (LEFT JOIN)

Custom user data

Custom user data is the durable counterpart of custom session data: app-defined values attached to the user record — a locale, provisioning state, profile fields synced from the IdP. Where session data is born and dies with one login, user data survives logout, session expiry, and regeneration, and dies with the user (your ON DELETE CASCADE FK removes it when the user row is deleted).

The mechanism mirrors custom session data deliberately — declare with tags, one validated config unit per backend, typed reads, transactional RMW updates — with two differences that follow from durability:

  • Reads are on demand, never per-request. User data is not joined into the session read and never appears in the request context; fetch it when you need it with API().CustomUserData(ctx, userID). A user with no row yields a zero-value U.
  • The write path depends on the auth mode, because the modes learn about users differently:
    • Auth: initial data is per-call on CreateSessionUser, written atomically with the user insert, or written by a custom account rule's signin.Provision hook in the sign-in's transaction for a user it provisions. There is no login hook: an identity's claims reach the rule, which decides what to keep.
    • Preauth: unsupported — there is no user record to anchor durable data to (construction error if configured).
Schema requirements

Identical to the session-data contract with one substitution: the primary-key column is named UserId and is a foreign key with ON DELETE CASCADE to SessionUsers(Id). Never tag a field UserId — it is implied and reserved. Nullable columns must map to nullable Go types.

-- Spanner, password auth
CREATE TABLE UserCustomData (
    UserId  STRING(36) NOT NULL,
    Locale  STRING(MAX),
    Theme   STRING(MAX),
    CONSTRAINT FK_UserCustomData_SessionUsers FOREIGN KEY (UserId)
        REFERENCES SessionUsers(Id) ON DELETE CASCADE,
) PRIMARY KEY (UserId);
Configuration — Auth

An Auth store takes one custom user data configuration, which fits either driver: NewCustomUserData validates the columns U's db:"..." tags name for PostgreSQL and its spanner:"..." tags name for Spanner, and the store's WithCustomUserData attaches it. The session type is built for the same U:

type UserData struct {
    Locale string `db:"Locale" spanner:"Locale"`
    Theme  string `db:"Theme" spanner:"Theme"`
}

userData, err := sessionstorage.NewCustomUserData[UserData]("UserCustomData")

store := sessionstorage.NewPostgresAuth(pool, sessionstorage.WithAuthEvents(events)).
    WithCustomSessionData(sessionData).
    WithCustomUserData(userData)
auth, err := session.NewAuth[MyData, UserData](store, cookieKey, signInPolicy)

// Create: initial data lands atomically with the user insert (at most one value —
// it is the complete row). Omit it for a plain insert (reads yield zero-value U).
id, err := auth.API().CreateSessionUser(ctx, req, &UserData{Locale: "en-AU"})

// Read: on demand, by user ID — never from the session context.
u, err := auth.API().CustomUserData(ctx, userID)

// Update: transactional read-modify-write — mutate the current row (zero-value U
// when none) and the full row is written back.
err = auth.API().UpdateCustomUserData(ctx, userID, func(d *UserData) error {
    d.Theme = "dark"
    return nil
})
Where failures surface
Misconfiguration / failure Surfaces as
Non-struct U, invalid tag identifier, reserved UserId, duplicate columns Error from the config constructor, at startup
Session type's U doesn't match the storage config's U (or no config attached) Error from the session-type constructor, at startup
Custom user data on OIDC storage without WithOIDCUsers() Error from NewOIDCAzure, at startup
Login hook on password-auth storage, or any user data config on preauth storage Error from the session-type constructor, at startup
WithOIDCUsers() on password-auth or preauth storage Error from the session-type constructor, at startup
Missing tid/oid claim with the anchor enabled Login aborts: no anchor row, no user data, no session, no cookies
Login hook returns an error Login aborts atomically (anchor upsert included)
Per-call data on CreateSessionUser with no config attached, or more than one value Error before any insert
UpdateCustomUserData for a user ID that doesn't exist Not-found error; nothing written
User has no custom row Not a failure: reads and RMW yield a zero-value U

Impersonated sessions

An impersonated session operates as a principal other than the person who authenticated: as another user (support staff seeing the application exactly as that user does, usually read-only) or as a role (an administrator working under a role chosen for the session). Every session type supports both, Auth and Preauth, through the same ImpersonationRequest on each API().

The model rests on two identities that are never conflated:

  • Actor — who authenticated. Constant for the session's life; the identity audit and attribution always name.
  • Principal — what permission checks evaluate against (accesstypes.UserPrincipal or accesstypes.RolePrincipal).

A session is a session. Once established, an impersonated session flows through ValidateSession, sessioninfo, custom session data and every handler exactly as an ordinary session does. The session's Username is its effective identity: the impersonated user for a user principal (so every consumer sees precisely what that user would see), or the actor for a role principal (nobody's identity is borrowed). The impersonation record — not the username — is what marks the session as impersonated, and only the way the session is established is new.

Enabling

Create the record table from the shipped DDL (schema/{spanner,postgresql}/impersonation/migrations) and attach it to the storage. The table deliberately has no foreign key to the session table: the record is evidence and outlives the session; retention is the application's policy.

imp, err := sessionstorage.NewImpersonationTable("SessionImpersonations")

auth, err := session.NewAuth[MyData, session.NoCustomData](
    sessionstorage.NewSpannerAuth(client,
        sessionstorage.WithAuthEvents(events),
        sessionstorage.WithImpersonation(imp)).
        WithCustomSessionData(sessionData),
    cookieKey, signInPolicy,
    session.WithImpersonationTimeout(time.Hour),        // hard cap; default one hour
    session.WithImpersonationAudit(func(ctx context.Context, e sessioninfo.ImpersonationEvent) error {
        return auditTrail.Record(ctx, e)                 // Started, Ended, IdentityOperationBlocked
    }),
)

The same WithImpersonation option and WithImpersonationTimeout / WithImpersonationAudit session options apply to NewPreauth. Without WithImpersonation nothing changes: no session is ever impersonated and the impersonation APIs return a configuration error.

Establishing a session

The establishing call runs in the target application's session API, typically from a server-to-server handoff (an admin application minting a session in a partner portal):

// Support views bob's portal, read-only, for an hour at most.
id, err := auth.API().StartImpersonatedSession(ctx, w, &session.ImpersonationRequest{
    Actor:      "alice@example.com",
    ActorRealm: "admin-portal",
    Principal:  accesstypes.UserPrincipal("bob@partner.org"),
    Mask:       accesstypes.MaskPermissions(accesstypes.List, accesstypes.Read),
    Reason:     "ticket JRN-123",
})

// An administrator of the admin application works the partner portal under a role.
id, err := auth.API().StartImpersonatedSession(ctx, w, &session.ImpersonationRequest{
    Actor:      "alice@example.com",
    ActorRealm: "admin-portal",
    Principal:  accesstypes.RolePrincipal("PartnerViewer"),
}, &MyData{PartnerID: partnerID}) // custom session data rides along as usual

// A user of this application acts under a narrower role for a while — their own
// session, narrowed. The actor is local: no realm, and their own session as the source.
// The call arrives on their validated session, so SourceSessionID may be omitted: it
// defaults to that session, and Actor must be that session's user.
info := sessioninfo.FromCtx(ctx)
id, err := auth.API().StartImpersonatedSession(ctx, w, &session.ImpersonationRequest{
    Actor:     info.Username,
    Principal: accesstypes.RolePrincipal("Auditor"),
})

The session row and the record are written in one transaction; the cookie is set only after the Started event has been delivered (a failing audit hook destroys the session and fails the call). Refused everywhere: a missing actor or principal, a caller that is itself an impersonated session (no chaining), and a local actor whose SourceSessionID is missing or is not their own live session here.

When the call arrives on a validated session of this application (the context has passed ValidateSession), the request is bound to that session: Actor must be its user, SourceSessionID must be it (and defaults to it when omitted), and ActorRealm must be empty — an actor logged in here is local. The binding keeps a caller from minting a session as another user by naming them and one of their session IDs, which appear in logs, spans and ActiveImpersonations. A call with no session in its context (a server-to-server handoff) is taken at its word, so its handler must authenticate the caller. Who may impersonate whom is the application's guard — the library records what happened.

Identity by session type

A role principal's session is always the actor's: nobody's identity is borrowed. What a user principal resolves to depends on what the session type knows about users:

Session type User principal becomes User ID Refused
Auth The SessionUsers record's username; the session belongs to that user and records an impersonation auth event naming the actor The record's ID A missing or disabled user
Preauth The name as given Zero — (trust-the-caller, as Login is)

On an Auth session an impersonation carries no identity of its own: no identity is linked, no roles are synchronized, and the custom session data resolver receives ReasonImpersonation with no claims. A provider-initiated logout reaches it through the session it was started from: azure.Method.FrontChannelLogout() ends the impersonations started from a session under the sid it names (their records end Logout) and no other (see "Every session").

Local and foreign actors

ActorRealm says where the actor was authenticated, and it decides what the actor's name means in this application's session table:

Local actor (ActorRealm empty) Foreign actor (ActorRealm set)
Who A user of this application, logged in here Authenticated by another application or IdP
SourceSessionID Required and verified: the actor's own live, non-impersonated session here, carrying their username. Defaults to the request's own session when the call arrives on one Optional; the session in the source application, for correlation
A role principal's session The actor's own session, narrowed to the role A session under a borrowed name
Kept alive The source session's activity is refreshed with the impersonated session's, so EndImpersonation can return to it —
Deactivating or renaming the user named Actor Includes the role session and every impersonation the actor holds (see One name, one user) Never touches the role session

Minting an impersonated session in the same application the actor is logged into replaces the browser's session cookie — which is why the source session is verified, kept alive, and returned to.

What the session carries

Every validated request exposes the record without branching on whether the session is impersonated:

principal := sessioninfo.PrincipalFromCtx(ctx) // UserPrincipal(username) for an ordinary session
actor     := sessioninfo.ActorFromCtx(ctx)     // == Username unless impersonated
mask      := sessioninfo.MaskFromCtx(ctx)      // unrestricted unless impersonated
imp, ok   := sessioninfo.ImpersonationFromCtx(ctx)

A permission check honors the mask by asking it before asking policy — sessioninfo.MaskFromCtx(ctx).Allows(perm) — and picks the check by the principal's kind (Role() → CheckRoleResources, otherwise CheckUserResources). Forgetting the mask fails open, so prefer a shared implementation over hand-rolling it per application.

Choosing the principal

By default a session's principal is its user, or the impersonation record's principal, and for almost every application that is the end of the story: put role membership in the permission store, check with ForUser, and a role change is enforced on the user's next request. WithPrincipalResolver exists for the narrow case where a session's subject genuinely is not a user. The resolver runs inside session validation, with the session, its custom data and its impersonation record in the context, and returns the principal PrincipalFromCtx reports for the request.

The resolver chooses which subject, never which grants. Grants always come from the permission store at check time. The moment a resolver reads role membership from somewhere that was copied at login, the application has built a cache of its authorization model with a lifetime of one session, and no amount of live grant checking repairs that.

Intended uses
  • Machine and API-key sessions. The caller is a service, not a person; the subject is the service's role, decided from the credential the session was established with.
  • Membership that lives outside the permission store and is read live. The resolver asks the external system on each request (or through a cache with a deliberate, short TTL that the application owns and documents). Staleness is bounded by that TTL, not by the session.
// A service session acts as the role bound to its API key. The key-to-role binding is
// read on every request, so revoking or re-binding the key takes effect immediately.
auth, err := session.NewPreauth[APIKeySession](storage, cookieKey,
    session.WithPrincipalResolver(func(ctx context.Context) (accesstypes.Principal, error) {
        data, err := sessioninfo.CustomDataFromCtx[*APIKeySession](ctx)
        if err != nil {
            return accesstypes.Principal{}, err
        }
        role, err := keys.RoleForKey(ctx, data.KeyID) // live lookup, not a stored copy
        if err != nil {
            return accesstypes.Principal{}, err
        }

        return accesstypes.RolePrincipal(role), nil
    }),
)
Not for this
  • A role snapshotted into custom session data at login. RolePrincipal(data.RoleID) where RoleID was resolved when the session was created is the anti-pattern this section exists to name. The user keeps the old role until they log in again; an administrator's change is silently ignored for the life of every open session. The fix is not a resolver — it is moving membership into the permission store (AddUserRoles / DeleteUserRoles) and letting the default user principal do its job.
  • "The user picked a role for this session." That is a deliberate, time-capped act by an actor, which is what the impersonation record is for: establish a role-principal impersonation with the user as actor and you get evidence, a hard cap, listing and revocation. A resolver gives you none of those.
  • Avoiding a permission-store write. If the only reason to reach for the resolver is that membership is stored somewhere else and nobody wants to move it, move it.
Mechanics
  • The choice is made per request at validation and never stored; nothing changes in the schema and no impersonation record is written.
  • The resolver runs for ordinary sessions and for user-principal impersonations — an impersonated user's session acts as that user's session would. A role-principal impersonation already names its subject and skips the resolver.
  • Returning the zero Principal keeps the default. An error fails the request as a server error, not an unauthorized one: the session is valid; the application could not decide what it acts as.
  • When the resolver changes the principal, the request's log entry and trace span carry principal.kind and principal (sessioninfo.AttrPrincipalKind, sessioninfo.AttrPrincipal); unchanged requests carry nothing extra.
Evidence

Everything an impersonated session touches names the actor and the principal:

Evidence Where
The record (actor, realm, source session, principal, mask, reason, started/expires/ended, end reason) The impersonation table, durable
impersonation.actor, .actor_realm, .principal_kind, .principal, .mask, .session_id, .source_session_id The request-level log entry and every line logged within the request (constants in sessioninfo)
principal.kind, principal — when a WithPrincipalResolver changed the request's subject The request-level log entry and every line logged within the request
Started / Ended / IdentityOperationBlocked / WriteBlocked events Structured log lines, span events (impersonation.Started, …) on the current trace span, plus the WithImpersonationAudit hook
enduser.id (the session's username), the same impersonation.* attributes, and principal.* when a resolver changed the subject The request's server span from the ValidateSession middleware (the caller's current span from ValidateSessionAPI), impersonation attributes set before any refusal so a refused request's trace still names the actor; the establishing call's own span on the source side
The establishing call's own log entry The source application's request log
impersonation object in the Authenticated() response For the frontend to banner the session and render read-only affordances
Lifecycle and guards
  • Hard cap. ExpiresAt is fixed at establishment (WithImpersonationTimeout, default one hour, shortened per call by MaxDuration); idle renewal never extends past it. The idle session timeout applies independently.

  • Ending. Logout, the hard cap, idle expiry, EndImpersonation, and DestroyUserSessions all end the record with a reason (Logout, Expired, Released, Revoked); an Auth session's Azure front-channel logout ends the records of the impersonations it reaches Logout. API().DestroyImpersonatedSessions(ctx, actor), on every session type, is the offboarding and incident tool: it expires every live impersonated session an actor established.

  • Returning to self. EndImpersonation (a handler on every session type, routed inside the validated group; API().EndImpersonation(ctx, w) beside it) ends the impersonated session Released and, for a local actor whose own session is still live, not itself impersonated, and still theirs, gives the response that session's cookies: the actor is back in their own session without logging in. The body says whether that happened ({"restored": true}); when it did not, send the actor to login. The hard cap is a hard boundary — a session past it is refused at validation before any handler runs, so a frontend offers return to self before expiresAt from the Authenticated() response, or warns and calls it as the cap nears. The route is a POST, so it sits outside any group carrying EnforceReadOnlyMask (see Read-only middleware).

    r.Group(func(r chi.Router) {
        r.Use(auth.ValidateSession, auth.ValidateXSRFToken)
        r.Post("/impersonation/end", auth.EndImpersonation())
    })
    
  • Validation (Auth). A user principal's record is looked up like any session's — a disabled impersonated user ends the session. A foreign actor's role principal has no local user: no record is looked up and UserFromCtx carries the actor's username with the zero ID, so self-referential checks (cannot delete yourself) go inert, correctly. A local actor's role principal is their own session, so their record is looked up as usual — a disabled actor's role session ends with their others. Preauth validates an impersonated session exactly as any other.

  • Identity operations. The library's own handlers refuse under impersonation: ChangeUserPassword (the password method's on Auth) always, since it would alter the impersonated user's credentials. Each refusal is an IdentityOperationBlocked event. On Auth the user operations are AuthAPI methods behind the application's own handlers, which guard them.

  • One name, one user. A role principal's session carries the actor's own username, in the same session table as the application's real users. For a local actor that name is their user, and the two username-keyed store operations treat everything under it as theirs: DestroyAllUserSessions expires their own sessions, their role sessions, and every impersonation they hold as a local actor under other names, ending the records Revoked; the session rename on ChangeUsername renames their role sessions and moves their live records to the new name. For a foreign actor the name is borrowed, so password auth refuses a role principal when that name is already a SessionUsers user (the actor logs in as that user, or impersonates it as a user principal), and the two operations never touch a session carrying a live foreign role-principal record — a user created later under that name cannot reach the actor's session either. On Auth the same holds by user ID: DestroyUserSessions ends the user's own sessions under any username, the user-principal impersonations of them and every impersonation they hold as a local actor. Preauth and the legacy OIDC type have no username-keyed user to collide with; the legacy FrontChannelLogout is username-keyed all the same, and makes no exception for a foreign role session (see Identity by session type). This is the store-level complement of the authorization rule: under a role principal the subject is the role, and application policy must not key row conditions on the session username.

  • Listing. API().ActiveImpersonations(ctx, q), on every session type, lists the impersonated sessions that are live right now, newest first — the admin surface's view of who is acting as whom. Active means: the record has not ended, the hard cap has not passed, the session row is not expired, and the session has seen activity within the idle session timeout. q (*session.ImpersonationQuery) narrows by Actor and/or Principal; nil lists everything.

    API().DestroyImpersonatedSession(ctx, sessionID) is the action on a row: it expires that session and ends its record Revoked in one transaction, so the next request on it is refused. Who may list or revoke is the application's guard.

    imps, err := auth.API().ActiveImpersonations(ctx, &session.ImpersonationQuery{Actor: "alice@example.com"})
    err = auth.API().DestroyImpersonatedSession(ctx, imps[0].SessionID)
    
  • Read-only middleware. EnforceReadOnlyMask (on every session type, after ValidateSession) refuses non-safe requests — anything but GET, HEAD, OPTIONS and TRACE — from a session whose mask is read-only: restricted, and allowing nothing beyond List and Read. The refusal is 403 with a WriteBlocked event naming the method and path. It is an opt-in backstop that keeps a read-only session away from every mutating handler whether or not that handler consults the mask; it does not replace honoring the mask in permission checks (Execute reaches handlers by POST, and a mask including Execute is not read-only). Ending a session is never a safe method either — EndImpersonation is a POST, Logout a POST or DELETE — so the EndImpersonation route (and Logout) must be mounted outside the group that carries the backstop, in a validated group of their own, or a read-only view-as session could never end itself.

    // Ending a session is never a safe method: these stay out from under the backstop.
    r.Group(func(r chi.Router) {
        r.Use(auth.ValidateSession, auth.ValidateXSRFToken)
        r.Post("/impersonation/end", auth.EndImpersonation())
        r.Delete("/session", auth.Logout())
    })
    // Everything else a read-only session may reach is under it.
    r.Group(func(r chi.Router) {
        r.Use(auth.ValidateSession, auth.ValidateXSRFToken, auth.EnforceReadOnlyMask)
        // ...
    })
    
Created and maintained by the CCC team.

Documentation

Overview

Package session provides cookie-backed sessions for web applications.

Auth is the session: one cookie, one session table and one middleware chain that any registered sign-in method can establish. The password method lives here (PasswordSignIn); the redirect-based methods are their own packages, built on the signin contract: azure (Microsoft Entra ID), google (Google Workspace) and workos (WorkOS SSO). Preauth lets an application bring its own authentication and still use the session handlers.

OIDCAzure and PasswordAuth are the legacy single-method session types, kept for the applications that still run on them; new applications use Auth.

Every session type supports custom session data: an app-defined table whose row is resolved atomically inside the session-insert transaction (or supplied per call), decoded on every authenticated request, reset on session regeneration, and cleaned up with the session via the table's ON DELETE CASCADE. See the "Custom session data" section of the README for the full lifecycle, schema contract, and failure semantics.

Auth, password auth and the legacy OIDC type additionally support custom user data: an app-defined table keyed by the durable user record (SessionUsers, or the library-managed OIDCUsers anchor for the legacy OIDC type), written atomically with user creation or login and read on demand — it survives logout, expiry, and regeneration, and dies with the user. See the "Custom user data" and "OIDC user anchor" sections of the README.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SignInAttemptName added in v0.3.0

func SignInAttemptName(username string) string

SignInAttemptName returns the name a username's failed sign-ins are counted under: the key of its row in the sign-in attempts table (Tables.SignInAttempts), the username in Unicode NFC and case-folded, as the users table normalizes usernames. A caller that clears a name's count in a transaction of its own (the generated user management) deletes the row of this key; a name with no row has no count.

Types

type AdvertisedMethod

type AdvertisedMethod struct {
	// Name is the name the method was registered under on the Auth ("password", or
	// the application's name for an external registration).
	Name string
	// Label is what the page shows for the method.
	Label string
	// Path is the path the method's Login handler is mounted at, a path in the
	// application in canonical form (see SanitizeReturnURL): /api/user/google/login.
	Path string
}

AdvertisedMethod is one method of a MethodList.

type ApplicationTokenHandlers

type ApplicationTokenHandlers struct {
	// contains filtered or unexported fields
}

ApplicationTokenHandlers are the HTTP handlers of a person's application tokens: the page where they issue, list and revoke tokens for programs of their own.

func (*ApplicationTokenHandlers) Create

Create accepts {"name", "outlet", "expiresIn"} from the signed-in person, expiresIn in seconds and optional, and issues an application token for the outlet as them. It answers {"id", "token", "name", "outlet", "expiresAt"}: token is the secret, shown this once. An outlet that is not registered, a missing name or a lifetime past the Auth's is 400. Route it behind ValidateSession and ValidateXSRFToken.

func (*ApplicationTokenHandlers) List

List answers the signed-in person's live tokens, newest first, as [{"id", "kind", "name", "outlet", "clientId", "createdAt", "expiresAt", "lastUsedAt"}]: their application tokens and the tokens of their device grants, never a secret. Route it behind ValidateSession.

func (*ApplicationTokenHandlers) Revoke

Revoke accepts {"id"} from the signed-in person and revokes that token of theirs, a device grant's with its family. It answers {}; a token that is not theirs or not live is 404. Route it behind ValidateSession and ValidateXSRFToken.

type ApplicationTokenRequest

type ApplicationTokenRequest struct {
	// UserID is the person the token acts as.
	UserID impulse.UUID
	// Outlet is the registered machine outlet the token is for.
	Outlet string
	// Name is what the person calls the token, so they recognize it in their listing.
	Name string
	// ExpiresIn is how long the token lives, at most the Auth's application token
	// lifetime; zero takes that lifetime.
	ExpiresIn time.Duration
}

ApplicationTokenRequest is what a person asks for when they issue an application token.

type Auth

type Auth[SessionData, UserData, Tx any] struct {
	// contains filtered or unexported fields
}

Auth is one session type that any registered sign-in method can establish. Auth, sessions, cookies, XSRF, custom data, impersonation and the middleware work the same for every method.

Register sign-in methods with PasswordSignIn, azure.SignIn and google.SignIn after NewAuth and before serving the first request (workos.SignIn once WorkOS returns to the public API in v0.13.1). Each returns the method's handlers.

Every session belongs to a user (SessionUsers). A sign-in either establishes a session under a new session ID, becomes a pending identity that waits for a password confirmation or the application's MFA step, or is refused with a sessioninfo.LoginRefusalCode. See the README's "Auth sessions (multiple sign-in methods)" for the routes and the redirect contract.

Tx is the storage's transaction type (pgx.Tx, *spanner.ReadWriteTransaction), taken from the storage NewAuth is given. The sign-in policy and every external method's user resolver receive it, so a hook written for the other backend does not compile.

func NewAuth

func NewAuth[SessionData, UserData, Tx any](
	storage sessionstorage.AuthStore[Tx], cookieKey string, options ...AuthOption,
) (*Auth[SessionData, UserData, Tx], error)

NewAuth creates an Auth session for the given storage. The storage's custom session and user data configurations must be built for SessionData and UserData. The OIDC-only storage features (the OIDC user anchor and the custom user data login hook) are refused. Tx is inferred from the storage: an application writes NewAuth[SessionData, UserData](store, cookieKey, options...).

A sign-in is decided by the library's own checks: the user exists and is enabled, the identity is linked or resolved, roles reconcile. An application with rules of its own sets a sign-in policy with SetSignInPolicy. Each external method's first sign-in rule is given to that method's registration. cookieKey: A Base64-encoded string representing at least 32 bytes of cryptographically secure random data.

func (*Auth[S, U, Tx]) API

func (a *Auth[S, U, Tx]) API() *AuthAPI[S, U, Tx]

API provides programmatic access to the Auth session.

func (*Auth[S, U, Tx]) ApplicationTokens

func (a *Auth[S, U, Tx]) ApplicationTokens() *ApplicationTokenHandlers

ApplicationTokens returns the application token handlers.

func (*Auth[S, U, Tx]) Authenticated

func (a *Auth[S, U, Tx]) Authenticated() http.HandlerFunc

Authenticated answers {"authenticated", "username", "passwordChangeRequired", "email", "emailVerified", "emailHint", "impersonation"}. A session whose user is missing or disabled is reported as not authenticated. passwordChangeRequired is set while the user must change a password an operator set (see "Users and the forced password change" in the README): the session read is answered under the mark, so the login page can show the change form. email is the user's address when they hold one, with emailVerified saying whether they have proven it; emailHint, present when the user holds no address, is the address a directory asserted at a sign-in, offered as a prefill for the add-address step and trusted for nothing.

func (*Auth[S, U, Tx]) Device

func (a *Auth[S, U, Tx]) Device() *DeviceHandlers

Device returns the device flow's handlers.

func (*Auth[S, U, Tx]) Email

func (a *Auth[S, U, Tx]) Email() *EmailHandlers

Email returns the email address handlers. It panics on an Auth without mail, as a wiring mistake.

func (*Auth[S, U, Tx]) EndImpersonation

func (a *Auth[S, U, Tx]) EndImpersonation() http.HandlerFunc

EndImpersonation ends the current impersonated session.

func (*Auth[S, U, Tx]) EnforceReadOnlyMask

func (a *Auth[S, U, Tx]) EnforceReadOnlyMask(next http.Handler) http.Handler

EnforceReadOnlyMask refuses writes from read-only impersonated sessions.

func (*Auth[S, U, Tx]) Invitation

func (a *Auth[S, U, Tx]) Invitation() *InvitationHandlers

Invitation returns the invitation handlers.

func (*Auth[S, U, Tx]) Logout

func (a *Auth[S, U, Tx]) Logout() http.HandlerFunc

Logout destroys the current session.

func (*Auth[S, U, Tx]) Methods

func (a *Auth[S, U, Tx]) Methods(list *MethodList) http.HandlerFunc

Methods answers the login page with the sign-in methods it offers: for each listed method its name, the method behind it, how it starts (a form for the password method, a redirect for an external one), its label and its path, in the list's order, the pending sign-in routes when the list names them, and the password change route when the password method is listed. When the list names the invitation routes and the browser carries a live invitation (the cookie Invitation().Open() set), the invitation block also reports it under "standing": the address it was sent to, its tenant, when it stops being accepted, whether an account created from it takes the address as its username, and the names of the listed external registrations that could admit the address (see Invitation().Open()), so a page that arrives without the mailed link's token, as it does when an external sign-in was refused and sent it back, still shows the invitation and hides the methods that would refuse the person. A browser without the cookie, or whose invitation is no longer live, gets the block without it. The answer is public: route it beside the login routes, behind StartSession and before ValidateSession, and it needs no XSRF token.

{"methods": [{"name": "password", "method": "password", "kind": "password", "label": "Password", "path": "/api/user/password/login"},
             {"name": "google", "method": "google", "kind": "redirect", "label": "Google", "path": "/api/user/google/login"}],
 "pending": {"status": "/api/user/pending", "confirm": "/api/user/pending/confirm", "cancel": "/api/user/pending/cancel"},
 "changePassword": "/api/user/password",
 "invitation": {"open": "/api/user/invitation", "accept": "/api/user/invitation/accept", "signUp": "/api/user/invitation/sign-up",
                "standing": {"email": "pat@lakeside.edu", "tenant": "", "expiresAt": "2026-10-31T20:00:00Z", "usernameIsEmail": false, "methods": ["google"]}}}

Methods is called where the routes are wired, after every method is registered, and panics on a wiring mistake, the way a registration does: an empty list, a method that is not registered on this Auth, a name listed twice, a method without a label or with a path that is not a canonical path in the application, a pending block with some of its paths, the password method without the password change route, or that route without the password method.

func (*Auth[S, U, Tx]) Pending

func (a *Auth[S, U, Tx]) Pending() *PendingHandlers

Pending returns the pending-identity handlers.

func (*Auth[S, U, Tx]) RegisterExternal

func (a *Auth[S, U, Tx]) RegisterExternal(reg *signin.Registration[Tx]) signin.Handlers

RegisterExternal registers a redirect-based sign-in method under its registration's name and returns its handlers. It implements signin.Core: the method packages (azure, google; workos under internal until v0.13.1) reach it through signin.Register, so an application never calls it directly. It panics on a registration rule, as refuseRegistration documents, when the registration has neither a standard account rule nor a custom one, when it names a standard rule that does not exist, and when a registration that synchronizes roles would stand beside another method, as refuseBeside documents.

func (*Auth[SessionData, UserData, Tx]) SetDirectoryAdmission

func (a *Auth[SessionData, UserData, Tx]) SetDirectoryAdmission(reader signin.DirectoryReader[Tx], roles signin.UserRoleManager, hook DirectorySeatedHook[Tx])

SetDirectoryAdmission sets what a tenanted application gives a first sign-in through a directory by a person no user was created for: reader, which reads every tenant's declaration of the directory the identity came through (signin.DirectoryReader); roles, the role store the person's memberships are read from (signin.UserRoleManager, the access library's user manager the tenant policy reads too); and hook, which seats the person with the default seats the declarations name. With them the standard account rules ask the tenants first: a directory some tenant declares belongs to that tenant, and its declaration decides before the registration's own rule. A person who already holds a membership under the sign-in name in a declaring tenant, or as the application's staff, is that tenant's person and is admitted; a default seat admits a stranger with it; and a declaration naming none refuses a stranger by invitation only (invitation_only, unless the sign-in carries an invitation), with no account created. A directory no tenant declares falls to the registration's rule as without them. Set the three after NewAuth and before serving the first request; a nil reader, roles or hook, a second call, or a call once the Auth is in use is a wiring mistake and panics, as SetSignInPolicy does.

func (*Auth[SessionData, UserData, Tx]) SetInvitationAccepted

func (a *Auth[SessionData, UserData, Tx]) SetInvitationAccepted(hook InvitationAcceptedHook[Tx])

SetInvitationAccepted sets the application's invitation acceptor, the hook that grants what an invitation names when it is accepted. An Auth that sends invitations (AuthAPI.Invite) needs one, or an acceptance grants nothing. Set it after NewAuth and before serving the first request; a nil hook, a second hook, or a hook set once the Auth is in use is a wiring mistake and panics, as SetSignInPolicy does.

func (*Auth[SessionData, UserData, Tx]) SetSignInPolicy

func (a *Auth[SessionData, UserData, Tx]) SetSignInPolicy(policy signin.Policy[Tx])

SetSignInPolicy sets the application's sign-in rule: asked once a sign-in's user is known and before any session exists, for every sign-in method and for a session the application starts for a user it authenticated itself (AuthAPI.StartAuthenticatedSession), with signin.Allow, signin.Deny or signin.RequireMFA. Without a policy the library's own checks decide. Set it after NewAuth and before serving the first request; a nil policy, a second policy, or a policy set once the Auth is in use is a wiring mistake and panics, as a misregistered sign-in method does.

func (*Auth[SessionData, UserData, Tx]) SetSignedInHook

func (a *Auth[SessionData, UserData, Tx]) SetSignedInHook(hook SignedInHook)

SetSignedInHook sets the application's after-sign-in hook, called once for every session a sign-in establishes, whatever the method, after the transaction that inserted it has committed, with the user and the sign-in's events; never for a refusal or a sign-in held for confirmation or MFA. An error from the hook is logged and the session stands. Set it after NewAuth and before serving the first request; a nil hook, a second hook, or a hook set once the Auth is in use is a wiring mistake and panics, as SetSignInPolicy does.

func (*Auth[SessionData, UserData, Tx]) SetUserRenamed

func (a *Auth[SessionData, UserData, Tx]) SetUserRenamed(hook UserRenamedHook)

SetUserRenamed sets the hook a rename the library performs is reported to. An application whose password method declares UsernameIsEmail and that keys memberships by username needs one. Set it after NewAuth and before serving the first request; a nil hook, a second hook, or a hook set once the Auth is in use panics.

func (*Auth[S, U, Tx]) SetXSRFToken

func (a *Auth[S, U, Tx]) SetXSRFToken(next http.Handler) http.Handler

SetXSRFToken sets the XSRF token.

func (*Auth[S, U, Tx]) SignUp

func (a *Auth[S, U, Tx]) SignUp() *SignUpHandlers

SignUp returns the sign-up handlers. It panics on an Auth without mail, as a wiring mistake; whether sign-up is offered is the password method's (OpenSignUp), checked as each request arrives.

func (*Auth[S, U, Tx]) StartSession

func (a *Auth[S, U, Tx]) StartSession(next http.Handler) http.Handler

StartSession restores or initializes the session. It also makes the browser's pending identity, if any, available to the Pending handlers and the AuthAPI pending methods, and the invitation and the trusted device the browser carries to the sign-in.

func (*Auth[S, U, Tx]) ValidateSession

func (a *Auth[S, U, Tx]) ValidateSession(next http.Handler) http.Handler

ValidateSession validates the session and loads its user by UserId. A session with no user, or whose user is missing or disabled, is refused with 401. The user is available through sessioninfo.UserFromCtx. A foreign actor's role-principal impersonation has no user and carries only its username. A user who must change a password an operator set is refused with 403 and {"message", "code": "password_change_required"} until the change: route the password change, the session read and the logout outside this middleware, since they validate on their own and are what the user reaches meanwhile. An impersonated session is not held to the mark.

func (*Auth[S, U, Tx]) ValidateXSRFToken

func (a *Auth[S, U, Tx]) ValidateXSRFToken(next http.Handler) http.Handler

ValidateXSRFToken validates the XSRF token.

type AuthAPI

type AuthAPI[SessionData, UserData, Tx any] struct {
	// contains filtered or unexported fields
}

AuthAPI provides programmatic access to an Auth session.

func (*AuthAPI[S, U, Tx]) ActivateSessionUser

func (p *AuthAPI[S, U, Tx]) ActivateSessionUser(ctx context.Context, userID impulse.UUID) error

ActivateSessionUser enables a user.

func (*AuthAPI[S, U, Tx]) ActiveImpersonations

func (p *AuthAPI[S, U, Tx]) ActiveImpersonations(ctx context.Context, q *ImpersonationQuery) ([]*sessioninfo.Impersonation, error)

ActiveImpersonations lists active impersonations matching q.

func (*AuthAPI[S, U, Tx]) ApproveDevice

func (p *AuthAPI[S, U, Tx]) ApproveDevice(ctx context.Context, userID impulse.UUID, userCode string) error

ApproveDevice records that userID approved the device authorization the person's code names; the client's next poll receives the pair as that person. A code that names no pending authorization is NotFound, so one decision stands.

func (*AuthAPI[S, U, Tx]) ChangeSessionUserPassword

func (p *AuthAPI[S, U, Tx]) ChangeSessionUserPassword(ctx context.Context, w http.ResponseWriter, userID impulse.UUID, req *ChangeSessionUserPasswordRequest) error

ChangeSessionUserPassword changes a user's password to one the user chose and regenerates its session.

The old password must match and the new one must differ from it (BadRequest otherwise). The password change mark is cleared, every session of the user is destroyed, by UserId, and the caller continues in a new session (ReasonRegeneration) that records a password event.

func (*AuthAPI[S, U, Tx]) ChangeSessionUserUsername

func (p *AuthAPI[S, U, Tx]) ChangeSessionUserUsername(ctx context.Context, userID impulse.UUID, username string) error

ChangeSessionUserUsername changes a user's username, and atomically the username on its live sessions.

func (*AuthAPI[S, U, Tx]) CompletePending

func (p *AuthAPI[S, U, Tx]) CompletePending(ctx context.Context, w http.ResponseWriter, stepUp ...sessioninfo.AuthEvent) (impulse.UUID, error)

CompletePending finishes a pending identity after the application's MFA step. It records the step-up events, links the identity if needed, starts the session, and regenerates the session ID.

The pending identity must wait for MFA (Conflict otherwise). It is consumed first, so it completes once: a second completion finds it expired. The user is resolved again and must be the one the identity waited on, and the sign-in policy is asked again with the sign-in's events and stepUp on the request: a RequireMFA those events satisfy proceeds, a Deny refuses the completion (no session; the pending identity is consumed), and a RequireMFA for a factor the person did not give holds the sign-in again. The session records the sign-in's events followed by stepUp. If the sign-in must wait again (the resolver now asks for a confirmation, or the policy for another factor), the error is a *signin.PendingSignInError and the pending identity is replaced.

func (*AuthAPI[S, U, Tx]) ConfirmPendingWithPassword

func (p *AuthAPI[S, U, Tx]) ConfirmPendingWithPassword(ctx context.Context, w http.ResponseWriter, password string) (impulse.UUID, error)

ConfirmPendingWithPassword checks the password of the pending identity's user, links the identity, calls the IdentityLinked hook, and starts the session.

The pending identity must wait for a password confirmation (Conflict otherwise). A wrong password is Unauthorized and leaves the pending identity in place; the right one consumes it. The check is limited as a login's is, under the user's name: a wrong password counts, and a name whose attempts reached the limit is refused with RefusedTooManyAttempts and the wait before the password is hashed. The session records the sign-in's event and a link-confirmation event. If the sign-in policy requires MFA after the link, no session starts. The error is then a *signin.PendingSignInError with reason PendingMFA, and a new pending identity waits for MFA (see CompletePending).

func (*AuthAPI[S, U, Tx]) Cookie

func (p *AuthAPI[S, U, Tx]) Cookie() *cookie.Client

Cookie returns the underlying cookie client.

func (*AuthAPI[S, U, Tx]) CreateApplicationToken

func (p *AuthAPI[S, U, Tx]) CreateApplicationToken(ctx context.Context, req *ApplicationTokenRequest) (*IssuedToken, error)

CreateApplicationToken issues an application token for req: the secret is returned this once, and the store keeps its hash. The outlet must be registered (RegisterMachineOutlet), the name set and at most 200 characters, the lifetime at most the Auth's application token lifetime, and the user there and enabled; otherwise the request is refused with 400, or 404 for an unknown user.

func (*AuthAPI[S, U, Tx]) CreateSessionUser

func (p *AuthAPI[S, U, Tx]) CreateSessionUser(ctx context.Context, req *CreateUserRequest, customData ...*U) (impulse.UUID, error)

CreateSessionUser creates a user. A nil req.Password creates a password-less user. req.PasswordChangeRequired marks the password as one an operator set, which the user changes before anything else is served; a user without a password has nothing to change, so the mark without a password is a BadRequest. req.Email, when given, is written unverified and reserves the address; one another user holds is a Conflict.

func (*AuthAPI[S, U, Tx]) CustomData

func (p *AuthAPI[S, U, Tx]) CustomData(ctx context.Context) (S, error)

CustomData returns the current session's custom data.

func (*AuthAPI[S, U, Tx]) CustomUserData

func (p *AuthAPI[S, U, Tx]) CustomUserData(ctx context.Context, userID impulse.UUID) (U, error)

CustomUserData returns a user's custom user data.

func (*AuthAPI[S, U, Tx]) DeactivateSessionUser

func (p *AuthAPI[S, U, Tx]) DeactivateSessionUser(ctx context.Context, userID impulse.UUID) error

DeactivateSessionUser disables a user and destroys its sessions. The caller must guard against self-deactivation.

func (*AuthAPI[S, U, Tx]) DeleteSessionUser

func (p *AuthAPI[S, U, Tx]) DeleteSessionUser(ctx context.Context, userID impulse.UUID) error

DeleteSessionUser deletes a user with its identity links and sessions. The sessions are destroyed first, by UserId, so a failed delete leaves no live session behind. The caller must guard against self-deletion.

func (*AuthAPI[S, U, Tx]) DenyDevice

func (p *AuthAPI[S, U, Tx]) DenyDevice(ctx context.Context, userCode string) error

DenyDevice records that the person denied the device authorization their code names; the client's next poll is told so. A code that names no pending authorization is NotFound.

func (*AuthAPI[S, U, Tx]) DestroyImpersonatedSession

func (p *AuthAPI[S, U, Tx]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error

DestroyImpersonatedSession expires one impersonated session.

func (*AuthAPI[S, U, Tx]) DestroyImpersonatedSessions

func (p *AuthAPI[S, U, Tx]) DestroyImpersonatedSessions(ctx context.Context, actor string) error

DestroyImpersonatedSessions expires every impersonated session started by actor.

func (*AuthAPI[S, U, Tx]) DestroyUserSessions

func (p *AuthAPI[S, U, Tx]) DestroyUserSessions(ctx context.Context, userID impulse.UUID) error

DestroyUserSessions expires every session of a user.

func (*AuthAPI[S, U, Tx]) EndImpersonation

func (p *AuthAPI[S, U, Tx]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)

EndImpersonation ends the current impersonated session, restoring the actor's session when possible.

func (*AuthAPI[S, U, Tx]) EnrollEmail

func (p *AuthAPI[S, U, Tx]) EnrollEmail(ctx context.Context, email string) error

EnrollEmail mails the code to email for a pending identity whose user holds no address; the address is written on the user, verified, when the code is entered. A user who holds an address is refused (Conflict). An address another account holds is told so by mail, and the call returns as if sent. See SendEmailCode.

func (*AuthAPI[S, U, Tx]) ForgetTrustedDevice

func (p *AuthAPI[S, U, Tx]) ForgetTrustedDevice(ctx context.Context, w http.ResponseWriter) error

ForgetTrustedDevice forgets the browser of the current request as a trusted device of the session's user: their device is revoked and their entry taken out of the cookie, so their next sign-in from it asks for the factor; the other people the browser was remembered for keep theirs. It reads the session StartSession validated, and a browser that is no trusted device of the user is left as it is.

func (*AuthAPI[S, U, Tx]) HashPassword added in v0.3.0

func (p *AuthAPI[S, U, Tx]) HashPassword(password string) (string, error)

HashPassword hashes a password with the password method's hasher and answers the hash as the users table's PasswordHash column holds it. It is for a caller that writes the column in a transaction of its own (the generated user management, which sets a temporary password beside its other writes); the session library's own writers (ResetSessionUserPassword, CreateSessionUser) hash for themselves. An empty password is refused: no password is an absent hash, never the hash of nothing.

func (*AuthAPI[S, U, Tx]) Identities

func (p *AuthAPI[S, U, Tx]) Identities(ctx context.Context, userID impulse.UUID) ([]*sessionstorage.SessionIdentity, error)

Identities lists a user's linked external identities.

func (*AuthAPI[S, U, Tx]) Invitations

func (p *AuthAPI[S, U, Tx]) Invitations(ctx context.Context) ([]*sessioninfo.Invitation, error)

Invitations lists the invitations that stand: sent, not accepted, not revoked and not expired, oldest first.

func (*AuthAPI[S, U, Tx]) Invite

func (p *AuthAPI[S, U, Tx]) Invite(ctx context.Context, req *InvitationRequest) (*sessioninfo.Invitation, error)

Invite sends an invitation to req.Email: a link to the login page that stands for MailSettings.InvitationTimeout, which whoever follows it accepts by signing in or signing up. The request is the same whether an account holds the address or not; only the invitee's path differs, and the caller does not learn which. An address that no sign-in method the login page offers could admit (an address outside the Google Workspaces a registration names, say, with no password method offered) is refused with a message naming its domain, and nothing is stored or mailed, so the sender learns now what the invitee would learn at the sign-in. The invitation is returned as stored; a message that could not be sent is an error and the invitation is withdrawn. It needs mail (WithMail).

func (*AuthAPI[S, U, Tx]) Logout

func (p *AuthAPI[S, U, Tx]) Logout(ctx context.Context) error

Logout destroys the current session.

func (*AuthAPI[S, U, Tx]) PendingDevice

func (p *AuthAPI[S, U, Tx]) PendingDevice(ctx context.Context, userCode string) (*sessionstorage.DeviceCode, error)

PendingDevice returns the device authorization the person's code names while it waits for their decision, its hash left out, so the approval page can say which client asks for which outlet. A code that names no pending authorization is NotFound.

func (*AuthAPI[S, U, Tx]) PendingIdentity

func (p *AuthAPI[S, U, Tx]) PendingIdentity(ctx context.Context) (*sessioninfo.PendingIdentity, error)

PendingIdentity returns the pending identity of the current request, or a NotFound error. An expired one is a sessioninfo.RefusedPendingExpired refusal. It reads the pending identity StartSession found, so the route must run behind StartSession.

func (*AuthAPI[S, U, Tx]) PrepareInvitation added in v0.3.0

func (p *AuthAPI[S, U, Tx]) PrepareInvitation(ctx context.Context, req *InvitationRequest) (PreparedInvitation, error)

PrepareInvitation checks and makes an invitation to req.Email without storing or mailing it: the checks Invite makes (the Auth sends mail, the address is one, and a sign-in method the login page offers could admit it), the token and its hash, and the time the link stands for (MailSettings.InvitationTimeout). The caller stores the row (PreparedInvitation.Row) in a transaction of its own and, once that has committed, mails the link (PreparedInvitation.Send). Invite is the two in the Auth's own storage.

func (*AuthAPI[S, U, Tx]) RedeemDeviceCode

func (p *AuthAPI[S, U, Tx]) RedeemDeviceCode(ctx context.Context, deviceCode string) (*TokenPair, sessionstorage.DeviceCodeStatus, error)

RedeemDeviceCode is the client's poll of its device authorization: the pair once the person approved it, with status DeviceApproved, and once only; otherwise no pair and the status, DevicePending while the person has not decided, DeviceSlowDown when the client polled before the interval passed, DeviceDenied, or DeviceExpired. A device code that is unknown or was redeemed already is NotFound.

func (*AuthAPI[S, U, Tx]) RefreshTokens

func (p *AuthAPI[S, U, Tx]) RefreshTokens(ctx context.Context, refreshToken string) (*TokenPair, error)

RefreshTokens exchanges a refresh token for the next pair: the one presented is revoked and the pair is issued in its family, for its person, outlet and client. A token that is not a live refresh token is NotFound. A refresh token presented again after its exchange is a reuse: the whole family is revoked, so the client that holds the current pair loses it too, and the error is sessionstorage.ErrTokenReuse under an Unauthorized refusal.

func (*AuthAPI[S, U, Tx]) ResetFactors

func (p *AuthAPI[S, U, Tx]) ResetFactors(ctx context.Context, userID impulse.UUID) error

ResetFactors is an administrator's reset of a user's second factor: every browser the person asked to be remembered is forgotten, so their next sign-in from any of them asks for the factor. The email code itself has nothing to reset: a person who lost their mailbox is given a new address (SetSessionUserEmail), unverified, and the next code proves it. Live sessions are not touched; DestroyUserSessions ends them.

func (*AuthAPI[S, U, Tx]) ResetSessionUserPassword

func (p *AuthAPI[S, U, Tx]) ResetSessionUserPassword(ctx context.Context, userID impulse.UUID, temporary string) error

ResetSessionUserPassword sets a temporary password an operator chose: the user must change it before anything else is served (SessionUser.PasswordChangeRequired; see "Users and the forced password change" in the README), its sessions are destroyed and the name's sign-in attempts are reset.

func (*AuthAPI[S, U, Tx]) RevokeInvitation

func (p *AuthAPI[S, U, Tx]) RevokeInvitation(ctx context.Context, id impulse.UUID) error

RevokeInvitation withdraws an invitation that stands; its link is then dead. One that no longer stands is NotFound.

func (*AuthAPI[S, U, Tx]) RevokeToken

func (p *AuthAPI[S, U, Tx]) RevokeToken(ctx context.Context, userID, id impulse.UUID) error

RevokeToken revokes the live token id of userID: an application token alone, or a device grant's token with its family. A token that is not live, or not the user's, is NotFound.

func (*AuthAPI[S, U, Tx]) RevokeUserTokens

func (p *AuthAPI[S, U, Tx]) RevokeUserTokens(ctx context.Context, userID impulse.UUID) error

RevokeUserTokens revokes every live token of a person, for example when an operator takes their access away.

func (*AuthAPI[S, U, Tx]) SendEmailCode

func (p *AuthAPI[S, U, Tx]) SendEmailCode(ctx context.Context) (codeEmail string, expiresAt time.Time, err error)

SendEmailCode mails the pending identity's user a one-time code for the second factor, to the address the user holds, replacing a code standing, and returns the masked address and when the code stops being accepted. The pending identity must wait for MFA and the policy accept the email code (Conflict otherwise), and the user must hold an address (Conflict: EnrollEmail takes one). It reads the pending identity StartSession found, and needs mail (WithMail).

func (*AuthAPI[S, U, Tx]) SetSessionUserEmail

func (p *AuthAPI[S, U, Tx]) SetSessionUserEmail(ctx context.Context, userID impulse.UUID, email *string) error

SetSessionUserEmail puts an address on a user by hand, unverified, or takes it off (nil): an operator's entry for an invitation or a migration. The entry reserves the address: one another user holds, verified or not, is a Conflict, and a sign-up with it is pointed at this account by mail. The address is trusted for nothing until the person verifies it. When the password method declares the username as the email address the entry is refused (Conflict): the address is the username, set at creation and changed through a verified link.

func (*AuthAPI[S, U, Tx]) SetSessionUserPassword

func (p *AuthAPI[S, U, Tx]) SetSessionUserPassword(ctx context.Context, userID impulse.UUID, password string) error

SetSessionUserPassword sets a password the user chose, without the old one: the end of a flow of the application's own that proved who they are (a reset link, an enrollment). The password change mark is cleared, the user's sessions are destroyed and the name's sign-in attempts are reset. A password an operator chose is ResetSessionUserPassword.

func (*AuthAPI[S, U, Tx]) StartAuthenticatedSession

func (p *AuthAPI[S, U, Tx]) StartAuthenticatedSession(ctx context.Context, w http.ResponseWriter, userID impulse.UUID, events []sessioninfo.AuthEvent, customData ...*S) (impulse.UUID, error)

StartAuthenticatedSession starts a session for an existing user the application authenticated itself, recording how in events, which must name at least one method: a sign-up that just created the user, a factor the application ran on its own. It is decided like a login: the sign-in policy, when one is set, answers with the request's ReasonExternalAuth, and the library refuses a missing or disabled user. An Allow establishes the session under a new session ID; a Deny is a refusal (sessioninfo.LoginRefusal); a RequireMFA holds the sign-in as the browser's pending identity and returns a *signin.PendingSignInError, as CompletePending does, for CompletePending to finish. There is no session start that skips the policy: a support session is StartImpersonatedSession.

An event with a zero At records the session's creation time. Optional customData (at most one *S) is written atomically with the session insert, and the custom session data resolver is not called for it; without it the resolver receives ReasonExternalAuth.

func (*AuthAPI[S, U, Tx]) StartDeviceAuthorization

func (p *AuthAPI[S, U, Tx]) StartDeviceAuthorization(ctx context.Context, req *DeviceAuthorizationRequest) (*DeviceAuthorization, error)

StartDeviceAuthorization starts a device authorization for req: the client shows the person the user code and the verification URI, and polls RedeemDeviceCode with the device code until the person decides. The client id must be set and the outlet registered, else 400.

func (*AuthAPI[S, U, Tx]) StartImpersonatedSession

func (p *AuthAPI[S, U, Tx]) StartImpersonatedSession(ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, customData ...*S) (impulse.UUID, error)

StartImpersonatedSession starts an impersonated session, with the same semantics as the other session types. A user principal resolves against the users, as on PasswordAuth.

A user principal's session belongs to the impersonated user (SessionData.UserID). A role principal's session belongs to no user (null UserID). The session records an impersonation auth event whose connection is the actor.

func (*AuthAPI[S, U, Tx]) Tokens

func (p *AuthAPI[S, U, Tx]) Tokens(ctx context.Context, userID impulse.UUID) ([]*sessionstorage.Token, error)

Tokens lists a person's live tokens, newest first, their hashes left out: their application tokens and the access and refresh tokens of their device grants.

func (*AuthAPI[S, U, Tx]) UnlinkIdentity

func (p *AuthAPI[S, U, Tx]) UnlinkIdentity(ctx context.Context, identityID impulse.UUID) error

UnlinkIdentity removes an identity link. The last means of sign-in of a password-less user is refused (sessionstorage.ErrLastSignInMethod, Conflict).

func (*AuthAPI[S, U, Tx]) UpdateCustomSessionData

func (p *AuthAPI[S, U, Tx]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *S) error) error

UpdateCustomSessionData updates the custom session data of an active session.

func (*AuthAPI[S, U, Tx]) UpdateCustomUserData

func (p *AuthAPI[S, U, Tx]) UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data *U) error) error

UpdateCustomUserData updates a user's custom user data.

func (*AuthAPI[S, U, Tx]) User

func (p *AuthAPI[S, U, Tx]) User(ctx context.Context, userID impulse.UUID) (*sessionstorage.SessionUser, error)

User returns a user by ID, or a NotFound error.

func (*AuthAPI[S, U, Tx]) UserByEmail

func (p *AuthAPI[S, U, Tx]) UserByEmail(ctx context.Context, email string) (*sessionstorage.SessionUser, error)

UserByEmail returns the user holding the address, verified or not, matched without regard to case, or a NotFound error.

func (*AuthAPI[S, U, Tx]) UserByUsername

func (p *AuthAPI[S, U, Tx]) UserByUsername(ctx context.Context, username string) (*sessionstorage.SessionUser, error)

UserByUsername returns a user by username, matched without regard to case, or a NotFound error.

func (*AuthAPI[S, U, Tx]) Users

func (p *AuthAPI[S, U, Tx]) Users(ctx context.Context) ([]*sessionstorage.SessionUser, error)

Users lists every user, by username. A user carries its username, whether it is disabled, its password hash (nil for a password-less user), whether it must change its password, when it was created and when it last signed in.

func (*AuthAPI[S, U, Tx]) ValidateCredentials

func (p *AuthAPI[S, U, Tx]) ValidateCredentials(ctx context.Context, username, password string) (impulse.UUID, error)

ValidateCredentials checks a username and password and returns the user ID. A password-less user always fails validation. It starts no session and asks no sign-in policy. It is limited as the login is: a failure counts against the name, and a name whose attempts reached the limit is refused with a *sessioninfo.LoginRefusal carrying RefusedTooManyAttempts and the wait (sessioninfo.RetryAfterOf), before the user is looked up or the password hashed. The call has no client, so only the name is counted.

func (*AuthAPI[S, U, Tx]) ValidateSession

func (p *AuthAPI[S, U, Tx]) ValidateSession(ctx context.Context) (context.Context, error)

ValidateSession validates the session cookie and stores the session data and its user (sessioninfo.UserFromCtx) in the context. Like Auth.ValidateSession, it refuses a session whose user is missing or disabled as unauthorized, and the request of a user who must change their password as forbidden, with a *sessioninfo.LoginRefusal carrying RefusedPasswordChangeRequired.

func (*AuthAPI[S, U, Tx]) VerifyEmailCode

func (p *AuthAPI[S, U, Tx]) VerifyEmailCode(ctx context.Context, w http.ResponseWriter, code string, rememberDevice bool) (impulse.UUID, error)

VerifyEmailCode completes the pending identity when code is the one sent, as CompletePending does with an email-code event, and returns the session's id; with rememberDevice the browser is remembered as a trusted device of the user. A wrong code is a *sessioninfo.LoginRefusal carrying RefusedInvalidCode and leaves the code standing with one fewer attempt; a code that expired, was used or took its last attempt, or entered before one was sent, is one carrying RefusedCodeExpired. If the sign-in must wait again, the error is a *signin.PendingSignInError.

type AuthOption

type AuthOption = sessioncore.AuthOption

AuthOption configures an Auth session: the cookie options, the session options and the Auth settings (WithIdentityLinked, WithPendingHook, WithPendingTimeout, WithPendingCookieName).

func WithDeviceCodeLifetime

func WithDeviceCodeLifetime(lifetime, pollInterval time.Duration) AuthOption

WithDeviceCodeLifetime sets how long a device authorization waits for the person's decision, and the interval a client is held to between polls. (default: ten minutes, five seconds)

func WithDeviceCodesTableName

func WithDeviceCodesTableName(name string) AuthOption

WithDeviceCodesTableName sets the name of the group's device codes table. (default: SessionDeviceCodes)

func WithDeviceVerificationURL

func WithDeviceVerificationURL(path string) AuthOption

WithDeviceVerificationURL sets the path of the application's page where a signed-in person approves a device, as the device authorization tells the client (verification_uri). It must be a path in the application. (default: /device)

func WithEmailCodeTimeout

func WithEmailCodeTimeout(d time.Duration) AuthOption

WithEmailCodeTimeout sets how long a mailed sign-in code is accepted. (default: 10m)

func WithFactorCodesTableName

func WithFactorCodesTableName(name string) AuthOption

WithFactorCodesTableName sets the name of the group's factor codes table. (default: SessionFactorCodes)

func WithIdentitiesTableName

func WithIdentitiesTableName(name string) AuthOption

WithIdentitiesTableName sets the name of the group's identities table, beside WithSessionTableName and WithUserTableName. (default: SessionIdentities)

func WithIdentityLinked

func WithIdentityLinked(hook IdentityLinkedHook) AuthOption

WithIdentityLinked sets the hook called after every identity link, whether made by a pending identity's password confirmation or by the account rules during a sign-in (LinkIdentity or ProvisionUser). A resolver's link is committed before the sign-in policy runs, so it is reported even when the policy then denies the sign-in or holds it for MFA. An error from the hook is logged. The link and the sign-in stand.

func WithInvitationCookieName

func WithInvitationCookieName(name string) AuthOption

WithInvitationCookieName sets the name of the cookie that carries an invitation the browser opened into the sign-in. (default: auth-invitation)

func WithMail

func WithMail(sender mail.Sender, settings MailSettings) AuthOption

WithMail gives the Auth the means to send mail: sender delivers the messages (mail/workspace is the Google Workspace relay), and settings say as whom and where the links lead. It is needed by invitations (AuthAPI.Invite, Invitation()), the add-address step (Email()) and sign-up (SignUp(), with OpenSignUp on the password method); an Auth without it offers none of them. NewAuth refuses a nil sender, an empty application name and a login URL that is not an absolute http or https URL.

func WithMailLinksTableName

func WithMailLinksTableName(name string) AuthOption

WithMailLinksTableName sets the name of the group's mail links table. (default: SessionMailLinks)

func WithPendingCookieName

func WithPendingCookieName(name string) AuthOption

WithPendingCookieName sets the name of the pending cookie, which carries the opaque token of the browser's pending sign-in. (default: "auth-pending")

func WithPendingHook

func WithPendingHook(hook PendingHook) AuthOption

WithPendingHook sets the hook called when PasswordMethod.Login(), an external method's Callback() or Pending().ConfirmWithPassword() holds a sign-in as a pending identity. The AuthAPI methods never call it. They return a *signin.PendingSignInError instead.

func WithPendingSignInsTableName

func WithPendingSignInsTableName(name string) AuthOption

WithPendingSignInsTableName sets the name of the group's pending sign-ins table. (default: SessionPendingSignIns)

func WithPendingTimeout

func WithPendingTimeout(d time.Duration) AuthOption

WithPendingTimeout sets how long a pending identity waits for confirmation or MFA. (default: 10m)

func WithSignInAttemptsTableName

func WithSignInAttemptsTableName(name string) AuthOption

WithSignInAttemptsTableName sets the name of the group's sign-in attempts table. (default: SessionSignInAttempts)

func WithTokenLifetimes

func WithTokenLifetimes(access, refresh, applicationMax time.Duration) AuthOption

WithTokenLifetimes sets how long the tokens live: an access token for access, a refresh token for refresh (at least access), and an application token for at most applicationMax, the default an application token is issued with. (default: an hour, thirty days, a year)

func WithTokensTableName

func WithTokensTableName(name string) AuthOption

WithTokensTableName sets the name of the group's tokens table. (default: SessionTokens)

func WithTrustedDeviceCookieName

func WithTrustedDeviceCookieName(name string) AuthOption

WithTrustedDeviceCookieName sets the name of the cookie that carries a trusted device's token. (default: "auth-trusted")

func WithTrustedDevicePeriod

func WithTrustedDevicePeriod(d time.Duration) AuthOption

WithTrustedDevicePeriod sets how long a browser the person asked to be remembered after a second factor stands in for it. (default: 30 days)

func WithTrustedDevicesTableName

func WithTrustedDevicesTableName(name string) AuthOption

WithTrustedDevicesTableName sets the name of the group's trusted devices table. (default: SessionTrustedDevices)

type BaseSessionOption

type BaseSessionOption = sessioncore.BaseSessionOption

BaseSessionOption configures the session itself. It is an option of every session type.

func WithImpersonationAudit

func WithImpersonationAudit(hook ImpersonationAuditHook) BaseSessionOption

WithImpersonationAudit registers the hook that receives impersonation lifecycle events (see ImpersonationAuditHook). Events are logged with the canonical evidence attributes whether or not a hook is registered.

func WithImpersonationTimeout

func WithImpersonationTimeout(d time.Duration) BaseSessionOption

WithImpersonationTimeout sets the hard cap on an impersonated session's lifetime. The cap is absolute: it is fixed when the session is established and idle-activity renewal never extends past it. The idle session timeout applies independently. The default is one hour.

func WithLogHandler

func WithLogHandler(l LogHandler) BaseSessionOption

WithLogHandler sets the LogHandler. (default: httpio.Log)

func WithPrincipalResolver

func WithPrincipalResolver(resolve PrincipalResolver) BaseSessionOption

WithPrincipalResolver installs the resolver that chooses each validated request's authorization subject (sessioninfo.PrincipalFromCtx). It is the seam for the narrow case of a session whose subject genuinely is not a user — a service or API-key session acting as the role bound to its credential, or membership held in an external system and read live — without an impersonation record and without storing anything: the choice is made per request at validation time. It is not for a role snapshotted into custom session data, and not for a user choosing a role for one session (that is an impersonation record: evidenced, capped, revocable). See the README, "Choosing the principal".

The resolver runs for ordinary sessions and for user-principal impersonations (so an impersonated user's session acts as that user would); a role-principal impersonation already names its subject and skips it. When the resolver changes the principal the choice is stamped on the request's log entry and trace span as principal.kind and principal (sessioninfo.AttrPrincipalKind, sessioninfo.AttrPrincipal).

func WithSessionTableName

func WithSessionTableName(name string) BaseSessionOption

WithSessionTableName sets the name of the session table. (default: Sessions) A name that is not a plain identifier (a letter or underscore, then up to 127 letters, digits or underscores) is refused by the session type's constructor, as every table-name option's is.

func WithSessionTimeout

func WithSessionTimeout(d time.Duration) BaseSessionOption

WithSessionTimeout sets the session timeout. (default: 10m)

func WithUserTableName

func WithUserTableName(name string) BaseSessionOption

WithUserTableName sets the name of the user table. (default: SessionUsers)

type ChangeSessionUserPasswordRequest

type ChangeSessionUserPasswordRequest struct {
	OldPassword string
	NewPassword string
}

ChangeSessionUserPasswordRequest takes in the user information for changing a SessionUser password

type CookieOption

type CookieOption = sessioncore.CookieOption

CookieOption configures the session cookie client. It is an option of every session type.

func WithCookieDomain

func WithCookieDomain(domain string) CookieOption

WithCookieDomain sets the domain for the session cookie.

func WithCookieName

func WithCookieName(name string) CookieOption

WithCookieName sets the cookie name for the session cookie.

func WithXSRFCookieName

func WithXSRFCookieName(name string) CookieOption

WithXSRFCookieName sets the cookie name for the XSRF cookie.

func WithXSRFHeaderName

func WithXSRFHeaderName(name string) CookieOption

WithXSRFHeaderName sets the header name for the XSRF header.

type CreateUserRequest

type CreateUserRequest struct {
	Username               string  `json:"username"`
	Password               *string `json:"password"`
	Disabled               bool    `json:"disabled"`
	PasswordChangeRequired bool    `json:"passwordChangeRequired"`
	// Email is the user's email address as an operator enters it, unverified: it
	// reserves the address, and a link may be sent to it. Nil for none. When the
	// username is the address (UsernameIsEmail) it is nil or the username.
	Email *string `json:"email"`
}

CreateUserRequest takes in the user information for creating a new SessionUser. A nil Password creates a password-less user. PasswordChangeRequired marks the password as one an operator set: the user changes it before anything else is served (see the README's "Users and the forced password change"); it needs a Password. Email is the address the operator enters, unverified (see "Users and their email address").

type DeviceAuthorization

type DeviceAuthorization struct {
	DeviceCode              string
	UserCode                string
	VerificationURI         string
	VerificationURIComplete string
	ExpiresIn               time.Duration
	Interval                time.Duration
}

DeviceAuthorization is what a client is told when it starts a device authorization (RFC 8628, 3.2): the device code it polls with, the user code the person types, the application's page to type it at, that page with the code already in, how long the authorization waits, and the interval between polls.

type DeviceAuthorizationRequest

type DeviceAuthorizationRequest struct {
	// ClientID names the client, as the person is told and the grant records.
	ClientID string
	// Outlet is the registered machine outlet the grant's tokens are for.
	Outlet string
}

DeviceAuthorizationRequest is what a command-line client asks for when it starts a device authorization.

type DeviceHandlers

type DeviceHandlers struct {
	// contains filtered or unexported fields
}

DeviceHandlers are the HTTP handlers of the device flow.

func (*DeviceHandlers) Approve

func (h *DeviceHandlers) Approve() http.HandlerFunc

Approve accepts {"userCode"} from the signed-in person and approves the client as them; the client's next poll receives its tokens. A code that names no pending authorization is 404. Route it behind ValidateSession and ValidateXSRFToken.

func (*DeviceHandlers) Authorize

func (h *DeviceHandlers) Authorize() http.HandlerFunc

Authorize is the device authorization endpoint (RFC 8628, 3.1): the client posts client_id and outlet, form-encoded or as JSON, and is answered {"device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in", "interval"}. An outlet that is not registered, or a missing client id, is 400 {"error": "invalid_request", "error_description"}. Route it outside ValidateSession and ValidateXSRFToken: the client has no session.

func (*DeviceHandlers) Deny

func (h *DeviceHandlers) Deny() http.HandlerFunc

Deny accepts {"userCode"} from the signed-in person and denies the client. A code that names no pending authorization is 404. Route it behind ValidateSession and ValidateXSRFToken.

func (*DeviceHandlers) Lookup

func (h *DeviceHandlers) Lookup() http.HandlerFunc

Lookup answers the approval page's question about the code the person typed, ?userCode=, with {"clientId", "outlet", "expiresAt"} while the authorization waits, and 404 otherwise. Route it behind ValidateSession.

func (*DeviceHandlers) Token

func (h *DeviceHandlers) Token() http.HandlerFunc

Token is the token endpoint (RFC 8628, 3.4; RFC 6749, 5): the client posts grant_type with device_code, or grant_type=refresh_token with refresh_token, and is answered {"access_token", "token_type": "Bearer", "expires_in", "refresh_token"}, or 400 {"error", "error_description"} with the RFC's codes: authorization_pending and slow_down while the person has not decided, access_denied, expired_token, invalid_grant for an unknown, redeemed, rotated or revoked token, and unsupported_grant_type. Route it outside ValidateSession and ValidateXSRFToken.

type DirectorySeatedHook

type DirectorySeatedHook[Tx any] = func(ctx context.Context, tx Tx, userID impulse.UUID, username string, seats []signin.DirectorySeat) (committed func(ctx context.Context), err error)

DirectorySeatedHook is the application's half of a directory's default seat: it seats the user a first sign-in provisions, named by id and by username (the key an application's memberships are held under), with seats, the default seats of the directories the tenants declared for the identity's connection, inside the transaction that provisions the user, which it is handed: the account is made and seated together, or neither. A seat the invitation this sign-in consumes names too (the same role in the same tenant) is not among seats: InvitationAcceptedHook gives it, in the same transaction, and the two hooks never write one membership twice. The hook is not called for no seats. It is held to what InvitationAcceptedHook is: tx alone for its reads and writes, the user not readable in it, a committed function (nil for none) the library runs once the transaction has committed and before the sign-in policy decides, and an error that fails the transaction and ends the sign-in, so no account is left holding nothing.

type DisabledRoleSyncConfig

type DisabledRoleSyncConfig = signin.DisabledRoleSyncConfig

DisabledRoleSyncConfig is the type returned by DisableRoleSync. See signin.DisabledRoleSyncConfig.

func DisableRoleSync

func DisableRoleSync() DisabledRoleSyncConfig

DisableRoleSync disables role synchronization. See signin.DisableRoleSync.

type EmailHandlers

type EmailHandlers struct {
	// contains filtered or unexported fields
}

EmailHandlers are the HTTP handlers of a user's email address.

func (*EmailHandlers) Add

func (h *EmailHandlers) Add() http.HandlerFunc

Add accepts {"email"} from the signed-in user and mails that address a link to confirm it; nothing is written until the link is followed. It answers {} whatever the address's state, so the screen reveals nothing: an address another account holds is told so by mail, and an address the user already holds verified gets no mail. An address that is not one is 400; a mailbox sent five links within fifteen minutes and using none is refused with too_many_emails and the wait. Route it behind ValidateSession.

func (*EmailHandlers) Verify

func (h *EmailHandlers) Verify() http.HandlerFunc

Verify accepts {"token"}, the token the mailed link carried, and writes the address on the signed-in user as verified, replacing whatever they held; when the password method declares the username as the email address, the user is renamed to it with their live sessions. It answers {"email"}. A token whose link is not the user's own, or is no longer live, is 404; an address another user has taken meanwhile is 409. Route it behind ValidateSession.

type EmailRoutes

type EmailRoutes struct {
	Add    string
	Verify string
}

EmailRoutes are the paths of the email address handlers, as a MethodList names them.

type IdentityLinkedHook

type IdentityLinkedHook = func(ctx context.Context, userID impulse.UUID, identity *sessioninfo.Identity) error

IdentityLinkedHook is called after an external identity is linked to a user, for example to notify the user.

type ImpersonationAuditHook

type ImpersonationAuditHook = func(ctx context.Context, event sessioninfo.ImpersonationEvent) error

ImpersonationAuditHook receives every lifecycle event of an impersonated session. For the Started event a returned error fails the establishment — the session is destroyed and the caller sees the error — so an application that must persist evidence before the session lives can guarantee it. Errors from other events are logged.

type ImpersonationQuery

type ImpersonationQuery = sessioninfo.ImpersonationQuery

ImpersonationQuery narrows an ActiveImpersonations listing; see sessioninfo.ImpersonationQuery. The zero query lists every active impersonation.

type ImpersonationRequest

type ImpersonationRequest = sessioncore.ImpersonationRequest

ImpersonationRequest describes the impersonated session to establish. It is a struct so future fields can be added without breaking callers.

type InvitationAcceptedHook

type InvitationAcceptedHook[Tx any] = func(ctx context.Context, tx Tx, userID impulse.UUID, username string, inv *sessioninfo.Invitation) (committed func(ctx context.Context), err error)

InvitationAcceptedHook is the application's half of an invitation's acceptance: it gives what the invitation names, its roles in its tenant, to the user who accepted it, inside the transaction that consumes the invitation, which it is handed (tx, the storage's transaction type): the invitation is spent and its roles given together, or neither. It runs for every acceptance: the one a sign-in or a sign-up performs with the invitation the browser carries, and Invitation().Accept() for a person already signed in. The user is named by id and by username, the key an application's memberships are held under; a user the same transaction provisioned is buffered in it and is not readable until the commit, so the hook writes under the name it is given and looks nobody up.

The hook reads and writes through tx alone. The Spanner emulator allows one read-write transaction at a time, so a second transaction, or a read through another client, inside the hook waits on the transaction the hook runs in and never returns.

committed, nil for none, is work the library runs once that transaction has committed and before the sign-in policy decides: the word to a permission engine that its rows changed, so the policy sees the membership. Spanner runs a transaction's closure again when it aborts, so the hook may be called more than once for one acceptance; only the committed function of the call whose transaction committed is run, once. A hook that fails fails the transaction and ends the sign-in with its error: nothing is consumed, a user the sign-in would have provisioned is not created, and the invitation stands for the next attempt.

type InvitationHandlers

type InvitationHandlers struct {
	// contains filtered or unexported fields
}

InvitationHandlers are the HTTP handlers of invitations.

func (*InvitationHandlers) Accept

func (h *InvitationHandlers) Accept() http.HandlerFunc

Accept accepts the invitation the browser carries for the signed-in user: the invitation is consumed, the user's address is set from it when they hold no verified address, and the application's hook grants what it names, in one transaction. It answers {"accepted": true}; 404 when the browser carries no live invitation. Route it behind ValidateSession.

func (*InvitationHandlers) Open

Open accepts {"token"}, the token the mailed link carried, and answers {"email", "tenant", "expiresAt", "signUp", "usernameIsEmail", "methods"}: the address the invitation was sent to, the tenant it seats the person in ("" for the application's global surface), when it stops being accepted, whether the person may create an account with a password here (the password method is registered), whether that account's username is the address, and the names of the listed external registrations that could admit the address (as the methods listing advertises them; empty when none could), so the page hides the methods that would refuse the person. It sets the invitation cookie, so the sign-in that follows carries the invitation. A token whose invitation is no longer live is 404. Route it behind StartSession and ValidateXSRFToken.

func (*InvitationHandlers) SignUp

func (h *InvitationHandlers) SignUp() http.HandlerFunc

SignUp accepts {"password", "username"} and creates the invited person's account with a password, then signs them in and accepts the invitation: the address the invitation was sent to is the account's, verified. username is the address when the password method declares the username as the email address, and chosen otherwise. It answers as the password login does ({"mfaIsRequired"}); a taken username or address is 409, a password under eight characters 400, no password method or no live invitation 404. Route it beside the password login, behind ValidateXSRFToken.

type InvitationRequest

type InvitationRequest struct {
	// Email is the address to invite.
	Email string
	// Tenant is the tenant the invitation seats the person in, "" for the
	// application's global surface.
	Tenant string
	// RoleNames are the roles the acceptance grants, as the application's hook
	// understands them.
	RoleNames []string
	// InvitedBy is the user sending the invitation, null when unknown.
	InvitedBy impulse.NullUUID
}

InvitationRequest is an invitation to send.

type InvitationRoutes

type InvitationRoutes struct {
	Open   string
	Accept string
	SignUp string
}

InvitationRoutes are the paths of the invitation handlers, as a MethodList names them.

type InvitationRow added in v0.3.0

type InvitationRow struct {
	// ID is the invitation's id.
	ID impulse.UUID
	// TokenHash is the hash the link's token is found by. The token itself is in the
	// message alone; the hash is a secret of the table and is served nowhere.
	TokenHash []byte
	// Email is the invited address, bare.
	Email string
	// Tenant is the tenant the acceptance seats the person in, "" for the
	// application's global surface, and RoleNames the roles it grants.
	Tenant    string
	RoleNames []string
	// InvitedBy is the user who sent the invitation, null when unknown.
	InvitedBy impulse.NullUUID
	// ExpiresAt is when the link stops being accepted.
	ExpiresAt time.Time
}

InvitationRow is the row a prepared invitation is stored as, in the mail links table (Tables.MailLinks), for a caller that writes it in a transaction of its own. The caller writes every field to the column of its name (TokenHash as the bytes they are), Kind as sessionstorage.MailLinkInvitation, CreatedAt as the commit time, and leaves UserId and ConsumedAt null; Tenant is null for the application's global surface (""), and InvitedBy null when unknown. The row is what the sign-in reads when the link is followed, so a row written otherwise is an invitation nobody can accept.

type IssuedToken

type IssuedToken struct {
	Secret string
	Token  *sessionstorage.Token
}

IssuedToken is a token as it leaves the library, once: Secret is what the person or the client holds and is never read back, and Token is the row the store keeps, its hash left out.

type LogHandler

type LogHandler = basesession.LogHandler

LogHandler defines the handler signature required for handling logs.

type MachineOutlet

type MachineOutlet struct {
	// contains filtered or unexported fields
}

MachineOutlet is a machine outlet registered on an Auth: the tokens the Auth issues for it are the credentials its requests carry.

func RegisterMachineOutlet

func RegisterMachineOutlet(auth outletRegistry, name string) *MachineOutlet

RegisterMachineOutlet registers the machine outlet name on auth and returns it. Tokens are issued only for registered outlets, and a token is accepted only on the outlet it was issued for. Register every outlet after NewAuth and before serving the first request; a name that is empty or not an identifier of letters, digits, hyphens and underscores, a name registered twice, or an outlet registered once the Auth is in use is a wiring mistake and panics, as a misregistered sign-in method does.

func (*MachineOutlet) Name

func (o *MachineOutlet) Name() string

Name is the outlet's name.

func (*MachineOutlet) ValidateToken

func (o *MachineOutlet) ValidateToken(next http.Handler) http.Handler

ValidateToken authenticates a request on the outlet by the bearer token it carries (Authorization: Bearer <token>) and binds it to the token's person the way ValidateSession binds a browser request to its user: the session read, the user (sessioninfo.UserFromCtx), the principal and the evidence are the token's, and sessioninfo.TokenFromCtx names the token. A request without a bearer token, or with one that is unknown, expired, revoked, not a bearer kind, issued for another outlet, or whose person is missing or disabled, is refused with 401 and a WWW-Authenticate challenge; a person who must change a password an operator set is refused with 403 and {"message", "code": "password_change_required"}, as everywhere. No cookie is read or written and no XSRF token is checked: a bearer token is nothing a browser sends on its own.

type MailSettings

type MailSettings struct {
	// Application is the application's name as the messages say it ("Harbor").
	Application string
	// LoginURL is the absolute URL of the application's login page
	// (https://harbor.example.com/login), where every mailed link leads: with
	// ?invitation=<token> for an invitation, ?verify=<token> for an address
	// verification and ?signUp=<token> for a sign-up. The page posts the token to the
	// matching route.
	LoginURL string
	// InvitationTimeout is how long an invitation stands; zero is seven days.
	InvitationTimeout time.Duration
	// LinkTimeout is how long a verification or sign-up link stands; zero is a day.
	LinkTimeout time.Duration
}

MailSettings is how the Auth sends mail: through sender, as the application, with links to its login page.

type MethodList

type MethodList struct {
	// Methods are the methods the page offers, in the order it renders them. Each
	// names a registration on the Auth; a method that is registered but not listed
	// here is not offered.
	Methods []AdvertisedMethod
	// Pending are the paths of the pending sign-in handlers (Pending().Status(),
	// ConfirmWithPassword() and Cancel()), all three or none. The page needs them once a
	// sign-in waits for a confirmation or the application's MFA step.
	Pending PendingRoutes
	// ChangePassword is the path of the password method's ChangeUserPassword handler,
	// which the page needs when a sign-in finds the user must change a password an
	// operator set. It is required when the password method is listed, since every
	// user an operator gives a password must change it, and refused when it is not.
	ChangePassword string
	// Invitation are the paths of the invitation handlers (Invitation().Open(),
	// Accept() and SignUp()), or none. Open and Accept go together; SignUp is named
	// when the password method is listed and refused when it is not.
	Invitation InvitationRoutes
	// Email are the paths of the email address handlers (Email().Add() and Verify()),
	// both or none.
	Email EmailRoutes
	// SignUp are the paths of the sign-up handlers (SignUp().Start(), Open() and
	// Complete()), all three or none; they need the password method listed and
	// registered with OpenSignUp.
	SignUp SignUpRoutes
}

MethodList is what an Auth tells its login page (Methods): the sign-in methods the page offers, each with the path the application mounted it at, and the pending sign-in routes. The application writes it where it wires the routes, so the paths the page is told are the paths the router serves.

type NoCustomData

type NoCustomData = sessioncore.NoCustomData

NoCustomData is the custom data type of session types that do not use custom session data (the SessionData type parameter) or custom user data (the UserData type parameter). Instantiate with NoCustomData for each axis the application does not use, e.g. session.NewAuth[session.NoCustomData, session.NoCustomData](...).

type PasswordMethod

type PasswordMethod struct {
	// contains filtered or unexported fields
}

PasswordMethod holds the handlers of the username and password sign-in method.

func PasswordSignIn

func PasswordSignIn(auth signInRegistry, options ...PasswordOption) *PasswordMethod

PasswordSignIn registers username and password sign-in on auth and returns its handlers. It takes the password options (HashAlgorithm, AutoUpgradeHashes, AttemptLimit, UsernameIsEmail, OpenSignUp); cookie and session options belong to NewAuth.

It panics when the method is already registered on auth, when auth has served a request, when it is given an option that is not a password option, or when the attempt limit is not at least one failure within a positive window and lock. The registration is named "password".

func (*PasswordMethod) ChangeUserPassword

func (m *PasswordMethod) ChangeUserPassword() http.HandlerFunc

ChangeUserPassword accepts {"oldPassword", "newPassword"} and changes the signed-in user's password to one they chose: the old one must match and the new one differ (400 otherwise). The password change mark is cleared, every session of the user is destroyed and the caller continues in a new one. It is the one route a user who must change their password reaches, so it validates the session itself: route it beside the session read and the logout, outside ValidateSession and behind ValidateXSRFToken, and name its path to Methods (MethodList.ChangePassword).

func (*PasswordMethod) Login

func (m *PasswordMethod) Login() http.HandlerFunc

Login accepts {"username", "password"}. On success it applies the sign-in policy and either starts the session or creates a pending identity for MFA. It answers {"mfaIsRequired": bool}, plus "redirectUrl" when a PendingHook chose one. A refusal is 401 with {"message", "code"}, where code is a sessioninfo.LoginRefusalCode.

type PasswordOption

type PasswordOption = sessioncore.PasswordOption

PasswordOption configures the password method (PasswordSignIn): AutoUpgradeHashes, HashAlgorithm and AttemptLimit.

func AttemptLimit

func AttemptLimit(failures int, window, lock time.Duration) PasswordOption

AttemptLimit sets how failed password attempts are limited: failures failed attempts on a name within window lock the name for lock, whether a user exists under the name or not, and an attempt during the lock is refused with too_many_attempts and the wait. The client's address and the login's XSRF cookie are each allowed ten times failures, across names, within window before they are locked for lock, and every attempt a client makes during a wait extends its own lock. A success, an MFA completion and a password change reset the name. (default: 5 failures within 15 minutes lock the name for 15 minutes) See "Attempt limiting and the after-sign-in hook" in the README.

func AutoUpgradeHashes

func AutoUpgradeHashes(a bool) PasswordOption

AutoUpgradeHashes controls if password hashes will be auto upgraded (default: true)

func HashAlgorithm

func HashAlgorithm(hasher securehash.HashAlgorithm) PasswordOption

HashAlgorithm controls hashing algrorithm (default: securehash.Argon2())

func OpenSignUp

func OpenSignUp() PasswordOption

OpenSignUp declares, on the password method, that anyone may create an account: the person gives their address, follows the link mailed to it, and sets a password (SignUp handlers). Without it an account is created by an operator (CreateSessionUser) or by the person through an invitation. It needs mail (WithMail). (default: no sign-up)

func UsernameIsEmail

func UsernameIsEmail() PasswordOption

UsernameIsEmail declares, on the password method, that the username is the user's email address: one value, which the users table derives from the username (see the README's "Users and their email address" for the DDL). The login page asks for the address, a sign-up's username is the address, renaming a user is refused, and a person who verifies a new address is renamed to it, with their live sessions. Without it the two are apart: the username is chosen, the address is added and verified separately, and sign-in is by username. (default: apart)

type PendingHandlers

type PendingHandlers struct {
	// contains filtered or unexported fields
}

PendingHandlers are the HTTP handlers for pending identities.

func (*PendingHandlers) Cancel

func (h *PendingHandlers) Cancel() http.HandlerFunc

Cancel discards the pending identity.

func (*PendingHandlers) ConfirmWithPassword

func (h *PendingHandlers) ConfirmWithPassword() http.HandlerFunc

ConfirmWithPassword accepts {"password"}. On success it links the pending identity to its user and starts the session. It answers {"mfaIsRequired": bool}. When the sign-in policy requires MFA after the link, the pending identity remains with reason "mfa", the PendingHook runs, and the application completes it with AuthAPI.CompletePending. A wrong password is 401 and leaves the pending identity.

func (*PendingHandlers) EnrollEmail

func (h *PendingHandlers) EnrollEmail() http.HandlerFunc

EnrollEmail accepts {"email"} from a pending identity whose user holds no address, and mails that address the code as SendCode does; the address is written on the user, verified, when the code is entered. It answers as SendCode does, and 409 when the user already holds an address: the code goes there, and an administrator changes it. An address another account holds is answered as sent and told so by mail to that address, as the add-address step does, so the screen reveals nothing. Route it as SendCode.

func (*PendingHandlers) SendCode

func (h *PendingHandlers) SendCode() http.HandlerFunc

SendCode mails the pending identity's user a one-time code for the second factor, to the address the user holds, and answers {"codeEmail", "codeSent", "codeExpiresAt"}: the masked address and when the code stops being accepted. A code already standing is replaced. It answers 409 when the pending identity does not wait for MFA, when the sign-in policy does not accept the email code, or when the user holds no address (the page then asks for one and posts it to EnrollEmail()); an address sent five codes within fifteen minutes and using none is refused with too_many_emails and the wait; a code that is used resets the count. Route it behind StartSession and ValidateXSRFToken; it panics at wiring on an Auth without mail.

func (*PendingHandlers) Status

func (h *PendingHandlers) Status() http.HandlerFunc

Status returns {"reason", "email", "expiresAt", "returnUrl"[, "factors"]} for the current pending identity, and for one that waits for MFA and may take the library's email code, the code's state under "emailCode": the masked address the code goes to ("codeEmail"), whether one is standing ("codeSent", "codeExpiresAt") and whether the user must first give an address ("enrollEmail"); see "The second factor" in the README. It answers 404 when there is none, and 401 with {"message", "code": "pending_expired"} when it has expired.

func (*PendingHandlers) VerifyCode

func (h *PendingHandlers) VerifyCode() http.HandlerFunc

VerifyCode accepts {"code", "rememberDevice"} and completes the pending identity when code is the one sent: the session starts under a new ID, recording the sign-in's events and an email-code event, and the address the code went to is written on the user verified when it was not. With rememberDevice the browser is remembered as a trusted device of the user for the trusted device period, so its next sign-ins skip the factor. It answers as the password login does: {"mfaIsRequired": false}, or the policy's next wait. A wrong code is 401 with {"code": "invalid_code"} and the code stands with one fewer attempt; a code entered while none stands, because none was sent or the one sent expired, was used or took its last attempt, is 401 with {"code": "code_expired"}, and the page asks for a new one. Route it as SendCode.

type PendingHook

type PendingHook = func(ctx context.Context, w http.ResponseWriter, r *http.Request, pending *sessioninfo.PendingIdentity) (redirectURL string, err error)

PendingHook is called after a sign-in handler holds a sign-in as a pending identity, for example to send an MFA code or choose the next page. It runs after the pending identity is stored and its cookie set, and cannot change either.

The hook may write the response itself, and the handler then writes nothing more. Otherwise it returns where the browser goes: Callback() redirects there and the JSON handlers return it as "redirectUrl". An empty URL keeps the default. The URL must be the application's own, never built from request input.

An error discards the pending identity and fails the sign-in. See the README's "The redirect and response contract".

type PendingRoutes

type PendingRoutes struct {
	Status      string
	Confirm     string
	Cancel      string
	SendCode    string
	VerifyCode  string
	EnrollEmail string
}

PendingRoutes are the paths of the pending sign-in handlers, as a MethodList names them: Status, Confirm and Cancel together, and the email code's SendCode, VerifyCode and EnrollEmail together or not at all, which the page needs when a sign-in waits for the library's second factor (see "The second factor" in the README).

type Preauth

type Preauth[SessionData any] struct {
	// contains filtered or unexported fields
}

Preauth handles session management for pre-authentication scenarios, with custom session data typed as SessionData (caller-supplied at Login); use NoCustomData when custom session data is not used. Preauth is trust-the-caller with no user record, so it has no custom user data axis — durable per-user data needs a user anchor (password auth's SessionUsers, or the OIDC user anchor).

func NewPreauth

func NewPreauth[SessionData any](storage sessionstorage.PreauthStore, cookieKey string, options ...PreauthOption) (*Preauth[SessionData], error)

NewPreauth creates a new Preauth for the custom session data struct type SessionData (use NoCustomData when custom session data is not used). The storage must carry a custom session data configuration built for the same SessionData; a mismatch is a construction error, as is any custom user data configuration — Preauth has no user record to anchor durable data to. Preauth custom session data is caller-supplied at Login (trust-the-caller); there is no resolver input source. cookieKey: A Base64-encoded string representing at least 32 bytes of cryptographically secure random data.

func (*Preauth[T]) API

func (p *Preauth[T]) API() *PreauthAPI[T]

API provides programatic access to Preauth handler internals

func (*Preauth[T]) Authenticated

func (p *Preauth[T]) Authenticated() http.HandlerFunc

Authenticated is the handler reports if the session is authenticated

func (*Preauth[T]) EndImpersonation

func (p *Preauth[T]) EndImpersonation() http.HandlerFunc

EndImpersonation ends the impersonated session (record ended Released) and, for a local actor whose own session is still live, returns the browser to that session; the body's restored flag says whether it did. Route it inside the validated group. See the "Impersonated sessions" section of the README.

func (*Preauth[T]) EnforceReadOnlyMask

func (p *Preauth[T]) EnforceReadOnlyMask(next http.Handler) http.Handler

EnforceReadOnlyMask refuses non-safe requests from a read-only impersonated session with 403 Forbidden, evidenced as a WriteBlocked event; every other request passes. Place it after ValidateSession. See the "Impersonated sessions" section of the README.

func (*Preauth[T]) Logout

func (p *Preauth[T]) Logout() http.HandlerFunc

Logout destroys the current session

func (*Preauth[T]) SetXSRFToken

func (p *Preauth[T]) SetXSRFToken(next http.Handler) http.Handler

SetXSRFToken sets the XSRF Token

func (*Preauth[T]) StartSession

func (p *Preauth[T]) StartSession(next http.Handler) http.Handler

StartSession initializes a session by restoring it from a cookie, or if that fails, initializing a new session. The session cookie is then updated and the sessionID is inserted into the context.

func (*Preauth[T]) ValidateSession

func (p *Preauth[T]) ValidateSession(next http.Handler) http.Handler

ValidateSession checks the sessionID in the database to validate that it has not expired and updates the last activity timestamp if it is still valid. StartSession handler must be called before calling ValidateSession

func (*Preauth[T]) ValidateXSRFToken

func (p *Preauth[T]) ValidateXSRFToken(next http.Handler) http.Handler

ValidateXSRFToken validates the XSRF Token

type PreauthAPI

type PreauthAPI[SessionData any] struct {
	// contains filtered or unexported fields
}

PreauthAPI provides programatic access to Preauth handler internals

func (*PreauthAPI[T]) ActiveImpersonations

func (p *PreauthAPI[T]) ActiveImpersonations(ctx context.Context, q *ImpersonationQuery) ([]*sessioninfo.Impersonation, error)

ActiveImpersonations lists the impersonated sessions that are live right now, newest first — the admin surface's view of who is acting as whom. A session is active while its record has not ended, its hard cap has not passed, its session row is not expired, and it has seen activity within the idle session timeout. q narrows the listing by actor and/or principal; nil lists every active impersonation. It errors when the storage has no impersonation table.

func (*PreauthAPI[T]) Cookie

func (p *PreauthAPI[T]) Cookie() *cookie.Client

Cookie returns the underlying cookie.Client

func (*PreauthAPI[T]) CustomData

func (p *PreauthAPI[T]) CustomData(ctx context.Context) (T, error)

CustomData returns the strongly typed custom session data for the current session from the context. A session with no custom data row yields a zero-value T.

func (*PreauthAPI[T]) DestroyAllUserSessions

func (p *PreauthAPI[T]) DestroyAllUserSessions(ctx context.Context, username string) error

DestroyAllUserSessions destroys all sessions for a given user

func (*PreauthAPI[T]) DestroyImpersonatedSession

func (p *PreauthAPI[T]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error

DestroyImpersonatedSession ends one live impersonated session — the operator's action on an ActiveImpersonations row: the session row is expired and the record ended with reason Revoked, in one transaction, so the next request on that session is refused as expired. A session that is not impersonated, or whose record has already ended, is left untouched. Who may revoke is the application's guard. It errors when the storage has no impersonation table.

func (*PreauthAPI[T]) DestroyImpersonatedSessions

func (p *PreauthAPI[T]) DestroyImpersonatedSessions(ctx context.Context, actor string) error

DestroyImpersonatedSessions expires every live impersonated session established by actor and ends their records with reason Revoked — the offboarding and incident tool. It errors when the storage has no impersonation table.

func (*PreauthAPI[T]) EndImpersonation

func (p *PreauthAPI[T]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)

EndImpersonation ends the impersonated session in ctx with reason Released and, for a local actor whose own session is still live, gives the response that session's cookies so the actor is back in it without logging in; restored reports whether that happened. See EndImpersonation on the handler type and the "Impersonated sessions" section of the README.

func (*PreauthAPI[T]) Login

func (p *PreauthAPI[T]) Login(ctx context.Context, w http.ResponseWriter, username string, customData ...*T) (impulse.UUID, error)

Login creates a new session for a pre-authenticated user.

Preauth is trust-the-caller: no user record is required or consulted, which makes it the right tool for stepping-stone sessions (e.g. MFA-pending) where identity is not yet fully established. For a full session backed by an existing user record after external authentication, use PasswordAuth's StartAuthenticatedSession instead.

Optional customData (at most one *T) is written atomically with the session insert — the session and its custom data row land together or not at all. The library does not validate the data beyond the custom session data configuration, which must be attached to the storage for customData to be accepted. See the "Custom session data" section of the README for the full lifecycle.

func (*PreauthAPI[T]) Logout

func (p *PreauthAPI[T]) Logout(ctx context.Context) error

Logout destroys the current session. For an impersonated session the end is announced as an Ended event, as on every other session type.

func (*PreauthAPI[T]) StartImpersonatedSession

func (p *PreauthAPI[T]) StartImpersonatedSession(ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, customData ...*T) (impulse.UUID, error)

StartImpersonatedSession establishes a session that operates as req.Principal on behalf of req.Actor; see AuthAPI.StartImpersonatedSession for the model.

Preauth has no user record, so a user principal is taken as given: the session's username is the principal's name and its user ID is zero, exactly as Login trusts the caller's username. Whether that user exists is the application's guard.

Establishment is refused when the storage has no impersonation table and when the calling context is itself an impersonated session (no chaining). Optional customData (at most one *T) follows Login's semantics.

func (*PreauthAPI[T]) StartSession

func (p *PreauthAPI[T]) StartSession(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error)

StartSession initializes a session by restoring it from a cookie, or if that fails, initializing a new session. The session cookie is then updated and the sessionID is inserted into the context.

func (*PreauthAPI[T]) UpdateCustomSessionData

func (p *PreauthAPI[T]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *T) error) error

UpdateCustomSessionData updates the custom session data for an active session via a transactional read-modify-write: mutate receives the current row (zero-value T when no row exists), and the full row is written back; a mutate error aborts with nothing written. It is intended for genuine mid-session updates only — initial population belongs in the creation path (caller-supplied data on Login), which is atomic with the session insert. See the "Custom session data" section of the README for the full lifecycle.

func (*PreauthAPI[T]) ValidateSession

func (p *PreauthAPI[T]) ValidateSession(ctx context.Context) (context.Context, error)

ValidateSession checks the sessionID in the database to validate that it has not expired and updates the last activity timestamp if it is still valid. StartSession handler must be called before calling ValidateSession

type PreauthHandlers

type PreauthHandlers interface {
	basesession.Handlers
}

PreauthHandlers defines the interface for pre-authentication session handlers.

type PreauthOption

type PreauthOption = sessioncore.PreauthOption

PreauthOption configures a Preauth session: the cookie options and the session options.

type PreparedInvitation added in v0.3.0

type PreparedInvitation interface {
	// Row answers the row to store, the caller's own copy.
	Row() *InvitationRow
	// Send mails the invitation's link to its address. Call it once the row is
	// committed. A message that could not be sent withdraws the invitation, in the
	// Auth's own storage, so no link stands that nobody holds, and is the error; the
	// caller reports that the mail did not go, and the invitation is sent again by
	// inviting again.
	Send(ctx context.Context) error
}

PreparedInvitation is an invitation checked and made, and neither stored nor mailed yet: the row to store, and the step that mails its link. The token, the message and the sender stay inside it. It is for a caller that stores the row in a transaction of its own beside other writes (the generated user management): the row is written there, and Send runs once that transaction has committed, since a message cannot be taken back if the commit fails. It is an interface so that code written over one is tested without an Auth; the Auth's is the only one that mails.

type PrincipalResolver

type PrincipalResolver = func(ctx context.Context) (accesstypes.Principal, error)

PrincipalResolver chooses the authorization subject of a validated request. It runs inside session validation with the session in ctx — sessioninfo.FromCtx, the custom session data (sessioninfo.CustomDataFromCtx) and the impersonation record are all available — and returns the principal the request evaluates permissions against. Returning the zero Principal keeps the default (the impersonation record's principal, or the session user's own). An error fails the request as a server error, not an unauthorized one: the session is valid; the application could not decide what it acts as.

A resolver chooses which subject, never which grants: grants come from the permission store at check time. A resolver must therefore derive the subject from something live (the credential a machine session was established with, an external system read per request), never from role membership copied into the session at login — that freezes the user's role for the life of the session and defeats the store. Put membership in the permission store instead and let the default user principal apply.

type RoleSyncConfig

type RoleSyncConfig = signin.RoleSyncConfig

RoleSyncConfig is the required role-synchronization slot of the Microsoft Entra ID method (azure.Config.RoleSync) and of the legacy OIDCAzure. See signin.RoleSyncConfig.

func RoleSync

func RoleSync(manager UserRoleManager) RoleSyncConfig

RoleSync enables directory-driven role synchronization. See signin.RoleSync.

type SignUpHandlers

type SignUpHandlers struct {
	// contains filtered or unexported fields
}

SignUpHandlers are the HTTP handlers of sign-up.

func (*SignUpHandlers) Complete

func (h *SignUpHandlers) Complete() http.HandlerFunc

Complete accepts {"token", "password", "username"}, creates the account with the address verified, and signs the person in, answering as the password login does ({"mfaIsRequired"}). username is the address when the password method declares the username as the email address, and chosen otherwise. A taken username or address is 409, a password under eight characters 400, a token whose link is no longer live 404. Route it beside the password login, behind ValidateXSRFToken.

func (*SignUpHandlers) Open

func (h *SignUpHandlers) Open() http.HandlerFunc

Open accepts {"token"}, the token the mailed link carried, and answers {"email", "usernameIsEmail"}: the address, and whether the account's username is the address or the person chooses one. A token whose link is no longer live is 404.

func (*SignUpHandlers) Start

func (h *SignUpHandlers) Start() http.HandlerFunc

Start accepts {"email"} and mails that address a link to finish the sign-up. It answers {} whatever the address's state, so the screen reveals nothing: an address an account already holds is told so by mail. An address that is not one is 400; a mailbox sent five links within fifteen minutes and using none is refused with too_many_emails and the wait; 404 when sign-up is not offered. Route it behind StartSession and ValidateXSRFToken.

type SignUpRoutes

type SignUpRoutes struct {
	Start    string
	Open     string
	Complete string
}

SignUpRoutes are the paths of the sign-up handlers, as a MethodList names them.

type SignedIn

type SignedIn struct {
	// SessionID is the new session's ID.
	SessionID impulse.UUID
	// UserID and Username are the user the session belongs to.
	UserID   impulse.UUID
	Username string
	// Reason is how the session came about: ReasonLogin for a password or external
	// sign-in, ReasonExternalAuth for one the application started
	// (StartAuthenticatedSession), ReasonStepUp for an MFA completion,
	// ReasonIdentityLinked for a password confirmation.
	Reason sessioninfo.NewSessionReason
	// Events are the auth events the session recorded, the sign-in's method first.
	Events []sessioninfo.AuthEvent
}

SignedIn is a session a sign-in established, as the SignedInHook receives it.

type SignedInHook

type SignedInHook = func(ctx context.Context, signedIn *SignedIn) error

SignedInHook is called once for every session a sign-in establishes, after the transaction that inserted it has committed: a password or external sign-in, a confirmation, an MFA completion, a session the application started. It is never called for a refused sign-in or one held as a pending identity. An error is logged and the session stands.

type Tables added in v0.3.0

type Tables struct {
	// Sessions holds the sessions and Users the people who sign in.
	Sessions string
	Users    string
	// Identities holds the links between a user and the external identities a
	// directory verified for them.
	Identities string
	// PendingSignIns holds the sign-ins that wait for a confirmation or a second
	// factor, and SignInAttempts what the password method's attempt limiter counts.
	PendingSignIns string
	SignInAttempts string
	// MailLinks holds the invitations, address verifications and sign-ups the Auth
	// mails, FactorCodes the sign-in codes it mails, and TrustedDevices the browsers
	// people asked to be remembered after a code.
	MailLinks      string
	FactorCodes    string
	TrustedDevices string
	// Tokens holds the bearer tokens the Auth issues for its machine outlets, and
	// DeviceCodes the device authorizations command-line clients wait on.
	Tokens      string
	DeviceCodes string
	// AuthEvents holds how each session was authenticated, and Impersonations who
	// established a view-as or act-as-role session; the storage attaches both
	// (sessionstorage.NewAuthEventsTable, sessionstorage.NewImpersonationTable).
	AuthEvents     string
	Impersonations string
}

Tables names the tables one Auth keeps, by what each holds. An application that runs several Auths in one database keeps each under a prefix of its own (TablesWithPrefix), and everything that must agree on the names reads them from here: the Auth's own construction, the application's migrations, and the code generator, which declares the management resources over the same tables.

func DefaultTables added in v0.3.0

func DefaultTables() Tables

DefaultTables answers the library's own names, the ones an Auth reads and writes when no option names another and the library's schema sets create.

func TablesWithPrefix added in v0.3.0

func TablesWithPrefix(prefix string) (Tables, error)

TablesWithPrefix answers the names of an Auth kept under prefix: the library's own name for each table, led by the prefix (Crew gives CrewSessions, CrewSessionUsers and so on). It is the one rule for the names of an Auth that shares its database with another, so the Auth's construction and whatever else names its tables cannot spell them two ways. A prefix that leaves a name no plain identifier is refused.

type TokenPair

type TokenPair struct {
	AccessToken  string
	RefreshToken string
	ExpiresIn    time.Duration
}

TokenPair is what a device grant or a refresh hands the client: the access token it presents on the outlet, how long that lives, and the refresh token it exchanges for the next pair.

type UserRenamedHook

type UserRenamedHook = func(ctx context.Context, userID impulse.UUID, from, to string) error

UserRenamedHook is told that a user's username changed by the library's own doing: under a password method declared UsernameIsEmail, the person who verifies a new address is renamed to it, live sessions included, as a rename does. An application that keys anything by the username, role memberships above all, moves it from the old name to the new here. The hook runs after the rename is written and outside any transaction; an error is logged and answered to the person as the verification having failed, with the address verified and the username changed, so the hook is written to be safe to run again (adding under the new name before removing under the old).

type UserRoleManager

type UserRoleManager = signin.UserRoleManager

UserRoleManager is the role store a role-synchronizing sign-in reconciles through. See signin.UserRoleManager.

Directories

Path Synopsis
Package azure is the Microsoft Entra ID (Azure) sign-in method: the OpenID Connect authorization code flow with PKCE against the tenants the registration admits, and its registration on an Auth session.
Package azure is the Microsoft Entra ID (Azure) sign-in method: the OpenID Connect authorization code flow with PKCE against the tenants the registration admits, and its registration on an Auth session.
Package cookie provides cookie encryption using PASETO
Package cookie provides cookie encryption using PASETO
Package deviceflow signs a command-line program in to an impulse application's machine outlet through the device flow (RFC 8628) the session library serves, keeps the token pair in the person's configuration directory, and hands the program an http.Client that carries the access token and refreshes it.
Package deviceflow signs a command-line program in to an impulse application's machine outlet through the device flow (RFC 8628) the session library serves, keeps the token pair in the person's configuration directory, and hands the program an http.Client that carries the access token and refreshes it.
Package google is the Google Workspace sign-in method: the OpenID Connect authorization code flow with PKCE (Proof Key for Code Exchange), restricted to the Workspaces the registration admits and keyed by the connection the slot selects for the account.
Package google is the Google Workspace sign-in method: the OpenID Connect authorization code flow with PKCE (Proof Key for Code Exchange), restricted to the Workspaces the registration admits and keyed by the connection the slot selects for the account.
internal
attempts
Package attempts limits the failed password attempts of an Auth.
Package attempts limits the failed password attempts of an Auth.
basesession
Package basesession implements the session management for the application.
Package basesession implements the session management for the application.
cookie
Package cookie implements all cookie handling for the session package
Package cookie implements all cookie handling for the session package
dbtype
Package dbtype contains types used by the database driver packages for session storage.
Package dbtype contains types used by the database driver packages for session storage.
oidctest
Package oidctest holds the test doubles the OIDC authenticator tests share: a minimal identity provider that signs real ID tokens, and a cookie client with a fresh key.
Package oidctest holds the test doubles the OIDC authenticator tests share: a minimal identity provider that signs real ID tokens, and a cookie client with a fresh key.
sessioncore
Package sessioncore is what the session types are built from: the base session over the storage and the cookie client, the options every session type takes, session establishment, the API methods every session type shares, impersonation establishment and its guards, the custom data type checks, the password comparison and the login refusal redirect.
Package sessioncore is what the session types are built from: the base session over the storage and the cookie client, the options every session type takes, session establishment, the API methods every session type shares, impersonation establishment and its guards, the custom data type checks, the password comparison and the login refusal redirect.
signinflow
Package signinflow establishes the session of an Auth sign-in over a storage driver: it resolves the identity's user, decides the sign-in and inserts the session, once for every driver, generic over the driver's transaction type.
Package signinflow establishes the session of an Auth sign-in over a storage driver: it resolves the identity's user, decides the sign-in and inserts the session, once for every driver, generic over the driver's transaction type.
simulated
Package simulated is the development build's simulated sign-in: under the skipAuth build tag the Azure and Google methods contact no provider and take who signed in, and which roles they hold, from the environment.
Package simulated is the development build's simulated sign-in: under the skipAuth build tag the Azure and Google methods contact no provider and take who signed in, and which roles they hold, from the environment.
testkey
Package testkey holds the one cookie master key the test suites share.
Package testkey holds the one cookie master key the test suites share.
util
Package util is used for general utility function such as generic sorting/filtering and more.
Package util is used for general utility function such as generic sorting/filtering and more.
workos
Package workos is the WorkOS SSO sign-in method: a client for the Standalone SSO authorization code flow.
Package workos is the WorkOS SSO sign-in method: a client for the Standalone SSO authorization code flow.
Package mail is how the session library sends mail: the invitation a tenant's administrator sends to an address, the link that verifies an address a person adds or changes, and the link a password sign-up starts from.
Package mail is how the session library sends mail: the invitation a tenant's administrator sends to an address, the link that verifies an address a person adds or changes, and the link a password sign-up starts from.
workspace
Package workspace sends the session library's mail through the Google Workspace SMTP relay: a plain mail submission to smtp-relay.gmail.com on port 587 over TLS, which Google Cloud's compute products allow (they block port 25, the port a mail server of our own would need), authenticated as one mailbox of the organization's Workspace domain with an app password.
Package workspace sends the session library's mail through the Google Workspace SMTP relay: a plain mail submission to smtp-relay.gmail.com on port 587 over TLS, which Google Cloud's compute products allow (they block port 25, the port a mail server of our own would need), authenticated as one mailbox of the organization's Workspace domain with an app password.
Package mock is used to generate mock files for testing.
Package mock is used to generate mock files for testing.
mock_azure
Package mock_azure is a generated GoMock package.
Package mock_azure is a generated GoMock package.
mock_cookie
Package mock_cookie is a generated GoMock package.
Package mock_cookie is a generated GoMock package.
mock_google
Package mock_google is a generated GoMock package.
Package mock_google is a generated GoMock package.
mock_oidc
Package mock_oidc is a generated GoMock package.
Package mock_oidc is a generated GoMock package.
mock_session
Package mock_session is a generated GoMock package.
Package mock_session is a generated GoMock package.
mock_signin
Package mock_signin is a generated GoMock package.
Package mock_signin is a generated GoMock package.
Package oidc is the OpenID Connect machinery the identity provider packages build on: the provider loader (discovery), the authorization code flow with PKCE and the state cookie, and the claims decoding.
Package oidc is the OpenID Connect machinery the identity provider packages build on: the provider loader (discovery), the authorization code flow with PKCE and the state cookie, and the claims decoding.
Package sessioninfo handles session information.
Package sessioninfo handles session information.
Package sessionstorage implements database storage for session data.
Package sessionstorage implements database storage for session data.
internal/drivertest
Package drivertest is the conformance suite the PostgreSQL and Spanner drivers share.
Package drivertest is the conformance suite the PostgreSQL and Spanner drivers share.
internal/postgres
Package postgres implements the session storage driver for PostgreSQL.
Package postgres implements the session storage driver for PostgreSQL.
internal/spanner
Package spanner provides the session storage driver for Spanner.
Package spanner provides the session storage driver for Spanner.
mock/mock_sessionstorage
Package mock_sessionstorage is a generated GoMock package.
Package mock_sessionstorage is a generated GoMock package.
Package signin is the contract between the Auth session and a sign-in method.
Package signin is the contract between the Auth session and a sign-in method.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL