session

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 42 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 (session/internal/workos): built and tested, in an internal package, so an application cannot import it
  • 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.
  • Open to sign-up, or invite only: whether a person with no account and no invitation may sign in is one choice an administrator makes in the running application, for each sign-in method, kept in a table of the auth; every method is invite only until it is opened, and an open method gives a new person its default role. See "Open to sign-up, or invite only" 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), or carrying the tenant its acceptance makes, held to an organization's directory where the tenant is entered through its directory only; 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 while an administrator has the password method open to it. See "Users and their email address", "Invitations" and "Sign-up" under the Auth session.
  • A person's first password: a person who has only ever signed in through a directory chooses a password while signed in, with a code mailed to the address their account holds confirmed, so the password is tied to that mailbox. See "A person's first password".
  • 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, superAdministrators).

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) 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 the 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), the person's name Name (SessionNames), and the tenant an invitation makes, the mail links table's NewTenant column (SessionTenantInvitations); see "Users and their email address" for the two shapes the address columns take, "A person's name" and "Invitations".

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.

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; the WorkOS method is session/internal/workos, which an application cannot import), 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, RemoveUserPassword 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) 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 library applies its standard account rule to a first sign-in, which reads what an administrator chose for the registration in the running application, open to sign-up or invite only (see "Storage and schema" and "Open to sign-up, or invite only").

Storage and schema

Each auth group owns eleven tables: sessions and users (the base migrations, schema/*/migrations), identities, auth events, pending sign-ins, sign-in attempts, mail links, factor codes, trusted devices and sign-in methods (the auth migrations, schema/*/auth/migrations, which also add UserId, AuthenticatedAt, ProviderSessionId and ProviderSessionIssuer to the sessions table and the email address columns and the person's name 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 mail links table holds the tenant an invitation makes in one nullable column, NewTenant: a JSON document, {"name", "directoryOnly", "details"}, null on a verification link, a sign-up link and an invitation that makes no tenant (see "Invitations"). The drivers write and read it. An application that stores an invitation's row in a transaction of its own (PrepareInvitation) writes the same document, which the row answers (InvitationRow.NewTenantColumn()), and a mail links table named per group, or kept in the application's own migrations, carries the column as the shipped one does.

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".

  • A super administrator signs in with a second factor whatever the sign-in policy asks of anyone else. No Auth is built without a word on who holds the Super Administrator role: it is NewAuth's third argument, so an application that leaves it out does not compile. An application whose people hold roles passes session.SuperAdministratorsBy(signin.SuperAdministrators(userManager)), over the access library's user manager, which it opens before the Auth (on Spanner over resource.SignInRoles(userManager), as the tenant policy is). The Auth then decides every sign-in by the application's policy and, after it, by a rule of its own (signin.SuperAdministratorFactor): a sign-in the policy allows is held for the code the library mails (sessioninfo.MethodEmailCode) when the person holds the role, with or without a policy of the application's. The directory's attestation and a remembered browser satisfy it as for any account, and a refusal, or a hold for a factor the policy names itself, stands as the policy decided it. The rule is for an Auth whose roles the application gives. A sign-in through a method that synchronizes roles is not held by it: there the directory is the authority, on who is a super administrator as on every role, and the application's own policy is asked of that person as of anyone (see "Role synchronization"). Such an Auth must send mail (WithMail): NewAuth refuses one that sends none, since the code could not be sent and a holder would never sign in. It refuses the argument's zero value and a nil check too, each saying what to pass. An application with no permission engine, and so no role of any kind, passes session.NoSuperAdministrators(), and its Auth holds nobody to the rule. The auth packages impulse writes pass the first, and impulse check (super-administrators) fails an auth package with a role file that passes the second, or that builds its check over another auth's engine.

  • 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. The library applies its standard rule inside the sign-in's first transaction:

    • A person who has an account is linked to it. A user the application created is found by the username first and then by the address: the user under the identity's sign-in name (the user principal name on Entra, the verified email on Google), 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, and outright when the user has none and has never signed in: it is the user's first identity. A user with no password who already signs in through an identity is linked no second one on the name, on the same connection or another (see "Never a second identity on a name alone" below). An address a user holds unverified is a reservation, not a match.
    • A person who has none is decided by what an administrator chose for the method, the registration's row of the sign-in methods table, read in the same transaction (see "Open to sign-up, or invite only"). A method with no row is invite only: the person is refused (not_invited) and nothing is written, unless the sign-in carries an invitation, which is then the account, with the invitation's roles. A method an administrator opened to sign-up gives the person an account under their sign-in name and the default role the row names, through the application's hook, in the transaction that makes the account. Nothing in code opens a method.
    • A method whose directory writes the roles (role synchronization) has no such choice: the directory says who holds a role, so a person whose token asserts one is given an account, and a person whose token asserts none is refused (no_roles).

    A new account holds no address until the person verifies one, a 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.

    In a tenanted application the tenant's declaration decides a stranger first. With auth.SetDirectoryAdmission(directoryLookup, seatHook) (see "The tenant policy"), a person no user was created for, from a tenant's directory, is decided by that tenant's declaration before the registration's rule is reached. A directory belongs to one tenant, so one declaration decides. A person an account exists for already, because the application gave them a role ahead of their first sign-in or another tenant invited them, is not such a person: the sign-in links to that account, under the sign-in name. That link is their first sign-in through the directory, so the tenant's default seat is given at it too, through the hook, in the transaction that makes the link, whether the link is made at once or after their password confirmed it.

    A first link on a name alone needs something to vouch for it. An account created ahead with no password, which has never signed in (an administrator's create that gave none), has neither a password to confirm a link with nor a link to compare a new one to: nothing but its name ties it to whoever signs in next under that name, and a directory asserts the names it likes (an organization's own OpenID Connect provider is held to no domain). The link hands whoever the directory signs in everything the account holds. So in a tenanted application the identity is linked to such an account only when the sign-in came through the directory of the one tenant the account belongs to (the hook's OnlyIn: the account holds a role, or a place in a group, in the tenant itself, and nothing in another tenant, in every tenant or outside the tenants, so the tenant's directory is given nothing the tenant's own administrators could not give, and a role a tenant's administrator gives an account that holds something elsewhere changes nothing), or when it carries the account's own invitation, the one mailed to the account's address, which must still be live; a disabled account accepts no invitation, so its own vouches for nothing. A person created ahead in two tenants, or holding a role in every tenant or outside them, is therefore linked at a first sign-in only with their invitation, or once they have a password to confirm with. One such account is the deployment's own: the first administrator of an Auth whose people sign in through a directory, which the seed creates with no password, holding roles for the whole application and belonging to no tenant. The deployment vouches for it. The seed creates it under session.SeedUserIDThrough(auth, registration, username), an id that names the sign-in registration the person comes through and that no request can give an account, the hook's Seeded recognizes the id, and the account is linked at its person's first sign-in through that registration while the registration admits one organization and nobody else. The same name through another registration of the Auth, a customer's own provider among them, or through a registration that names several organizations or is open to any or to personal accounts, is not the deployment's word and links nothing, and neither does a seed that was disabled; so the first administrator of an Auth whose only directory methods are that wide is given another way in (a directory method of one organization, or a password). Naming a registration in the seed says that whoever its directory presents under the name is that person: it is for the deployment's own directory, whose sign-in names only its administrators give, and never for a provider that lets a person choose a name. Any other sign-in under the name is refused as a person no account was created for is, with that refusal's own code and words, which say nothing of the account (invitation_only through a directory some tenant has, not_invited through any other), and nothing is linked, seated or accepted. An account with a password keeps the confirmation above, and one that already signs in through an identity is linked no second one on the name (below). The rule is the standard rule's own: a registration's custom rule that answers signin.Link links on its own evidence, as before, and a registration of the generic OpenID Connect method that sets Config.SeededUsers declares its provider's names the application's own and links such an account on the name. It is for the provider a deployment runs for the accounts it seeds, never for an organization's directory, whose names are the organization's to assert. An account an application's seed creates with no password and with roles in every tenant or in none, as the cast of the persona sign-in is, signs in through such a registration; through any other it has no tenant whose directory could vouch for it and is linked only with its own invitation, or as the seed of that registration (the first administrator, above). An application whose tenants have no directories (no SetDirectoryAdmission) has only the directories its deployment registered for itself, and links such an account under its name as before. A declaration naming a default seat admits a stranger, who is provisioned and seated with it in the tenant, through the hook, in the transaction that creates the account and links it. The hook is called once for a link, never for a sign-in that finds the link, and the application's hook gives the seat only where the person holds none in the tenant (the generated identity client's does), so a seat an administrator removed is not given back by signing in, and a link that is deleted and made again gives it again. 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 through a method that is invite only, and without one the sign-in is refused (invitation_only) and nothing is written, whether the method is open or not. A directory no tenant declares falls to what was chosen for the method, as above.

    Never a second identity on a name alone. A name proves nothing about who holds an account. Where a username is not an address, a person may sign up under a colleague's sign-in name, sign in through the directory as themselves (the account holds their own address, so the directory's sign-in finds it and the password confirms the link) and remove the password. The account then has no password to confirm a link with and one identity on the directory's connection, and the colleague's first sign-in through that directory arrives under the account's name; with a method that writes one connection for every account (any Google account, Microsoft personal accounts) every account shares the connection. So the standard rule links an identity the application has not seen, on its sign-in name, to a user without a password only as that user's first identity. Where the user already signs in through one, the sign-in is refused (identity_rejected: signin.ErrLinkSecondIdentity on the same connection, signin.ErrLinkCrossConnection from another) and nothing is linked. A second identity is linked on proof instead: a user who holds, verified, the address the method verified for the identity is the person, and is linked on a connection they already sign in through, as before; a user with a password confirms the link with it, as above, so an administrator who gives the person a temporary password lets them confirm it at their next sign-in; a registration's own rule that answers signin.Link links on its own evidence, as before; and the application may link an identity itself (the store's LinkIdentity). A directory that issues a person a new subject under the same name (their directory account deleted and made again) is therefore followed only where the account holds the address verified and the method verifies it; elsewhere the sign-in is refused until the new identity is linked one of those ways.

    The 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, oidc.AccountRule) 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. A rule's link on a connection the user already signs in through is made on the rule's word, which the standard rule's match by name does not have. 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
// library's standard rule 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))

// Who holds the Super Administrator role, over the access library's user manager: a
// holder signs in with a second factor whatever the policy asks of anyone else.
superAdministrators := session.SuperAdministratorsBy(signin.SuperAdministrators(resource.SignInRoles(userManager)))

auth, err := session.NewAuth[MyData, session.NoCustomData](store, cookieKey, superAdministrators,
    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
auth.SetSignUpSeated(giveDefaultRole) // gives a person who signs up through an open method its default role

// 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 the standard rule alone
    Tenants: azure.Tenant(cfg.EntraTenantID), ClientID: cfg.EntraClientID, ClientSecret: cfg.EntraClientSecret,
    RedirectURL: cfg.SSORedirectURL, RoleSync: signin.DisableRoleSync(), LoginURL: "/login",
})
Open to sign-up, or invite only

Whether a person with no account and no invitation may sign in is not written in code. It is one choice an administrator makes in the running application, for each sign-in method: invite only, or open to sign-up. The choice is a row of the sign-in methods table (SessionSignInMethods, under the group's prefix), keyed by the name the method is registered under:

Column What it holds
Name The registration's name (password, google, entra, ...).
OpenSignUp Whether the method is open to sign-up.
OpenedFor Whom the method admitted when it was opened, as its registration spells its audience (signin.Audience.Key()): what identifies each organization and each kind of account it admits, never a name of theirs. Null for a row that keeps none. The row opens the method for that audience and no other.
DefaultRole The role a person who signs up through the method is given, or null. An application without tenants names one for every open method; an application with tenants names none, since a person who signs up there creates a tenant of their own.
UpdatedAt When the row was written, by the database's clock.

A method with no row is invite only, so a new application, and a method added to one, admits nobody an administrator did not invite or create. The sign-in reads the row in the transaction that would make the account, so the choice and the account are never out of step: a method made invite only refuses the next person, and a link mailed to a person who started a password sign-up while the method was open makes nothing once it is not.

What open admits is how wide the registration is, which stays in code: a method limited to the organizations it names (azure.Tenant, google.Workspace, an oidc provider) admits anyone with an account there; azure.AnyTenant, azure.PersonalAccounts, google.AnyWorkspace, google.AnyGoogleAccount and the password method admit anyone who has such an account. auth.API().SignInMethods() lists the registrations with that width in words (signin.Audience.Words(): "anyone with an account at lakeside.edu", "anyone with a Google account"), for the page where an administrator makes the choice and the warning they confirm. A method that synchronizes roles from its directory has no choice to make (RegisteredMethod.SyncsRoles), and neither has a registration that carries an account rule of its own (RegisteredMethod.OwnRule): the application's code decides who signs in through it.

The administrator who opens a method confirms a sentence that names whom it admits, and the row keeps that audience (OpenedFor). The row opens the method only while the registration's audience is the one it was opened for: a registration that code widens afterwards, from the organizations it named to any organization, say, or by one more organization, is invite only again until an administrator opens it for the audience it has now, and so is one that code narrows or changes in any other way.

Two audiences are compared by what identifies the people, never by what they are called (signin.Audience.Identities): a Microsoft Entra tenant by its tenant id, a Google Workspace by its domain, a generic OpenID Connect provider by its issuer, and each kind of account a method admits outside its organizations by its kind. A name is the application's to give, and a second organization can be given the first one's: a tenant listed beside another under the same label is one organization more, and a tenant put in another's place under its name is another audience, so each is invite only until it is opened again. An organization that is renamed, or listed in another order, is the same audience, and the method stays open. A row that keeps no audience opens nothing, and neither does a row whose OpenedFor is not the key of an audience. A sign-in method an application builds itself (signin.Method) gives its identities in Audience.Identities; one that gives none is compared by the names it gives, which then must be its organizations' alone.

The person The method is invite only The method is open
has an account signs in signs in
carries a live invitation gets an account with the invitation's roles the same
has neither refused (not_invited), nothing written gets an account, and the default role the row names

The default role is given by the application, through the hook it sets once at startup, inside the transaction that makes the account, so the account and the role are written together or not at all:

auth.SetSignUpSeated(func(ctx context.Context, tx *spanner.ReadWriteTransaction, userID impulse.UUID, username, method, role string) (func(ctx context.Context), error) {
    // Write the role for userID through tx. What must happen once the transaction has
    // committed (telling a permission engine that keeps roles in memory) is returned.
    return nil, giveRole(ctx, tx, userID, role)
})

An open method whose row names a role on an Auth with no hook fails the sign-in in its transaction, and no account is made holding nothing. The auth packages impulse writes set the hook, write the table with the group's other tables, and give every application the page where the choice is made; an application that wires its Auth by hand writes the row with sessionstorage.AuthStore.SetSignInMethod, with OpenedFor the key of the registration's audience (auth.API().SignInMethods() answers each registration's), and lists them with SignInMethods. session.WithSignInMethodsTableName renames the table.

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 store names a person by the id of their account, and the policy asks it for the user the sign-in resolved to. 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 declaration restricts that tenant's own door and nobody else's: a tenant that is not directory only, and a tenant that declares nothing (a nil declaration), admits everyone it seats, however they signed in.
  • 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, seatHook). directoryLookup, a signin.DirectoryReader[Tx], reads the declaration of the tenant whose directory the identity came through, with its default seat (signin.DeclaredDirectory: the tenant and the role, "" for none; a directory belongs to one tenant, which the application's schema holds, so the answer carries one tenant at most), in the sign-in's first transaction; seatHook, a session.DirectorySeatedHook[Tx], is the application's two functions over a person's roles. Its Seat seats the person with the seat the declaration names (signin.DirectorySeat), inside the transaction that links the identity to the user, which it is handed, so the link is made and the seat given together or neither is, under the contract the invitation hook has (see "Invitations"). Its OnlyIn answers whether a tenant is the only place a person holds anything, read in that transaction, which the library asks before it links an identity on its name alone to an account that has never signed in (see "A first link on a name alone" above). Its Seeded, which a hook may leave out, answers whether an account is the one the deployment's seed created for the registration a sign-in came through (session.SeedUserIDThrough), which the library asks at the same point; the generated identity client answers all three. Seat is called at a person's first sign-in through the directory, the one that makes the link, whether the account is created in it or stood before: a person given a role ahead of their first sign-in, or invited by another tenant, has an account, which the sign-in links to after the pending confirmation (Pending().Confirm()) when it holds a password, and at once when it holds none and the link is vouched for, and the hook runs in the transaction of that link (the storage's LinkConfirmedIdentity for the confirmed one, which an AuthStore of the application's own must implement). It is called once for a link: a later sign-in finds the link and calls nothing. Whether the person is seated is the hook's to decide over what it is handed: the generated identity client's gives the seat where the person holds no role in the tenant, so a seat an administrator removed is not given back by signing in, and a link that is deleted and made again gives it again. A personal account, one of the two connections that stand for everyone who is in no organization (signin.Directory.PersonalAccounts: any Google account, signin.GoogleAnyAccountConnection, and Microsoft's personal accounts, signin.MicrosoftPersonalAccountsConnection), is no tenant's directory: no declaration is read for it, and it falls to the registration's account rule. A default seat admits and seats a stranger, so rule 5 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 what an administrator chose for the method. Without the three, a stranger is that choice's alone, and a method opened to sign-up gives them an account holding what its row names: the default role, or nothing.

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

  1. A super administrator, a person holding the Super Administrator role (accesstypes.SuperAdministrator, which the access library defines in every auth and which is held in the global partition alone), is admitted on the library's own checks, whatever any tenant declares: the role is the way back in, and no tenant's sign-in settings shut its holder out. The policy and the session's reach into a tenant ask the question through one function (accesstypes.RoleCollection.HoldsSuperAdministrator). A sign-in whose method synchronizes roles is admitted here too, 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 tenant's own administrators keep a way into their tenant. A person who signs in with a password and administers a tenant that is directory only is not refused, and the sign-in is held for the library's second factor, the code it mails (RequireMFA with sessioninfo.MethodEmailCode), whatever else would have admitted it and whatever the application's own rule asks of anyone; a browser the person asked to be remembered passes it for the usual period. A tenant whose directory is broken, or was set wrong, would otherwise be a tenant nobody in it could mend. See "A tenant's administrators and a directory-only tenant" below for who that is. Nobody but a super administrator and a tenant's own administrators, in their own tenant, enters a directory-only tenant another way than through its directory.
  3. A person holding a role outside any one tenant is admitted: in the global partition, which is no tenant's and which no declaration governs, or in every tenant domain, whose tenants the policy has no list of. It is no exemption: the session then reaches a tenant only where the tenant's declaration admits it, as anyone's does.
  4. 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.
  5. The sign-in is admitted when one of the person's tenants admits it (signin.TenantDeclaration.Admits). A tenant that is not directory only admits every sign-in: a password, a personal account, a session the application starts for a user it authenticated itself, and a sign-in through any organization's directory, the tenant's own or another's. A tenant that is directory only admits a sign-in through its own directory and nothing else.
  6. Otherwise every tenant of the person is directory only and none has the way they signed in as its directory: nothing would be reachable, and the sign-in is refused. A sign-in through a directory (Entra, Google, WorkOS, an OpenID Connect provider) is refused with connection_not_in_tenant, and any other, a password, a personal account (which is no tenant's directory) or a session the application started itself, with directory_only.

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:

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

The application's rule is asked after an Allow, and its decision is the answer. It is not asked after a Deny, which stands as it is. It is asked after a RequireMFA too, so a person the tenant policy holds for a second factor (a tenant's administrator signing in with a password) is still refused by the rule that refuses them: its refusal stands, a hold of its own stands (the application names its factor, as it does for a super administrator), and when it allows, the tenant policy's hold is the answer.

A tenant's administrators and a directory-only tenant. The exemption of rule 2 is narrow on every side, and one function decides it for the sign-in and for the session's reach alike (signin.TenantDeclaration.AdmitsAdministrator(method, secondFactor, administers)):

  • Who. The person holds, in that tenant itself and inside its period, one of the roles the application names as a tenant's administrator's (access.WithTenantAdministratorRoles, which the generated auth package sets from its AdministratorRoles()): by a membership of their own in the tenant's domain, or through a group kept in that tenant, whose people and roles are written in the tenant and so give nobody what a membership there would not. A role held in every tenant does not count, and neither does one held through a group kept for the whole application: those are how the application's own people are seated everywhere, and a tenant's switch shuts them out with everyone else. A role that inherits from an administrator's role administers nothing: the application names the roles themselves. The sign-in asks the role store (signin.UserRoleManager.TenantsAdministered), and every request asks the permission engine's snapshot (access.Client.UserAdministersTenant), both through one statement of where a role must be held to count.
  • How they signed in. With a password, and nothing wider: an administrator who came through another organization's directory, or with a personal account, is kept out of the tenant as anyone is.
  • The second factor. The session carries one, an auth event after the first that is not itself a way of signing in (sessioninfo.SessionData.SecondFactor): the mailed code, a remembered browser, an attestation, or a step of the application's own. A password session without one reaches no directory-only tenant, whoever holds it.
  • For how long. While the role is held: it is asked again at every request, so a role taken away, or one whose period ends, closes the way at the next request and not at the next sign-in.

The same person's password session reaches their other tenants only by those tenants' own declarations, unchanged.

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). A session reaches every tenant that seats the person, except a tenant that is directory only and whose directory is not the one the person signed in through; such a tenant is still reached by its own administrator's password session that carries a second factor (TenantDeclaration.AdmitsAdministrator, above). So a person seated in a directory-only tenant and in a tenant that is not signs in by password and reaches the second; signed in through the first one's directory they reach both. A person invited into one tenant who signs in through another tenant's directory reaches both, unless the tenant that invited them is directory only. A member of two directory-only tenants 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).

A tenant's directory is an organization's: signin.Directory.Organization reports a directory method with a connection that names one organization, so neither a password nor a personal account (signin.Directory.PersonalAccounts, the two connections every account outside an organization carries). Admits and the policy treat a personal account as they treat a password: no tenant can have it as its directory, so it reaches a tenant unless the tenant is directory only. A tenant's directory can be any directory method the application registers: Entra, Google Workspace, WorkOS, or an organization's own OpenID Connect provider (sessioninfo.AuthMethod.ThroughDirectory). The session read (Authenticated()) answers directory, the method and the connection of the organization's directory the session was established through, and leaves it out for every other session: it is what an application offers a tenant's administrator to make the tenant's directory, which is set from the sign-in and never typed (the resource package's reference, "One directory, set from a sign-in").

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 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; 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"},
    FirstPassword: session.FirstPasswordRoutes{SendCode: "/api/user/first-password/code", Set: "/api/user/first-password"},
}))
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/password/remove", password.RemoveUserPassword()) // {"password"}: the person's own password, removed; validates the session itself
    r.Get("/api/user/sign-in-means", auth.SignInMeans())        // what the person signs in with: a password or none, the directory sign-ins linked; validates the session itself
    r.Post("/api/user/name", auth.ChangeName())                 // {"name"}: the person's own name; validates the session itself
    r.Post("/api/user/look", auth.ChangeLook())                 // {"scheme", "palette"}: the look the person chose; 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; 404 while the password method is invite only
    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.Post("/api/user/first-password/code", auth.FirstPassword().SendCode()) // mails a person who has no password the code to choose one
        r.Post("/api/user/first-password", auth.FirstPassword().Set())           // {"code", "password"}
        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, the sign-in code's under "The second factor", and the first password's under "A person's first password"; the groups that send mail (Email(), SignUp(), FirstPassword(), 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. The removal of a person's own password (RemoveUserPassword) validates the session itself too and is routed beside the change, though a user who must change their password is refused there as everywhere else; the methods list names it where the application serves it (RemovePassword).

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",
  "removePassword": "/api/user/password/remove",
  "usernameIsEmail": true,
  "invitation": {"open": "/api/user/invitation", "accept": "/api/user/invitation/accept", "signUp": "/api/user/invitation/sign-up",
                 "standing": {"email": "pat@lakeside.edu", "newTenant": false, "directoryOnly": false, "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.
  • removePassword is the path of the password method's RemoveUserPassword handler, present when the list names it (MethodList.RemovePassword, which needs the password method listed): where a signed-in person's account page posts {"password"} to remove their own password (see "Users and the forced password change").
  • firstPassword are the paths of the first password handlers, {"sendCode", "set"}, present when the list names them (MethodList.FirstPassword, both or neither, which needs the password method listed): where the account page of a signed-in person who holds no password asks for the code and posts {"code", "password"} (see "A person's first password").
  • signInMeans is the path of the SignInMeans handler, present when the list names it (MethodList.SignInMeans): where a signed-in person's account page reads what they sign in with, {"password": true, "directories": [{"name": "google", "label": "Fleet Google"}]}. The page hides the change and the removal of a password from a person who holds none, offers the removal only where a directory sign-in can sign them in, and says what the removal leaves by the label of the button the person signs in through, as this list words it.
  • forgetBrowser, changeName and changeLook are the paths of the ForgetBrowser, ChangeName and ChangeLook handlers, each present when the list names it (MethodList.ForgetBrowser, MethodList.ChangeName, MethodList.ChangeLook): where a signed-in person's account page forgets this browser and writes the person's own name, and where their pages keep the look they chose (see "The second factor", "A person's name" and "The look a person chose").
  • 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 is in the answer only while an administrator has the password method open to sign-up, read as each request arrives. 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. For an invitation that makes a tenant, newTenant is true, tenantName is the name the invitation carries for it, and directoryOnly says it is accepted with an organization's account alone, so the page offers no account with a password for it (see "Invitations"). 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 with no password method listed. 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.
  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. A guess takes its attempt before it is judged: the store counts it on the code's row and answers which attempt it was in one step (AuthStore.RecordFactorCodeAttempt), and a guess past the fifth is answered code_expired without being compared with the code, so of guesses entered at once no more than five are ever judged. A code whose five attempts are taken stands no longer: the pending sign-in's state reports none, so the page offers a new one. 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. A request takes its place under the address's limit before its code is mailed, counted in the store's one transaction (AuthStore.RecordSignInFailure, SignInAttempts.Counted), so of codes asked for at once no more than five are mailed; and of codes recorded at once for one pending sign-in one stands, so there is never a second code to guess at with attempts of its own. 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. Auth.ForgetBrowser() is the handler over it that a person's account page posts to: it validates the session itself, as the password change does, so it is routed beside it outside ValidateSession, and it refuses an impersonated session; the generated router mounts it at /user/browser/forget and names it in the methods list (MethodList.ForgetBrowser). The session read (Authenticated) says browserRemembered: true while the browser carries the person's remembered entry, so the page offers the action only then. 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, however many are recorded at once (the PostgreSQL driver takes the pending sign-in's row for the insert, and Spanner's transaction is serializable), 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 is established through auth.API().StartImpersonatedSession (see "Impersonated sessions"). 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 the last identity that can sign in a user with no password, and RemoveSessionUserPassword the password of a user no identity can 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 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). The library generates the user's id; a seed that must know the id before the user exists sets ID (Go callers only, never read from a request body; the nil id is refused): one that names its people in rows of its own, so a development database reads the same on every machine, and one that gives a user its roles (SeedUserID, below).
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. Writes the new password over the one that was proved and no other (Conflict, sessionstorage.ErrPasswordChanged, when the password changed meanwhile: nothing is written and no session ends), clears the mark and destroys the sessions in the same transaction (AuthStore.ChangeUserPassword: the password changed and the sessions ended, or neither), then continues in a new one. The new session is the continuation of the one that made the change: it records that session's auth events, how it was established and the factors it holds, read from the session and never from the request, so a person who signed in through a directory still holds the directory's session and one who entered with a password and the mailed code keeps the code. Where there is none to continue (a call outside a session of the user, a request a bearer token authenticated, or a session that views the application as them) it records the password the change proved, alone. 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 and destroys the sessions in the transaction that writes the password (AuthStore.ReplaceUserPassword: the password replaced and the sessions ended, or neither).
ResetSessionUserPassword(ctx, id, temporary) A temporary password an operator chose. Sets the mark and destroys the sessions in the transaction that writes the password (AuthStore.ReplaceUserPassword), so no failure leaves the temporary password in place and a session alive, on the act meant to end them.
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). A password shorter than eight characters is refused, as on every path that sets one. 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.

One rule holds a password's shape on every path that sets one: it is at least eight characters, counted as characters and not as bytes, and a shorter one is 400 saying so. A sign-up, the account an invitation's acceptance makes, a first password, a person's own change, a password set by a flow of the application's own, an operator's temporary password, an account created with one and the hash HashPassword hands the generated user management all hash the password through the one function that asks the rule first, so no path sets a password another would refuse. The hash a sign-in upgrades is of a password the person already holds, and is not asked. | Identities(ctx, id), UnlinkIdentity(ctx, identityID) | The user's identity links; unlinking the last link that can sign in a user with no password is refused (Conflict, sessionstorage.ErrLastSignInMethod): another link must be one a sign-in is still possible through (SignsInThrough), whatever links that sign nobody in remain. A user who holds a password may lose every link. | | SignInMeans(ctx, id) | What the user signs in with (SignInMeans): whether they hold a password, never its hash, and the sign-in methods the login page offers that an identity linked to them signs in through, each by the registration's name and the label its button carries, in the page's order. A link answers the registrations that can still sign the person in through it: of the link's method, offered on the login page, and taking the link's connection, so of two listed Entra registrations a link names the one whose tenants hold its tenant; a method that cannot tell one connection from another answers every registration of it. A link of a method the page no longer offers, or from a tenant or a Workspace no registration takes any more, names nothing, and is no means of sign-in to the removal either. For an administrator's page; the caller guards who may ask about whom. Auth.SignInMeans() is the person's own read over HTTP, answered in the words of the methods list that names its path. SignsInThrough(method, connection) is the judgment itself, for one link. | | DirectoryName(method, connection) | What the Auth's sign-in registrations call the directory an identity of this method and connection came through, for a sentence that names it to a person: the name a registration that takes the connection gives it (signin.Method.ConnectionName: a tenant listed with azure.NamedTenant, a Google Workspace's name or the domain of one admitted as any Workspace, an OpenID Connect provider's name or its issuer's host), and the label of the button of the first registration of the login page that takes the connection; each is empty where the registrations have none. A tenant listed by its id alone (azure.Tenant), one admitted as any tenant, and a method that names no connection have no name, so a sentence says such a directory by the label ("your organization's Microsoft directory") and never by the connection, which for an Entra tenant is an id. It reads nothing. | | RemoveSessionUserPassword(ctx, id) | Removes the user's password, an operator's act: the password then signs nobody in, and the user signs in through an identity linked to them. A user keeps it, their last means of sign-in (Conflict, sessionstorage.ErrLastSignInMethod), unless a link can sign them in: one of a method the login page offers whose registration still takes the link's connection (SignsInThrough), which rules out a user with no link and one whose links are all left over. A user with no password has none to remove (BadRequest). Clears the mark and the name's count of failed sign-ins; the user's sessions stand. PasswordMethod.RemoveUserPassword() is the person's own removal over HTTP, which asks for the password. | | 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". | | SetSessionUserName(ctx, id, name) | An operator's entry of the person's name, or its removal (nil). See "A person's name". | | Invite(ctx, &InvitationRequest{Email, Name, Tenant, RoleNames, InvitedByUserID}), 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. |

A seed that gives a user its roles. A role is held by the id of an account, so a seed needs the id before the user exists. session.SeedUserID(auth, username) is that id, the same on every run: the seed writes the roles under it first and creates the user under it last (CreateUserRequest.ID). The user's row then says the seed is done. A run that stopped before it is repeated whole by the next one, which writes the same memberships again and creates the user. A seed that created the user first would have to give the roles, after a stopped run, to a user it found under a name, and a name is something anyone may come to hold. The generated seed of an auth's first administrator and the persona cast's seed work this way, and seed nothing for a user that exists, whatever it holds. The first administrator is the deployment's first super administrator: the seed writes the Super Administrator role under the id beside the application's own administrator roles, since only a holder of that role makes another. An auth whose roles come from its directory seeds nobody: the directory names its super administrators, as it names every role.

A first administrator who signs in through a directory holds no password, and the seed creates the account under session.SeedUserIDThrough(auth, registration, username): the same id on every run, which also names the sign-in registration the person comes through. In an application whose tenants have directories that id is what links the account at the person's first sign-in (see "A first link on a name alone"): it is the deployment's word on which registration the name is believed from, and it holds while that registration admits one organization alone. The id names the registration and not the organization behind it: a registration pointed at another organization before the person has signed in believes that organization's word instead. The generated foothold seeds its administrator this way where it can name the registration without guessing, for an auth whose one directory method is of one Microsoft Entra tenant or one Google Workspace; for any other auth it seeds for no registration and says how its author names the deployment's own directory.

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 and goes on in a new session that carries the auth events of the one that made it (ChangeSessionUserPassword, below); 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.

Removing a password. A person who signs in through a directory does not need the password they started with. Its removal follows the rule of an identity's unlinking, from the other side: an identity is not unlinked when it is the last one that can sign in a user with no password, and a password is not removed from a user no identity can sign in (409, sessionstorage.ErrLastSignInMethod).

"Linked" means a link that can sign the person in. A row of the identities table is not a way in by being there. A link counts when a sign-in through it is still possible: its method is a registration the login page offers (the methods list, or every registration where the application wrote none), and that registration still takes the link's connection, where the method can tell: an Entra registration asks its tenants, a Google one whether it would write that connection for the account today (a Workspace it still names, an account's own domain while any Workspace is admitted and no named one has taken the domain), a generic OpenID Connect one whether the connection is its own. A method that cannot tell one connection from another counts every link of it. So a link left from a registration the Auth no longer has, or from a tenant taken off the registration, does not hold the password in place of a way to sign in: the person keeps the password until a link that works stands beside it. One judgment says this everywhere (AuthAPI.SignsInThrough): the operator's removal and the person's own are refused by it, the unlink of an identity is refused by it, SignInMeans answers by it, the generated user management refuses and offers by it, and the pages offer the removal by those reads. The library names the links that count to the store, and the store removes the password only while one of them is still linked, in the transaction that removes it, so an unlink asked at once cannot leave the person with neither. An unlink is held the same way from its side: where the person holds no password, UnlinkIdentity hands the store the judgment, and the store asks it of the person's other links in the transaction that unlinks, so the last link that counts is not unlinked while only links that sign nobody in would remain (409, told so and what to do), a link that signs nobody in goes from beside one that counts, and two unlinks asked at once cannot take the person's last two between them. The tenant sign-in policy is not asked: it decides a sign-in from a request no link can stand in for, and it may write. A person whose link passes this judgment and whom the policy would refuse (no tenant of theirs declares the link's directory) is therefore still counted as having a way in.

An operator removes a password with RemoveSessionUserPassword(ctx, id); the person removes their own by posting {"password"}, the password as proof, to the password method's RemoveUserPassword handler, routed beside the change and named to the page as the methods list's removePassword. A wrong password answers 400, and a person no link can sign in is told what to do first: sign in through their directory, which links it. The handler validates the session itself and holds it to what every own-account route but the change holds it to: a person whose operator-set password must change is refused (403, password_change_required), since the removal would clear the mark with the temporary password and no change would have been made. It refuses an impersonated session. Either way the removal takes the password and the mark with it, clears the count of failed sign-ins kept under the user's name, and ends no session: the sessions the user holds stand, the ones the password established among them, as they do when an identity is unlinked. From then on a sign-in with the password is refused exactly as a wrong password is, and counted the same way.

What the pages offer. The server's refusals are the rule: no password to remove is a 400, and a last means of sign-in a 409. A page is told enough not to offer what would be refused. The person's account page reads SignInMeans() (the methods list's signInMeans): it shows the change and the removal only to a person who holds a password, the removal only where a directory sign-in can sign them in, and its question names what is left ("You will sign in through Fleet Google only."). A page whose read fails offers no removal: it does not fall back to naming every method the login page lists. The generated router mounts the read at /user/sign-in-means and names it in the methods list (MethodList.SignInMeans). The read answers in the words of the list that names the path it is served at, so an Auth served on two outlets, each with its own list and its own labels, tells each outlet's page what that outlet's login page calls the method; a read at a path no list names, or one two lists name, answers each method under the label it was first listed under. A page that hides a button is a courtesy and decides nothing.

A write that follows a proof writes over the password that was proved, and no other. Three writes are made on the strength of a password the person just entered: the hash upgrade at a sign-in (a matching password stored under an older algorithm or older parameters is hashed again, unless AutoUpgradeHashes(false)), the person's own change and the person's own removal. Each reads the user, compares the password and then writes, and another write can commit in between: the person changes the password in another window, or an operator resets or removes it. So each hands the store the hash it compared against (UpgradeUserPasswordHash, ChangeUserPassword, RemoveProvenUserPassword), and the store writes only while the row still holds that hash: on PostgreSQL the write's WHERE names it, or the removal compares it under the lock it holds on the user row; on Spanner the hash is read in the transaction that writes. A write that finds another hash, or none, writes nothing (sessionstorage.ErrPasswordChanged, a Conflict), and the other write stands whole, hash and mark. An upgrade that finds the password changed fails its sign-in as a wrong password does, since the password entered is no longer the person's; a change or a removal answers 409 and says the password has changed since it was entered and to try again, with no session ended. Without this an upgrade could put back a password that had just been changed or removed, and a change or a removal could undo an operator's reset on proof of the password it replaced.

What a password proves is inserted only while the person still holds that password. A sign-in compares the password and inserts later: the session, or the pending sign-in the login is held as while a second step waits, up to the pending sign-in's ten minutes. A change, an operator's temporary password or a removal can commit in between, and it ends the person's sessions before the sign-in's own is there to be ended. So the sign-in carries a proof of the password it compared against (sessionstorage.PasswordProof: the SHA-256 of the stored hash, never the hash), and the store inserts only while the user's row still answers to it, compared in the transaction that inserts: the session (SignInRules.Proven), the pending sign-in (PendingSignIn.PasswordProof, kept in the row's PasswordProof column) and the link a password confirmation makes (LinkConfirmedIdentity). On PostgreSQL the user row is read under a share lock a password write waits for, on Spanner in the read-write transaction, so of a sign-in and a password write asked at once either the session is there for the write's ending of the sessions to find, or the sign-in finds the new password and inserts nothing. A pending sign-in completes on the proof its row carries, whichever step completes it (CompletePending, the email code), and a sign-in held again is held with it: once the password was changed, reset or removed, the old password completes nothing, however long the row had left and whatever address the holder gives the code for. A sign-in refused this way is answered as a wrong password is, 401 Invalid Credentials in the same body, and counts as a failed attempt where a password was entered (the login, the confirmation); a completion refused this way leaves its pending sign-in spent, and the person signs in again. A sign-in no password proved (a directory sign-in waiting for its confirmation or its factor, a session the application starts) carries no proof and is held to none. A pending sign-ins table made before the proof takes the column from the auth set's SessionPasswordProofs migration.

An operator's writes follow no proof and overwrite on purpose: ResetSessionUserPassword, SetSessionUserPassword and RemoveSessionUserPassword write whatever the row holds (the store's ReplaceUserPassword and RemoveUserPassword), and so do the generated user management's temporary password and removal, which write the column in the caller's transaction. The operator is not claiming to know the password being replaced, so there is nothing to compare, and their password is to stand whatever the person did a moment before. A reset ends the person's sessions as their own change does, in the transaction that writes the password: the store's ReplaceUserPassword writes the hash and the mark and expires every session of the user together, or does neither, so a failure between the two cannot leave the new password in place with the old sessions alive.

A person's first password

A person who has only ever signed in through a directory holds no password, and the change of a password asks for the old one, so they could never give themselves one. auth.FirstPassword() is how they do, signed in, in two steps:

  • SendCode() takes no body and mails a six-digit code to the address the account holds confirmed, in place of any code that stood, and answers {"codeEmail", "codeExpiresAt"}: the address masked, and when the code stops being accepted (the sign-in code's lifetime, WithEmailCodeTimeout, ten minutes by default).
  • Set() accepts {"code", "password"} and writes the password.

The code ties the password to the mailbox the account holds confirmed: whoever asks must read that mailbox to finish, and a code counts only while the address it was mailed to is still the one the account holds confirmed. It is as strong as that address is: a signed-in person replaces their address with a link mailed to the new one (Email(), above), and a code asked for afterwards goes there. The mail says a code was asked for from a browser where the person is signed in, and tells them to sign out of the browsers they do not use.

What is refused, and how:

Case Answer
The account holds a password 409: it is changed with the old one (PasswordMethod.ChangeUserPassword). The store writes a first password only while the row holds none, decided by the write itself (AuthStore.SetFirstUserPassword, sessionstorage.ErrPasswordHeld otherwise), so of two asked at once one lands.
The Auth has no password method 409: nobody signs in to the application with a password, so there is none to choose.
The account has no confirmed address 409 from SendCode(), saying to add an address and confirm it from the link first (Email(), "Users and their email address"). An address nobody confirmed is not mailed the code: the person has not shown it is theirs, and the code would go wherever whoever typed the address pointed it. A confirmed address no message can be sent to is answered the same way: the simulated build's directories vouch for a person under their login name, so a person signed in through one adds their address first.
The session views as someone else 403, on both routes: an impersonated session changes nothing of the account it looks at, as on every own-account route.
A wrong code 400. The fifth within fifteen minutes ends the code and holds the account's first password for fifteen minutes, whatever codes are asked for meanwhile: 429 with too_many_attempts, the wait, and words that say wrong codes were what was held. A guess takes its attempt before it is judged, counted against the account in the store's one transaction, which says whether it was counted (SignInAttempts.Counted); a guess that was not, the limit reached already, is answered 429 without being compared with the code, so of guesses entered at once no more than five are ever judged, on both databases (the PostgreSQL driver takes the account's attempts row and its lock in one statement, so a failure recorded while the count is cleared is the first after the clear). The right code gives the attempts back.
A code entered when none stands 409: none was sent, or the one sent expired, was used, was replaced by a newer one or was ended by wrong codes.
A password shorter than eight characters 400: the password is held to the rule a sign-up's is. The code still stands.
A sixth code asked for a mailbox that used none of five 429 with too_many_emails and the wait, the limit every code and link shares.

A first password ends no session: the person added a way to sign in, and nothing they held is in doubt. Where the Auth records auth events, the session the person chose it in records a password event beside the ones it had, since the person proved the password is theirs there; the name's count of failed sign-ins is cleared, as a change clears it. The code is kept in the mail links table as a row of the kind first-password that names the account (its hash where a link's row keeps its token's), so it goes with the user, and the guesses are counted in the sign-in attempts table under the account.

The generated router mounts the two routes with the other own-account routes, inside the validated group, where the auth has the password method (/user/first-password/code and /user/first-password), and names them in the methods list. The account page offers "Choose a password" to a person the server says holds none.

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 request takes its place under the limit before anything is mailed, so of links asked for at once no more than five are mailed. 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 rule matches 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 of its own by the username is told of that rename through auth.SetUserRenamed(func(ctx, userID, from, to) error) and moves what it holds. Role memberships are not such a thing: the permission store names a person by the id of their account, which a rename leaves alone. 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.

A person's name

A user may hold a name: the person's name as people read it ("Gale Reyes"), which a page shows in place of the username. It identifies nobody. The username stays what a person signs in under, and a role membership names them by the id of their account, so writing a name renames nobody, ends no session and moves no role. No name is required of any user, and two people may hold the same one. A name is kept without the space around it, a name of nothing but space is no name, and one longer than 200 characters, or one that is not text on one line (a line break, a tab or another control character in it), is refused as a bad request (sessioninfo.CleanName, sessioninfo.MaxNameLength): everything that writes a name holds it to that one rule.

How a name gets onto a user:

  • A directory asserts it at a sign-in. The Google, Microsoft Entra and generic OpenID Connect methods read the name claim and WorkOS the profile's first and last name (sessioninfo.Identity.Name). A sign-in that creates the account writes the name with it. A sign-in to an account that exists fills the name only where the user holds none, after the session stands, so a name the person or an operator wrote is never replaced by the directory's. A name the rule would refuse is dropped before anything of the sign-in is written, and the sign-in stands (sessioninfo.KeptName).
  • An invitation carries it. InvitationRequest.Name is the name the sender gives the person. An account the acceptance creates takes it unless the sign-in asserted a name of its own, and an existing account that accepts takes it only where it holds none.
  • The person writes their own, signed in: Auth.ChangeName() takes {"name"} and answers {"name"}, the name as it is kept, absent when the person now holds none (an empty name takes it off; the next directory sign-in then fills it again). The handler validates the session itself, as the password change does, so it is routed beside it outside ValidateSession, and it refuses an impersonated session: the name is the person's own to write. The generated router mounts it at /user/name and names it in the methods list (MethodList.ChangeName).
  • An operator writes it: CreateSessionUser takes CreateUserRequest.Name, SetSessionUserName(ctx, id, name) replaces the name whatever the user held (nil takes it off), and the management an application generates for an auth's people creates and invites with a name and changes one (Set<Auth>UserName).

The session read (Authenticated) reports name when the user holds one, and UserInfo.Name carries it to the application's handlers.

A users table made before the name existed takes the column from the auth set's SessionNames migration, which also adds the name an invitation carries to the mail links and the name a waiting sign-in's identity asserted to the pending sign-ins, and stores the name in the two indexes a list reads without a row of the table.

The look a person chose

A user may hold a look: light or dark, and one of the palettes the application offers (sessioninfo.Look{Scheme, Palette}). It is the person's own choice for how the application's pages are drawn for them, kept with the account so that it follows them to every browser they sign in from. Nobody else sets it: there is no operator's entry for it, and the management an application generates for an auth's people neither lists nor changes it.

  • The rule (sessioninfo.CleanLook): the scheme is light, dark or none; the palette is an id as the application names its palettes, kept without the space around it and at most 64 characters (sessioninfo.MaxPaletteLength), or none. The session library does not know an application's palettes, so a page drops an id its application no longer offers. A scheme that is neither, a longer id, and an id with a control character in it are a bad request.
  • The person's pages write it, signed in: Auth.ChangeLook() takes {"scheme", "palette"} and answers the look as it is kept, each half absent when the person now holds none. The look is replaced as a whole, so a half left out is taken off. The handler validates the session itself, as the password change does, so it is routed beside it outside ValidateSession, and it refuses an impersonated session: the look is the person's own to choose. The generated router mounts it at /user/look and names it in the methods list (MethodList.ChangeLook).
  • The session read (Authenticated) reports look when the user holds one, and UserInfo.Look carries it to the application's handlers. A browser applies it once the session is checked and keeps a copy of its own for the login page.

A users table made before the look existed takes the two columns, LookScheme and LookPalette, from the auth set's SessionLooks migration.

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, Name, Tenant, RoleNames, InvitedByUserID}) stores the invitation and mails the link; Name, optional, is the name the sender gives the person (see "A person's name"), and NewTenant, in place of a tenant and roles, makes the invitation one that makes a tenant (below). The invitation 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", "tenantId", "tenantName", "newTenant", "directoryOnly", "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, and the invitation is not one accepted with an organization's account alone), 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. tenantId is the tenant the invitation seats the person in, and tenantName what people call it: the person reading the screen is not signed in and can read no tenant record, and a tenant's id says nothing to them, so the application hands each Auth its tenant roster (SetTenantNames(roster), after NewAuth and before serving), which names the tenant from its copy with no read. Without one, or for a tenant it does not know, the name is absent and the screen names no tenant. 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 id 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. Through a method that is invite only the invitation is the account: 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. The hook is told how the person signed in: the invitation it is handed carries SignInMethod and SignInConnection, the method and connection of the sign-in that carries the invitation, and of the session's first auth event for an acceptance by hand (empty for a session that records no events).

  • An invitation that makes a tenant: staff bring an organization into a tenanted application by inviting one person, and that person's first sign-in makes the tenant. The request carries NewTenant (sessioninfo.NewTenant{Name, DirectoryOnly, Details}) in place of a tenant and roles: such an invitation names no tenant and carries no roles, since the tenant does not exist yet and whoever accepts it becomes its first administrator, and the tenant's name is required. Invite and PrepareInvitation answer a bad request, in words, for a request that says otherwise. Name is what the invitation page shows the person before they sign in: Invitation().Open() and the methods listing answer newTenant true and the name as tenantName, with no tenantId, since the tenant has none yet. Details is the application's own JSON document, whatever else staff entered for the tenant: the library stores it with the invitation, hands it to the acceptance hook and reads none of it. No handler of the library answers it, and the mailed message is the message of any invitation: it carries nothing of the tenant, its name included, since a message is read by whoever holds the mailbox before anyone has signed in.

    The acceptance hook makes the tenant. It is handed the invitation with NewTenant and how the person signed in, in the transaction that consumes the invitation, so the tenant, the person's seat in it and the spent invitation are written together or not at all. signin.Directory{Method: inv.SignInMethod, Connection: inv.SignInConnection}.Organization() says whether the person came through an organization's directory (a Google Workspace, a Microsoft Entra tenant), which the hook may then write as the tenant's own. A hook that will not make the tenant answers a sessioninfo.LoginRefusal with a code of its own: the sign-in ends on that code, nothing is written and the invitation stands. sessioninfo.RefusedOrganizationHasTenant (organization_has_tenant) is the code for an organization whose directory another tenant already has; Invitation().Accept() answers it 403 with a sentence that says what to do and nothing of that tenant, the browser still carrying the invitation. An account Invitation().SignUp() made stays where the hook then refuses, as for any invitation: it is created before the sign-in that carries the invitation, holds nothing, and accepts the invitation by signing in once it can be accepted. An Auth with no acceptance hook (SetInvitationAccepted) never consumes an invitation that makes a tenant, since nothing would make it: the sign-in that carries one and the acceptance by hand fail, and the invitation stands.

    DirectoryOnly says the tenant is entered through its organization's directory alone, and the library holds the acceptance to it. A sign-in that carries such an invitation with a password, with a personal account (a Google account in no Workspace, a Microsoft personal account) or through anything else that is no organization's directory is refused (organization_account_required) before anything is read or written: no account is made, and the invitation stands for the sign-in with the organization's account. Invitation().Open() answers directoryOnly true and signUp false for it, so the page offers the directory buttons and no account with a password; Invitation().SignUp() refuses it with the same code before any account is created; and Invitation().Accept() answers a session that was not established through an organization's directory 403 with the sentence, the invitation standing.

  • 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

While an administrator has the password method open to sign-up (its row of the sign-in methods table; see "Open to sign-up, or invite only"), 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 the method's default role, 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.

Every application with the password method and mail (WithMail) routes the three handlers; nothing in code offers or withholds sign-up. While the method is invite only, which it is until an administrator opens it, the handlers answer 404 and Methods leaves the block out of its answer, so the login page offers nothing. Complete makes the account in one transaction that reads the method's row, spends the link, writes the user and gives the default role through the application's hook (SetSignUpSeated): a link mailed while the method was open creates nothing once it is invite only again, and is not spent by the refusal.

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. An attempt takes its place under the limit before its password is compared, so the limit holds however many attempts arrive together (see "Attempts made at once" below). 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. The password a signed-in person proves is held to the same limit, under their own name: the old password of a change (ChangeSessionUserPassword, the method's ChangeUserPassword) and the password a removal asks for (RemoveUserPassword). A wrong one answers 400 as before and counts; a name at the limit answers 429 with too_many_attempts and the wait before anything is hashed, so a session of the person guesses their password no faster than the login lets a stranger. 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.

Attempts made at once. An attempt takes its place under the limit before its password is compared: the store counts it against the name in one transaction and says whether it was counted (AuthStore.RecordSignInFailure, SignInAttempts.Counted), and an attempt that was not, because others made at once with it reached the limit first, is refused with too_many_attempts and the wait without being compared. Of any number of attempts on a name made together, no more than the limit are ever compared with a password, on both databases; the one that reaches the limit is compared itself. A wrong password leaves its place taken, which is its count. A right password gives the place back and resets the name: the row is deleted, whatever lock the attempts in flight beside it earned included, so a person's own sign-ins leave nothing held, and the place is given back though the request was canceled once the password was compared. The client's address and cookie are counted the same way, in memory, in the step that finds them free, and a right password gives that count back too, so the sign-ins of people who share an address leave nothing held against it. The limit so bounds the attempts on a name that are compared at one time, right ones among them: when more sign-ins with the right password than the limit arrive together for one name, the ones past the limit are refused with too_many_attempts until one of the others finishes and resets the name, which an instance that cached the lock learns within five seconds. An application that checks one account's password many times at once (ValidateCredentials for an account its services share) meets those refusals; a higher AttemptLimit avoids them at the price of as many more guesses at every name.

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 by each attempt that takes its place, deleted by a right password, and kept per instance in a cache that trusts a lock 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 counted or hashed, and the store is asked about the name 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.

The generated management of an Auth's people answers this hook to remove a person's role assignments whose period has ended (<auth>identity.Client.SignedIn, the resource package's README, section 21): because the hook runs after the commit and its error is logged, the removal can neither fail a sign-in nor undo one. An application with a hook of its own calls the client's from it.

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, superAdministrators,
	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.

The directory decides who is a super administrator too. A name it asserts that resolves to the Super Administrator role is written like any other, in the global partition, the one place the role is held and the one place it resolves; a person the directory names for that role alone holds a role and signs in; and the role goes at the sign-in where the directory no longer names it, the last holder's included. So such an Auth has the super administrators its directory names and no other, and none is seeded. The library's own second factor for a super administrator (signin.SuperAdministratorFactor) does not hold a sign-in through a method that synchronizes roles: how the directory's people prove who they are is the directory's to say, and the application's sign-in policy still asks what it asks of anyone.

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.

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
})
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 rule provisions and matches users under it. The provider is the one organization the registration is limited to: until an administrator opens the registration to sign-up it is invite only, and opening it admits anyone the provider authenticates (see "Open to sign-up, or invite only"). 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 rule provisions and matches 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 rule (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 rule stores as the tenant key of the links it makes (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.

The entry is also how wide the registration is, which is whom an administrator admits by opening it to sign-up (see "Open to sign-up, or invite only"): the people of the tenants it lists, each by the name azure.NamedTenant gives it; anyone with a Microsoft work or school account under any tenant; anyone with a personal Microsoft account under personal accounts. Every registration is invite only until it is opened.

The name azure.NamedTenant gives a tenant is also what a person reads wherever the application speaks of the tenant's directory: a link's connection is the tenant id, which nobody knows, so AuthAPI.DirectoryName answers the name for it and a sentence says "Lakeside". A tenant listed by its id alone, and every tenant admitted under azure.AnyTenant(), has no name: a sentence then says the directory by the label of the registration's button on the login page, "your organization's Microsoft directory" for a button labeled Microsoft. Name the tenants you list.

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.

Provider-initiated logout

Entra calls the application's front-channel logout URL (FrontChannelLogout) with the sid when the person signs out of Microsoft. The handler ends every session whose sign-in carried that sid under an issuer the registration declares, impersonations started from them included. A registration serving one tenant scopes the request to that tenant's issuer; one serving several, to whichever of its issuers live sessions carry the sid under. A request that names an iss is scoped to it, and refused when no tenant the registration admits has it. 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 rule provisions and matches 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".

The entry is also how wide the registration is, which is whom an administrator admits by opening it to sign-up (see "Open to sign-up, or invite only"): anyone with an account at the domains of the Workspaces it names; anyone with a Google Workspace account under any Workspace; anyone with a Google account under any Google account. Every registration is invite only until it is opened.

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, a password-less user who already signs in through an identity was matched by the sign-in name with no verified address to prove it, 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: the sign-in method is invite only, and the person holds no account and carries no invitation.
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: through a sign-in method that is invite only, 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.
organization_account_required RefusedOrganizationAccountRequired Auth: a sign-in, a sign-up with a password or an acceptance by hand carried an invitation that makes a tenant entered through its directory only, and came through no organization's directory (a password, a personal account, a session established any other way); refused before anything is read or written, no account made and the invitation left standing. The login page asks for a sign-in with the organization's account.
guest_account RefusedGuestAccount Auth: the identity is a guest of its directory (an Entra B2B guest), which the standard account rule refuses.
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 the 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), every tenant that seats the person is directory only, and none of them has that directory as its own.
directory_only RefusedDirectoryOnly Auth, the tenant policy: a sign-in that is not through a directory (a password, a personal account, a session the application started itself) by a person whose every tenant is directory only. A password sign-in by a person who administers one of those tenants is not refused: it is held for the second factor (see "The tenant policy", rule 2).
other_tenant RefusedOtherTenant Never answered by the session library itself: the generated user management answers it from its hooks where the application declared that a person belongs to one tenant (identity.WithOneTenantPerPerson()). The invitation the sign-in carried, or the default role of the directory it came through, would give the person a role in a second tenant; the hook fails the sign-in's transaction, so nothing is consumed and no account is made.
organization_has_tenant RefusedOrganizationHasTenant Never answered by the session library itself: the generated user management answers it from its invitation hook. The invitation the sign-in carried makes a tenant, and the organization's directory the person signed in through is already another tenant's; the hook fails the sign-in's transaction, so no tenant and no account is made and the invitation stands.
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, superAdministrators)

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.

Configuration — Preauth

A Preauth store takes its one configuration the same way, through its own WithCustomSessionData, typed to its transaction, and the session type is built for the same T:

sessionData, err := sessionstorage.NewCustomSessionData[MyData, pgx.Tx]("SessionCustomData", nil)
if err != nil { /* as above */ }

store := sessionstorage.NewPostgresPreauth(pool).WithCustomSessionData(sessionData)
preauth, err := session.NewPreauth[MyData](store, cookieKey)

A Preauth session's row is the caller's: Login is given it (see "Per-call custom data"). A configuration that carries a resolver has it asked for a session started with no row, a Login's with Reason: ReasonPreauth and the username; the request names no user and no identity, since a Preauth keeps none.

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
A config typed to the other backend's transaction given to a store's WithCustomSessionData 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: 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
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, superAdministrators)

// 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
A custom user data configuration on the storage given to NewPreauth Error from NewPreauth, at startup
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, superAdministrators,
    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. A user principal names
// the person as the permission store does, by the id of their account.
id, err := auth.API().StartImpersonatedSession(ctx, w, &session.ImpersonationRequest{
    Actor:      "alice@example.com",
    ActorRealm: "admin-portal",
    Principal:  accesstypes.UserPrincipal(accesstypes.User(bob.ID.String())),
    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 the user principal is the id of the person's account, and the record keeps it in the one text every membership is held under, whatever form of the id the request gave.

A name and an id are kept apart. The permission store names an account by its id and a session with no account (a Preauth session, an actor from another application) by its name, so a name must never read as an id where the two are asked of one store. An Auth refuses a foreign actor whose name parses as an id. Preauth trusts its caller and takes any name, so an application that runs a Preauth session type beside an Auth over one permission store keeps the rule itself: the names it hands Preauth must not read as ids.

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
The actor's account The record carries its id (Impersonation.ActorID, the table's ActorUserId column), read from the source session: the permission store names the actor by it (ActorUser), so the actor's own roles are found under it and a row condition's subject binds to it in a role principal's session None here: ActorID is null, the permission store names the actor by the name the record carries, and the actor holds nothing in this application
The actor's name The username of the source session Any name that does not read as the id of an account: an Auth refuses a foreign actor whose name parses as one (400, in every form the id parser reads), since a text that reads as an id names an account here
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(the id of the account) for an ordinary session
actor     := sessioninfo.ActorFromCtx(ctx)     // == Username unless impersonated: what people read
who       := sessioninfo.ActorUserFromCtx(ctx) // the same person as the permission store names them: the id of their account
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, by the username the session carries — a disabled actor's role session ends with their others. Preauth validates an impersonated session exactly as any other.

  • Identity operations. A person's own account is theirs alone: every handler of the library's that writes to the signed-in person's account refuses a session that views as them, whatever its mask, with 403 and an IdentityOperationBlocked event, before it reads its body. They are ChangeUserPassword and RemoveUserPassword (the password method's), ChangeName, ChangeLook, ForgetBrowser, Email().Add() and Email().Verify() (the address the code of their second factor is mailed to), ApplicationTokens().Create() and ApplicationTokens().Revoke(), Device().Approve() and Device().Deny() (a token and an approved device act as the person for as long as they live) and Invitation().Accept() (which gives the person roles). The routes that only read (ApplicationTokens().List(), Device().Lookup()) answer a view, and Logout and EndImpersonation end it. The generated router registers the routes it mounts behind ValidateSession (the invitation's, the address's, the tokens' and the device's) in front of the application's hook, so what the hook asks of a request, a tenant or a role say, gates the application's generated routes and never a person's own account; and it mounts the read-only mask (EnforceReadOnlyMask) in front of them itself, as it does in front of the generated routes behind the hook. The password's, the name's, the look's and the remembered browser's validate the session themselves, in front of the session check, and the handler's own refusal is what answers a view there. 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 sessions of the application's users, and belongs to no account. On an Auth what is a user's is found by the id of their account: DestroyUserSessions(ctx, userID) ends the user's own sessions under any username, the user-principal impersonations of them and every impersonation they hold as a local actor, their role sessions among them, ending the records Revoked. A local actor's role session is reached through the actor's username: validation loads the actor's user by the username the session carries, and the records a local actor holds are found by the actor's username. So ChangeSessionUserUsername renames the user's live sessions, their role sessions with them, and moves the live records they hold as a local actor to the new name. For a foreign actor the name is borrowed, so an Auth refuses a foreign actor's role principal when that name is already a SessionUsers username (403: the actor logs in as that user, or impersonates it as a user principal), and neither operation touches a session carrying a live foreign role-principal record: a user created later under that name cannot reach the actor's session either. Preauth keeps no accounts, so there a name is all a session has, and there is no user for a foreign actor's name to collide with: PreauthAPI.DestroyAllUserSessions(ctx, username) expires every session under the name but a foreign actor's role session, and every impersonation the name holds as a local actor under other names, ending the records Revoked. 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 a 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). The generated router mounts it by itself in front of an outlet's generated routes, wherever the application's hook registers them, and in front of the routes a signed-in person calls on their own account; a route an application registers by hand, through the hook or on a router of its own, is under it only where the application mounts it, as below. 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.

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 additionally supports custom user data: an app-defined table keyed by the durable user record (SessionUsers), written atomically with user creation and read on demand — it survives logout, expiry, and regeneration, and dies with the user. See the "Custom user data" section of the README.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SeedUserID added in v0.5.0

func SeedUserID(auth, username string) impulse.UUID

SeedUserID returns the id a seed creates a user under: the id of the username within the auth named auth, the same on every run, and the same for a username spelled in another case, which the users table holds to be the same name. A role is held by the id of an account, so a seed that gives a user its roles needs the id before the user exists. It writes the roles under this id first and creates the user under it last (CreateUserRequest.ID): the user's row then says the seed is done, a run that stopped before it is repeated whole, and the same memberships are written again instead of a second set under another id. No other user can come to hold the id: every other id is generated, and a request body cannot name one.

func SeedUserIDThrough added in v0.5.0

func SeedUserIDThrough(auth, registration, username string) impulse.UUID

SeedUserIDThrough returns the id a seed creates a user under who holds no password and signs in through a directory: the first administrator of an auth whose roles the application gives. It is SeedUserID with the name of the sign-in registration the person comes through, so the account's id carries the deployment's word twice: that the account is a seed's, which no request can make (CreateUserRequest.ID), and which of the Auth's registrations the name is believed from.

The second is what the first sign-in needs. Such an account has no password and no link, so nothing but its name ties it to whoever signs in under it, and a directory asserts the names it likes. In an application whose tenants have directories the standard rule therefore links an account created ahead only when something vouches for it (SetDirectoryAdmission), and for this account the deployment does: the Auth's directory admission recognizes the id (DirectorySeatedHook.Seeded) and links the account at its person's first sign-in through that registration, where the registration admits one organization and nobody else. A sign-in under the name through any other registration, a customer's own provider among them, or through a registration open to more than one organization, is refused as a stranger's is.

Seeding an account under this id says that whoever the registration's directory presents under the username is the person: it is for the deployment's own directory, whose sign-in names only its administrators give, and never for a provider that lets a person choose a name. The id names the registration and not the organization behind it, so a registration pointed at another organization before the person has signed in believes that organization's word instead.

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 (the WorkOS method is in an internal package, which an application cannot import). 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, superAdministrators SuperAdministrators, 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. Tx is inferred from the storage: an application writes NewAuth[SessionData, UserData](store, cookieKey, superAdministrators, options...).

superAdministrators says who holds the Super Administrator role (SuperAdministratorsBy, or NoSuperAdministrators for an application with no permission engine). It is an argument and not an option so that no Auth is built without it: a holder always signs in with a second factor, whether or not the application's sign-in rule asks anyone for one. A sign-in the rule allows, or any sign-in where no rule is set, is held for the code the library mails when the person holds the role, unless the sign-in already carries a second factor as any account's may (the directory's attestation, or a browser the person asked to be remembered). So an Auth with super administrators must send mail (WithMail), and NewAuth refuses one that does not.

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", "name", "look", "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. name is the person's name as people read it, present when the user holds one: what a page shows for the person in place of the username, which stays what identifies them. look is the look the person chose ({"scheme", "palette"}, each present where they chose it), present when the user holds one: what their pages draw themselves in on every browser. directory is the organization's directory the session was established through ({"method", "connection"}: a Google Workspace by its connection, a Microsoft Entra tenant by its tenant id), present for a sign-in through one and absent for a password, for a personal account, which is no organization's directory, and for an impersonated session: what a page offers the person to make a tenant's directory.

func (*Auth[S, U, Tx]) ChangeLook added in v0.5.0

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

ChangeLook is the handler a signed-in person's pages call to keep the look the person chose, so it follows them to every browser they sign in from: it accepts {"scheme", "palette"} and answers the look as it is kept, each half absent when the person now holds none. The scheme is light or dark; the palette is an id as the application names its palettes, which the session library does not know, so a page drops one its application no longer offers. A scheme that is neither, or a palette id longer than a user row keeps, is a 400. The look replaces the one held as a whole: a half left out is taken off.

The handler validates the session itself, as the password change does, so it is routed beside it, outside ValidateSession; an impersonated session is refused, since the look is the person's own to choose. Nothing else writes it: no operator's entry and no method of the generated user management.

func (*Auth[S, U, Tx]) ChangeName added in v0.5.0

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

ChangeName is the handler a signed-in person's account page calls to write their own name: it accepts {"name"} and answers {"name"}, the name as it is kept (without the space around it), absent when the person now holds none. A name of nothing but space takes the name off; one longer than a user row keeps is a 400. The name is what pages show for the person in place of the username, which stays what identifies them: changing it renames nobody and ends no session.

The handler validates the session itself, as the password change does, so it is routed beside it, outside ValidateSession; an impersonated session is refused, since the name is the person's own to write. A name a directory asserts at a later sign-in never replaces the one written here; after the name is taken off, the next such sign-in fills it again.

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]) FirstPassword added in v0.5.0

func (a *Auth[S, U, Tx]) FirstPassword() *FirstPasswordHandlers

FirstPassword returns the handlers of a person's first password. It panics on an Auth without mail, as a wiring mistake. On an Auth with no password method the handlers refuse every request: there is no password to choose.

func (*Auth[S, U, Tx]) ForgetBrowser added in v0.4.0

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

ForgetBrowser is the handler a signed-in person's account page calls to forget this browser as a trusted device of theirs (AuthAPI.ForgetTrustedDevice): their next sign-in from it asks for the second factor again, and the other people the browser was remembered for keep theirs. It validates the session itself, as the password change does, so it is routed beside it, outside ValidateSession; an impersonated session is refused. A browser that is not remembered for the person answers 200 too: there is nothing to forget. The session read says whether there is (browserRemembered).

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, with the route that removes the password when the list names it. 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 (for an invitation that makes a tenant, "newTenant" with the tenant's name, and "directoryOnly" where it is accepted through an organization's directory alone), 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. The sign-up block is in the answer only while the password method is open to sign-up: an administrator's choice in the running application, which the answer reads as each request arrives, so a page loaded after the method is opened offers to sign up and one loaded after it is closed does not.

{"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 or the remove-password 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) reach it through signin.Register, so an application never calls it directly. It panics on a registration rule, as refuseRegistration documents, and when a registration that synchronizes roles would stand beside another method, as refuseBeside documents. A person the registration has no account for is decided by its own account rule where it has one, and otherwise by what an administrator chose for the method in the running application: open to sign-up, or invite only, which every method is until it is opened (signin.AccountRule).

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

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

SetDirectoryAdmission sets what a tenanted application gives a person's first sign-in through a tenant's directory: reader, which reads the declaration of the directory the identity came through (signin.DirectoryReader: the tenant whose directory it is, since a directory belongs to one tenant), and hook, which seats the person with the default seat the declaration names. With them the standard rule asks the tenant first: its declaration decides before the sign-in method's own choice, open or invite only. 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 person who has an account is no stranger. One with a password confirms the link with it, and the default seat is given with the link when they hold no role in the tenant. One with no password who has never signed in (an account an administrator created ahead) is tied to the sign-in by nothing but the name the directory asserts, so the identity is linked only when the directory is that of the one tenant the person belongs to, holding a role there and nothing anywhere else (hook.OnlyIn), or the sign-in carries the person's own invitation, or the account is the deployment's own seed for the registration the sign-in came through and that registration admits one organization alone (hook.Seeded, the first administrator of an Auth whose people sign in through a directory); any other sign-in under the name is refused as a stranger is, and says nothing of the account. A directory no tenant declares, and a personal account, which is no organization's directory (signin.Directory.PersonalAccounts), fall to the sign-in method's choice as without them. Set the two after NewAuth and before serving the first request; a nil reader, a hook missing either function, 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]) SetSignUpSeated added in v0.5.0

func (a *Auth[SessionData, UserData, Tx]) SetSignUpSeated(hook SignUpSeatedHook[Tx])

SetSignUpSeated sets the hook that gives a person who signed up through an open sign-in method the method's default role. Whether a method is open is no setting of the Auth's: an administrator chooses it in the running application, for each method, and the choice is a row of the Auth's sign-in methods table (Tables.SignInMethods), which each sign-in reads in its own transaction; a method with no row is invite only. A row that names a role on an Auth with no hook fails the sign-up, so no account is made holding nothing. Set it after NewAuth and before serving the first request; a nil hook, a second call, or a call once the Auth is in use is a wiring mistake and panics, as SetDirectoryAdmission 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]) SetTenantNames added in v0.5.0

func (a *Auth[SessionData, UserData, Tx]) SetTenantNames(names TenantNamer)

SetTenantNames sets what names the tenant an invitation seats a person in. The invitation screen is read by a person who is not signed in, who can read no tenant record and to whom the tenant's key, an id, says nothing: with names, the opened invitation (Invitation().Open()) and the invitation a sign-in methods answer reports carry the tenant's name beside its key (tenantName), and the screen says where the person is invited. Without them, or for a tenant the namer does not know, the name is empty and the screen names no tenant. Set it after NewAuth and before serving the first request; a nil namer, a second call, or a call once the Auth is in use is a wiring mistake and panics, as SetDirectoryAdmission 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 anything of its own by the 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]) SignInMeans added in v0.5.0

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

SignInMeans is the handler a signed-in person's account page reads what they sign in with from: {"password", "directories": [{"name", "label"}]} (see SignInMeans the type), for the session's user and nobody else. The page hides the change and the removal of a password from a person who holds none, offers the removal only where a directory sign-in can sign the person in, and names what the removal leaves by its label. The server's own refusals stand whatever the page shows.

The handler validates the session itself, as the name change does, so it is routed beside it, outside ValidateSession, and its path is named to the page as the methods list's SignInMeans. A session that acts for someone else is answered for the person it acts as, as the session read is. The labels are those of the methods list that names the path the read is served at, so an Auth served on two outlets, each with a list of its own, answers each outlet's page in that outlet's words; a read served at a path no list names, or one that two lists name, answers each method under the label it was first listed under.

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. Every application with the password method and mail routes them: whether sign-up is offered is an administrator's choice in the running application, read 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 old password is checked under the attempt limiter, counted under the user's name as a login is: a wrong one counts, and a name whose attempts reached the limit is refused with a *sessioninfo.LoginRefusal carrying RefusedTooManyAttempts and the wait (sessioninfo.RetryAfterOf), before anything is hashed. The call has no client, so only the name is counted; the password method's ChangeUserPassword handler counts the request's client too. The store is handed the hash the old password matched and writes the new one only while the user still holds it: a password that was changed, reset or removed after this call read the user stands as it is, and the call answers a Conflict that says to try again, with nothing written and no session destroyed. The store writes the password, clears the password change mark and destroys every session of the user, by UserId, in one transaction (AuthStore.ChangeUserPassword): the password is changed and the sessions ended together, or neither is. The caller then continues in a new session (ReasonRegeneration) that carries the auth events of the session the change was made in, its establishment and its factors (continuedAuthEvents); a call with no session of the user's own in the context starts one that records a password event. The new password is held to the rule every password is (acceptedPassword).

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.

A pending identity that a password started, or confirmed, completes only while the user still holds that password: once it was changed, reset or removed, the completion is refused as a wrong password is (Unauthorized, "Invalid Credentials", with sessionstorage.ErrPasswordChanged as its cause), the pending identity stays consumed and the person signs in again.

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).

The link and the session rest on the password that confirmed: both are made only while the user still holds it. A password changed, reset or removed after it was compared links nothing and starts no session; the confirmation is then refused as a wrong password is and counted as one, and the pending identity stays consumed.

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. req.Name, when given, is the person's name, kept without the space around it; one too long to keep is a BadRequest.

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]) DirectoryName added in v0.5.0

func (p *AuthAPI[S, U, Tx]) DirectoryName(method sessioninfo.AuthMethod, connection string) (name, label string)

DirectoryName answers what the Auth's sign-in registrations call the directory an identity of method and connection came through, for a sentence that names it to a person: name is the name a registration that takes the connection gives it (a listed Entra tenant's or Workspace's name, a provider's), "" where none names it, and label is the label of the button of the first registration of the login page that takes the connection, "" where the page offers none. A sentence says the name where there is one and otherwise the directory by the button a person signs in to it with, never the connection itself, which for an Entra tenant is an id. It reads nothing: the answer is what the registrations fixed in code. It closes registration, as every read of the Auth's methods does.

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]) RemoveSessionUserPassword added in v0.5.0

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

RemoveSessionUserPassword removes a user's password: from then on the user signs in through their identity links alone, and a password sign-in under their name is refused as a wrong password is. A user keeps the password, their last means of sign-in (sessionstorage.ErrLastSignInMethod, Conflict), unless an identity linked to them can sign them in: a link counts when its method is a registration the login page offers and that registration still takes the link's connection (signsInThrough), so a link left from a method the Auth no longer offers, or from a tenant or a Workspace its registration no longer takes, does not, and neither does a user with no link at all. The links that count are named to the store, which removes the password only while one of them still stands, in the transaction that removes it, so an unlink asked at once cannot leave the user with neither. A user that holds no password is a BadRequest. The password change mark goes with the password, and the name's sign-in attempts are reset. The user's sessions stand, the ones the password established among them, as a removed identity link's do.

It asks for no proof and removes whatever password the user holds: it is an administrator's removal, or the end of a flow of the application's own that proved who the person is. A person removes their own through the password method's RemoveUserPassword handler, which asks for the password first and removes that password and no other.

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]) SetSessionUserName added in v0.5.0

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

SetSessionUserName writes a person's name on a user, or takes it off (nil, or nothing but space): an operator's entry. The name is kept without the space around it; one longer than sessioninfo.MaxNameLength is a BadRequest, and a user that does not exist a NotFound. It replaces whatever the user held, and stands until it is written again: a later sign-in through a directory fills a name only where the user holds none.

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]) SignInMeans added in v0.5.0

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

SignInMeans answers what a user signs in with (see SignInMeans the type): for an administrator's page, or a flow of the application's own. The caller guards who may ask about whom. A user that does not exist is a NotFound. Each method carries the label it was first listed under.

func (*AuthAPI[S, U, Tx]) SignInMethods added in v0.5.0

func (p *AuthAPI[S, U, Tx]) SignInMethods() []RegisteredMethod

SignInMethods lists the sign-in methods registered on the Auth, in the login page's order, then every other registration by name. It reads nothing: the answer is what the registrations fixed in code. It closes registration, as every read of the Auth's methods does.

func (*AuthAPI[S, U, Tx]) SignsInThrough added in v0.5.0

func (p *AuthAPI[S, U, Tx]) SignsInThrough(method sessioninfo.AuthMethod, connection string) []string

SignsInThrough names the sign-in registrations of the login page that an identity of method and connection (a link's Method and Connection) can sign its person in through, and none for an identity that signs nobody in: see signsInThrough. The generated user management judges a person's links by it, so its refusal of a password's removal is this library's.

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 establishes a session that operates as req.Principal on behalf of req.Actor. A user principal names the person by the id of their account and resolves against the users: a principal that is no id is a BadRequest, a missing user is an error and a disabled one is refused. An actor from another application (req.ActorRealm set) is refused when their name reads as the id of an account, and, for a role principal, when their name is already a user's username.

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. A user that holds no password keeps a means of sign-in: the unlink is refused (sessionstorage.ErrLastSignInMethod, Conflict) unless another identity linked to them can sign them in, by the judgment the removal of a password is held to (signsInThrough). The last link that counts is therefore not unlinked while only links that sign nobody in would remain: one left from a method the Auth no longer offers, or from a tenant or a Workspace its registration no longer takes. The store judges the user's other links in the transaction that unlinks, so two unlinks asked at once cannot take the user's last two between them. A user that holds a password may lose every link; the password of a user with no link that counts is refused the same way (RemoveSessionUserPassword).

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(), while an administrator has the password method open to it); 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 WithSignInMethodsTableName added in v0.5.0

func WithSignInMethodsTableName(name string) AuthOption

WithSignInMethodsTableName sets the name of the group's sign-in methods table. (default: SessionSignInMethods)

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 {
	// ID is the id the new user is created under, for a seed that must know the id
	// before the user exists: one that names its people in rows of its own (who filed a
	// row, whose record a row is), so a development database reads the same on every
	// machine, and one that gives a user its roles before it creates the user
	// (SeedUserID). Null, as everywhere else, has the library generate one. It is set by
	// Go callers alone and never read from a request body. An id another user holds
	// fails, and so does the nil id.
	ID                     impulse.NullUUID `json:"-"`
	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"`
	// Name is the person's name as people read it, nil for none: kept without the
	// space around it, and refused when longer than sessioninfo.MaxNameLength.
	Name *string `json:"name"`
}

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"). Name is the person's name as people read it (see "A person's name").

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] struct {
	Seat   func(ctx context.Context, tx Tx, userID impulse.UUID, username string, seats []signin.DirectorySeat) (committed func(ctx context.Context), err error)
	OnlyIn func(ctx context.Context, tx Tx, userID impulse.UUID, tenant accesstypes.Domain) (bool, error)
	Seeded func(userID impulse.UUID, username, registration string) bool
}

DirectorySeatedHook is the application's half of a tenant directory's admission: what it alone can read and write of a person's roles, in two functions.

Seat seats the user at their first sign-in through a tenant's directory, named by id (the key an application's memberships are held under) and by username (what a log line reads), with seats, the default seat of the tenant whose directory the identity came through, inside the transaction that links the identity to the user, which it is handed: the link is made and the person seated together, or neither. The first sign-in through a directory is the one that makes the link, whether it makes the account too or the account stood before, and whether the link is made at once or once the user's password has confirmed it. The library calls it once for a link: a later sign-in finds the link and gives nothing, so a seat an administrator removed is not given back, and a link that was deleted and is made again is a first sign-in again. It gives a seat only where the person holds no role in the tenant: a person who holds one keeps what they hold. 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. It is not called for no seats. It is held to what InvitationAcceptedHook is: tx alone for its reads and writes, a user the transaction made 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 and no link is left that gave nothing.

OnlyIn reports whether tenant is the only place the user holds anything, read through tx: the user holds a role, or a place in a group, in tenant itself, and nothing in another tenant, in every tenant or outside the tenants. The library asks it before it links an identity, on its sign-in name alone, to an account that has no password and has never signed in. A directory asserts the names it likes, and the link hands whoever it signs in everything the account holds, so such a link is made only through the directory of the one tenant the person belongs to, which is given nothing the tenant's own administrators could not give, or by a sign-in that carries the person's own invitation; any other sign-in under the name is refused as a person no account was created for is.

Seeded is optional and reports whether the account with this id and username is the one the deployment's own seed created for a person who signs in through the registration named: the first administrator of an Auth whose people sign in through a directory, who holds roles for the whole application and belongs to no tenant, so no tenant's directory vouches for them. The seed creates the account under SeedUserIDThrough, and the function answers by that id, which no request can give an account. Such an account is linked on its name at its person's first sign-in through that registration, where the registration admits one organization and nobody else (signin.Audience.OneOrganization) and the account is not disabled; through any other registration, or a wider one, the name links nothing. Nil recognizes no account, and a seeded first administrator is then held to the rule every account created ahead is.

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 FirstPasswordHandlers added in v0.5.0

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

FirstPasswordHandlers are the HTTP handlers of a person's first password.

func (*FirstPasswordHandlers) SendCode added in v0.5.0

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

SendCode takes no body. It mails the signed-in user, who holds no password, a code at the address their account holds confirmed, replacing the code that stood, and answers {"codeEmail", "codeExpiresAt"}: the address masked and when the code stops being accepted. It is refused (409) for an account that holds a password, which is changed with the old one; for an account with no confirmed address, since the code has nowhere to go that the person has shown is theirs (they add and confirm one first, Email()); and on an Auth with no password method. A mailbox sent five codes within fifteen minutes and using none is refused with too_many_emails and the wait, and an account held after five wrong codes with too_many_attempts and the wait. It is refused in an impersonated session. Route it behind ValidateSession.

func (*FirstPasswordHandlers) Set added in v0.5.0

Set accepts {"code", "password"} from the signed-in user who holds no password and writes the password, with the code SendCode mailed. The password is held to the rule a sign-up's is (400 when it is shorter than eight characters). A code that is not the one sent is 400, and the fifth wrong one within fifteen minutes ends the code and holds the account's first password for fifteen minutes (429, too_many_attempts and the wait); a code entered when none stands, because none was sent or the one sent expired, was used or was ended, is 409. It is refused (409) for an account that holds a password and on an Auth with no password method, and in an impersonated session. No session of the user ends, this one among them; where the Auth records auth events, this session records a password event beside the ones it had. It answers {}. Route it behind ValidateSession.

type FirstPasswordRoutes added in v0.5.0

type FirstPasswordRoutes struct {
	SendCode string
	Set      string
}

FirstPasswordRoutes are the paths of the first password 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, the key role memberships are held under, and by username, what a log line reads; a user the same transaction provisioned is buffered in it and is not readable until the commit, so the hook writes under the id 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. The hook is told how the session was established (its first auth event), and an invitation that makes a tenant entered through its directory only is refused (403, naming what to do) for a session that came through no organization's directory, the invitation left standing. 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. An invitation that makes a tenant answers "newTenant" true and the tenant's name as the invitation carries it ("tenantName"; it has no id yet), and "directoryOnly" true where it is accepted through an organization's directory alone: "signUp" is then false, since an account with a password could not accept it, and the page offers the directory buttons. 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. An invitation that makes a tenant entered through its directory only is refused as a sign-in is (organization_account_required) before any account is created. Route it beside the password login, behind ValidateXSRFToken.

type InvitationRequest

type InvitationRequest struct {
	// Email is the address to invite.
	Email string
	// Name is the person's name as the inviter gives it, "" for none: the account the
	// acceptance creates carries it unless the sign-in asserts a name of its own, and
	// an existing account that holds none takes it.
	Name string
	// TenantID is the tenant the invitation seats the person in, "" for the
	// application's global surface.
	TenantID string
	// RoleNames are the roles the acceptance grants, as the application's hook
	// understands them.
	RoleNames []string
	// InvitedByUserID is the user sending the invitation, null when unknown.
	InvitedByUserID impulse.NullUUID
	// NewTenant is the tenant the invitation makes when it is accepted, nil for an
	// invitation into a tenant that exists or into the application's global surface.
	// An invitation that makes a tenant names none and carries no roles (TenantID is
	// "" and RoleNames empty): the application's hook makes the tenant from the
	// details and seats the person in it. The tenant's name is required, since the
	// invitation page shows it.
	NewTenant *sessioninfo.NewTenant
}

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
	// Name is the invited person's name as the inviter gave it, without the space
	// around it; "" for none.
	Name string
	// TenantID is the tenant the acceptance seats the person in, "" for the
	// application's global surface, and RoleNames the roles it grants.
	TenantID  string
	RoleNames []string
	// InvitedByUserID is the user who sent the invitation, null when unknown.
	InvitedByUserID impulse.NullUUID
	// NewTenant is the tenant the invitation makes when it is accepted, nil for none.
	// The caller writes the NewTenant column as NewTenantColumn answers it: the
	// tenant's JSON document, and null when it is nil.
	NewTenant *sessioninfo.NewTenant
	// 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; TenantId is null for the application's global surface (""), InvitedByUserID null when unknown, and NewTenant null for an invitation that makes no tenant. The row is what the sign-in reads when the link is followed, so a row written otherwise is an invitation nobody can accept.

func (*InvitationRow) NewTenantColumn added in v0.5.0

func (r *InvitationRow) NewTenantColumn() (*string, error)

NewTenantColumn renders the row's NewTenant as the mail links table's NewTenant column holds it: the tenant's JSON document, or nil, which is NULL, for an invitation that makes none. It is what the library's own storage writes for an invitation it stores, so a row a caller stores with it is read back as the same tenant.

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 LinkedDirectory added in v0.5.0

type LinkedDirectory struct {
	Name  string `json:"name"`
	Label string `json:"label"`
}

LinkedDirectory is a sign-in method of the login page that an identity linked to a user can sign them in through: the registration's name and the label its button carries, as the methods list gives them (MethodList). Where the page lists two registrations of one method (two Entra tenants), a link answers the ones that take its connection; a method that cannot tell one connection from another answers every registration of it.

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
	// RemovePassword is the path of the password method's RemoveUserPassword handler,
	// where a signed-in person's account page removes their password once they sign in
	// through a directory, or none. It is refused when the password method is not
	// listed.
	RemovePassword string
	// FirstPassword are the paths of the first password handlers
	// (FirstPassword().SendCode() and Set()), where the account page of a signed-in
	// person who holds no password mails them a code and takes the password they
	// choose with it; both or none. They are refused when the password method is not
	// listed.
	FirstPassword FirstPasswordRoutes
	// ForgetBrowser is the path of the Auth's ForgetBrowser handler, where a signed-in
	// person's account page forgets the browser the second factor remembered for them,
	// or none. The page shows the action only where the session says the browser is
	// remembered for the person.
	ForgetBrowser string
	// ChangeName is the path of the Auth's ChangeName handler, where a signed-in
	// person's account page writes their own name, or none.
	ChangeName string
	// SignInMeans is the path of the Auth's SignInMeans handler, where a signed-in
	// person's account page reads what they sign in with (whether they hold a password,
	// and the directory sign-ins that can sign them in), or none. The read answers in
	// this list's labels. Without it the page offers the change of a password to
	// everyone the password method serves and the removal to nobody, since it cannot
	// say what a removal would leave the person.
	SignInMeans string
	// ChangeLook is the path of the Auth's ChangeLook handler, where a signed-in
	// person's pages keep the look the person chose, or none.
	ChangeLook 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. The page
	// is told them only while an administrator has the password method open to
	// sign-up, which the answer reads as each request arrives.
	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); cookie and session options belong to NewAuth. Whether a person with no account may sign up with a password is no option: an administrator opens the method in the running application (see "Sign-up" in the README), and until then it is invite only.

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 old password is checked under the attempt limit, counted under the user's name as a login is: a name at the limit is answered 429 with too_many_attempts and the wait. 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.

func (*PasswordMethod) RemoveUserPassword added in v0.5.0

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

RemoveUserPassword accepts {"password"}, the signed-in user's current password, and removes it: from then on they sign in through their identity links alone. The password must match (400 otherwise), as a change asks, checked under the attempt limit as the change checks the old one (429 with too_many_attempts and the wait for a name at the limit), and a user with no identity link that can sign them in keeps it, their last means of sign-in (409). The user's sessions stand, this one among them. It validates the session itself, so it is routed beside the change, outside ValidateSession and behind ValidateXSRFToken, and refuses a user who must change their password as ValidateSession does (403, password_change_required): a temporary password is changed, not removed. Name its path to Methods (MethodList.RemovePassword) for the account page to offer it.

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 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 record (an Auth's SessionUsers).

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, attached with the store's WithCustomSessionData; 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); a resolver the configuration carries is asked for a session started with none, with the reason and the username alone. 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 AuthAPI.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. Without customData, a resolver the configuration carries runs in the insert's transaction with ReasonPreauth and the username. 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, or the resolver), 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 RegisteredMethod added in v0.5.0

type RegisteredMethod struct {
	// Name is the name the method is registered under on the Auth: "password", or the
	// application's name for an external registration ("google", "lakeside-entra"). It
	// is the key of the method's row of the sign-in methods table.
	Name string
	// Method is the method behind the registration (password, azure, google, oidc).
	Method sessioninfo.AuthMethod
	// Label is what the login page shows for the method, "" for a method the login
	// page does not offer.
	Label string
	// Audience is how wide the method is: the organizations it is limited to, or the
	// kind of account it admits. It is whom opening the method to sign-up admits.
	Audience signin.Audience
	// SyncsRoles reports a method whose directory writes the roles of the people it
	// signs in. Such a method has no choice to make: the directory says who holds a
	// role, a person it gives one is admitted, and one it gives none is refused.
	SyncsRoles bool
	// OwnRule reports a registration that carries an account rule of its own
	// (signin.AccountRule): the application's code decides who may sign in through it,
	// so an administrator neither opens it to sign-up nor makes it invite only.
	OwnRule bool
}

RegisteredMethod is one sign-in method registered on an Auth, as the code that registered it fixed it: what the page where an administrator opens a method to sign-up, or makes it invite only, lists beside the administrator's choice. The choice itself is no part of it: it is a row of the Auth's sign-in methods table (Tables.SignInMethods), keyed by Name.

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 generic OpenID Connect method (oidc.Config.RoleSync). See signin.RoleSyncConfig.

func RoleSync

func RoleSync(manager UserRoleManager) RoleSyncConfig

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

type SignInMeans added in v0.5.0

type SignInMeans struct {
	// Password reports whether the user holds a password.
	Password bool `json:"password"`
	// Directories are the sign-in methods the login page offers that an identity linked
	// to the user can sign them in through, in the page's order (signsInThrough). It is
	// empty, never nil, when none can: the user holds no identity link, or only links
	// that sign nobody in any more, and then the password is their only means of
	// sign-in and its removal is refused.
	Directories []LinkedDirectory `json:"directories"`
}

SignInMeans is what a user signs in with: whether they hold a password, and the directory sign-ins an identity linked to them can sign them in through. It is what a page needs to offer the removal of a password only where it can happen (a password is held, and something else signs the person in) and to say what the removal leaves. The password's hash is no part of it.

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 the method's default role, 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, and a sign-up through a method that was closed since the link was mailed 404: the link is spent, the account made and the role given in one transaction that reads the method's row, or none of it is. 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, as is every token while the password method is not open to sign-up.

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 while the password method is not open to sign-up. 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 SignUpSeatedHook added in v0.5.0

type SignUpSeatedHook[Tx any] = func(ctx context.Context, tx Tx, userID impulse.UUID, username, method, role string) (committed func(ctx context.Context), err error)

SignUpSeatedHook is the application's half of a sign-up through a method an administrator opened: it gives the person the default role the method's row names, inside the transaction that makes their account, which it is handed, so the account is made and holds the role together, or neither. The user is named by id (the key an application's memberships are held under) and by username (what a log line reads); method is the name the method is registered under, and role the row's default role, as the application wrote it there. The library calls the hook for a person the open method alone admitted and made an account for: a person who came with an invitation is given the invitation's roles (InvitationAcceptedHook), and one whose account stood before signs in as before and is given nothing. It is not called where the row names no role, which is what an application whose people get their roles in a tenant writes. It is held to what InvitationAcceptedHook is: tx alone for its reads and writes, a user the transaction made 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-up, so no account is left holding nothing.

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 SuperAdministrators added in v0.5.0

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

SuperAdministrators is what NewAuth is told about the holders of the Super Administrator role (accesstypes.SuperAdministrator), the role the access library defines in every auth. An Auth is not built without one: a holder who signed in with no second factor would be the one account no tenant's sign-in settings shut out, behind a password alone. Build one with SuperAdministratorsBy, or with NoSuperAdministrators for an application that has no permission engine; the zero value is refused.

func NoSuperAdministrators added in v0.5.0

func NoSuperAdministrators() SuperAdministrators

NoSuperAdministrators tells an Auth that nobody of its application is a super administrator, because the application has no permission engine and so no role of any kind. An application whose people hold roles passes SuperAdministratorsBy: with this, a person who holds the Super Administrator role would sign in as anyone else does.

func SuperAdministratorsBy added in v0.5.0

func SuperAdministratorsBy(check signin.SuperAdministratorCheck) SuperAdministrators

SuperAdministratorsBy tells an Auth who its super administrators are: the people check reports. Pass signin.SuperAdministrators over the access library's user manager (on Spanner over resource.SignInRoles of it, as the tenant policy is), built before the Auth. The Auth then holds a holder's sign-in for the code it mails, whatever the application's sign-in rule asks of anyone else (signin.SuperAdministratorFactor), so the Auth must send mail (WithMail): NewAuth refuses one that sends none, and a nil check. A sign-in through a method that synchronizes roles is not held: there the directory is the authority on who is a super administrator, and the application's own rule is asked of that person as of anyone. NewAuth asks such an Auth for mail all the same.

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
	// SignInMethods holds what an administrator chose for each sign-in method: whether
	// it is open to sign-up, and the role a person who signs up through it is given. A
	// method with no row is invite only.
	SignInMethods 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 TenantNamer added in v0.5.0

type TenantNamer interface {
	Name(tenant accesstypes.Domain) string
}

TenantNamer names a tenant by its key: what people call it, "" for a tenant it does not know. The application's tenant roster (resource.TenantRoster) is one, answering from its copy with no read.

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. Role memberships are held by the id of the account and follow nothing; an application that keys anything of its own by the username 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 password attempts of an Auth.
Package attempts limits the 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