auth

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 26 Imported by: 0

README

Authenticate requests before authorizing actions

Use auth to resolve who is acting from verified credentials. The result is an immutable auth.Identity (subject, factors, scopes, optional actor and user record) that any package can read without knowing your application's user type. Parsing an identity header is not verification. Your verifier must check authenticity, expiry, and revocation before returning an identity.

For an existing router routes, handler me, and verifier verifyToken(context.Context, string) (auth.Identity, error):

routes.Use(auth.Middleware(auth.Bearer(verifyToken)), auth.Require())
routes.Get("/me", me)

Requests without credentials remain anonymous until Require rejects them. Invalid credentials stop the chain. Return ErrNoCredentials only when your authenticator has nothing to handle, not for a rejected token. Require defaults to 401 with a Bearer challenge; MiddlewareBuilder.ErrorResponse can replace the response.

Read the identity with request.Identity(r) or auth.FromContext. When the authenticator attached your application user to the identity's record, request.User[User](r) and auth.UserFromContext[User] return it; a record holding another type is reported as absent.

Browser sessions and resource access

Install session middleware and CSRF protection before cookie authentication. Create one auth.NewGuard(provider, store) and share it across authentication, login, and logout. Modules register auth.Credential values with policy.SecondFactor(...) (may finish a parked login) and policy.StepUp(...) (may re-prove a logged-in user). Every login method calls Begin with the subject and the factors it verified and returns outcome.Response(w): 204, or 202 with the user's second-factor methods when a registered credential says one is needed. guard.PendingHandler() (GET), guard.ChallengeHandler() (POST {"method": ...}) and guard.ConfirmHandler() finish a parked login or confirm a logged-in one; they share one per-user attempt count. A session already logged in as that subject keeps its login instead: Begin adds the factors and skips the second-factor rules. web.Post("/logout", guard.LogoutHandler()) owns the logout route: it ends the login, publishes auth.LoggedOut and answers 204, or 303 with LogoutBuilder.Redirect. RequireLevel and guard.RequireFresh protect routes by the factors of the identity, so they also work for tokens; auth.RequireSession keeps credential routes away from tokens. Factor time is the server's clock, and a user who has a step-up method is fresh only through one of them. The provider is asked on every request, so a deleted or disabled user is anonymous. Each login also creates a login record, so a user can list devices with Logins and log them out with Revoke, RevokeOthers and RevokeAll; a revoked device is anonymous on its next request. Handle mutation errors. Rotation does not prove persistence succeeded; session middleware owns saving, renewal, and retirement. Handles select context slots, not separate authorization realms or physical identity fields.

Use gate for permission checks after authentication. Route admission does not authorize every resource: check resource policy in the application operation and scope database queries. Conditional writes or database locking must enforce concurrent invariants.

Look up users without HTTP

auth.NewUserProvider wraps a UserDriver so jobs, MCP tools, and feature packages can find a user by subject and clean up user data through Forget. See the package documentation for the subject rules.

Observe rejection without publishing identity data

Configure auth.MiddlewareBuilder.Events or gate.Builder.Events to publish observations. Authentication rejection carries Method; gate denial carries Method and the zero-based denying Rule. Neither payload carries paths, queries, identities, or raw causes. Paths were removed because they can contain identifiers and credentials. Listeners that previously read Path must select application-owned safe metadata instead; no request-path replacement is populated automatically.

The event context still has request context values. Custom HTTP methods are client-controlled. Select safe attributes rather than dumping contexts or credential errors. Normal HTTP problem instance rendering is unchanged and can include the request path. Every rejection publishes, so keep listeners cheap and place rate limiting before these checks when needed.

Documentation

Overview

Package auth answers two questions for any part of an application: who is acting, and does this user exist. Authentication of HTTP requests, the application user lookup and the cleanup of user data share one vocabulary, the subject, and none of them needs to know the application's user type. Authorization lives in the gate subpackage, and authtest checks drivers and authenticators.

Identity

An Identity says who is acting: a Identity.Subject, the Factor values that were verified, the granted Identity.Scopes, an optional Identity.Actor and the UserRecord the authenticator resolved. It is an immutable value built with NewIdentity and read from a context with FromContext, so jobs, MCP tools and arks can use it without importing the application's user type. Identity.Level is derived from the factors: LevelNone without factors, LevelSingle for factors of one kind and LevelMulti for two distinct kinds among KindKnowledge, KindPossession and KindInherence. KindFederated never counts toward LevelMulti.

A request authenticator may attach the application's own user to the record. UserFromContext returns it by type, and a value of another type is reported as absent, so a mismatch fails closed.

Authenticating requests

An Authenticator turns a request into an Identity. It returns ErrNoCredentials when the request has nothing it understands, so Middleware tries the next one; any other error stops the request. Anonymous requests continue without an identity; Require rejects them. Bearer adapts a token verifier. Require uses MiddlewareBuilder construction policies.

Browser sessions use Guard, described below. Its Guard.Authenticator reads the session record, asks the UserProvider on every request and builds an identity with the stored factors and the provider's UserRecord.

Wiring

Order matters: session, then authentication, then everything that needs the identity (rate limits keyed by user, routes).

r := router.New()
driver, err := auth.NewUserDriver(loadUser, userID)
if err != nil {
	return err
}
users, err := auth.NewUserProvider(driver)
if err != nil {
	return err
}
guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.SecondFactor(totp.Credential()).StepUp(passwords.Credential(), totp.Credential())
})
if err != nil {
	return err
}
r.Use(session.Middleware(store))
r.Use(csrf.Middleware())
r.Use(auth.Middleware(guard.Authenticator(), auth.Bearer(verifyKey)))
r.Use(ratelimit.Middleware(store, func(limiter *ratelimit.Builder) {
	limiter.KeyFunc(func(r *http.Request) string {
		if current, err := request.Identity(r); err == nil {
			return "user:" + current.Subject()
		}

		// Key on the client IP, never on r.RemoteAddr: its ephemeral port
		// gives every connection its own budget. With no trusted proxies
		// this is the limiter's default key; behind a proxy pass its
		// prefixes to ratelimit.TrustedProxyKey.
		return "ip:" + ratelimit.TrustedProxyKey()(r)
	})
}))

r.Post("/login", signIn)
r.Get("/login/second-factor", guard.PendingHandler())
r.Post("/login/second-factor", guard.ChallengeHandler())
r.Post("/logout", guard.LogoutHandler())
r.With(auth.RequireSession()).Post("/confirm", guard.ConfirmHandler())

private := r.With(auth.Require())
private.Get("/me", me)
r.With(gate.Require(isAdmin)).Delete("/users/{id}", deleteUser)

Guard, levels and step-up

Guard turns "this person proved X" into a logged-in session. Every login method (password, OAuth, SAML, passkey) verifies its own credential and then calls Guard.Begin with the subject and every Factor it verified. Begin looks the user up with the provider (a deleted or disabled user is ErrUnauthenticated) and, unless the factors already reach LevelMulti, asks each Credential registered with GuardBuilder.SecondFactor whether the user is enrolled, so core never imports the package that owns the method. With no enrolled method the user is logged in. Otherwise the login is parked as pending and the request stays anonymous. Begin returns an Outcome whose Outcome.Response answers 204, or 202 with the methods to choose from, the same for every login method.

A pending login is finished by two core routes. Guard.PendingHandler (GET) lists the user's methods and spends nothing. Guard.ChallengeHandler (POST {"method": "otp", ...}) finds the registered credential, reserves one of the user's GuardBuilder.MaxAttempts attempts, calls Credential.Verify with the rest of the body and logs the user in, once. The attempt count is per user, shared by all methods, sessions and requests; a wrong code costs the attempt, an infrastructure error refunds it (ErrInvalidCredential). A user over the limit is locked out of the second factor for the challenge window (GuardBuilder.ChallengeTTL). Later lockouts double, up to 24 hours, as wrong codes add up in a 24 hour budget per user even when each window stays under the limit; a successful challenge or Guard.Unlock resets it. A lockout also blocks step-up and can be chained by anyone who knows the password. SecondFactorLocked reports each lockout; the application must subscribe and count it as a failure in its login throttle (ark/access does not yet). A logged-in user proves themselves again with Guard.ConfirmHandler, the same route shape over the methods registered with GuardBuilder.StepUp; it requires a browser session (Identity.Session). Modules that need their method accepted call Guard.MustAccept at composition. Every transition regenerates the session ID.

A session that is already logged in as the subject keeps its login: Begin then adds the factors, keeps the login record and skips the second-factor rules, so a logged-in user who connects a provider or re-authenticates through one is not challenged again and keeps the factors they have. Releases before v0.6.0 replaced the factors and parked the login instead. Guard.LogoutHandler returns the handler of the logout route: it ends the login with Guard.Logout, publishes LoggedOut and answers 204, or 303 with LogoutBuilder.Redirect.

The session holds one record (subject, factors, a hash of the user's UserRecord.Version and a login-record ID) under one key, and a pending login under another. The authenticator compares the version in constant time, so changing the version ends every other session of the user. Sessions written before this layout, under "arkoren:auth:user", are anonymous.

Devices

Every login (Begin without a second factor, and a successful challenge) creates a LoginRecord with a random ID that survives session ID rotation. All records of a user live in one entry of the cache given to NewGuard, under "arkoren:auth:logins", whose lifetime is GuardBuilder.SessionLifetime (set it to the session middleware's maximum lifetime). Guard.Logins lists them and flags the current one, Guard.Revoke, Guard.RevokeOthers and Guard.RevokeAll log devices out, and Guard.LoginsOf serves administrators. The authenticator reads the entry on every request and treats a missing record as ErrNoCredentials, so a revoked device cannot list or revoke devices either; it refreshes LoginRecord.SeenAt at most every five minutes, ignoring a failed write. Records older than the session lifetime are never listed and the next write removes them. At most GuardBuilder.MaxLogins records are kept and the oldest is dropped, which logs that device out. Guard.Logout removes its record and NewGuard registers Guard.RevokeAll with UserProvider.OnForget.

Records hold the user agent (cut to 255 bytes) and client address, which are personal data: GuardBuilder.Devices turns them off, and they never enter telemetry or events. The address is the host of r.RemoteAddr unless GuardBuilder.ClientIP says otherwise; behind a reverse proxy pass ratelimit.TrustedProxyKey from core/http/middleware/ratelimit with your proxy prefixes (it reports IPv6 addresses as their /64 prefix). Writes take a per-user cache lock and compare-and-put with a bounded retry. A flushed cache logs everyone out, and each authenticated session request costs one extra cache read.

Freshness

RequireLevel and Guard.RequireFresh protect routes by the factors of the identity in the context, so they also work for tokens that carry factors. No identity is rejected like Require. Factor time is this server's clock: the guard stamps every factor when it records it, whatever the login method reports, and a factor dated in the future is not fresh. The rule of Guard.Fresh: fresh means a factor of an enrolled GuardBuilder.StepUp method within GuardBuilder.FreshFor (15 minutes by default); a user with no step-up method counts any recent factor. Too weak or too old is ErrStepUpRequired (403) with the user's step-up methods in its "methods" extension, or ErrNoStepUpMethod (403) when the user must log in again. A silent re-login through a provider therefore refreshes a federated-only user but not one with a password. Guard.RecentLogin instead checks the age of the login record, which a same-subject Begin does not reset, for actions that need a new login.

A Factor replaces an older one with the same Method and Kind. Core names only the RFC 8176 methods (MethodPassword, MethodOTP, MethodHardwareKey, MethodSoftwareKey); modules declare their own, and publish CredentialEnrolled after an enrolment. RequireSession and Identity.Session keep credential routes away from bearer tokens. External and Resolver are the shared types for identities asserted by another system.

Hash passwords with the hash package. Precompute dummyHash at startup with the same hasher and cost as real passwords. Checking it for unknown emails reduces timing differences; it does not guarantee identical request times. A missing account or password mismatch is a credential rejection; return database and hash failures without replacing them with ErrUnauthenticated. JSON v2 matches field names case-sensitively, so tag the lower-case request members:

func signIn(w http.ResponseWriter, r *http.Request) error {
	in, err := request.JSON[struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}](r)
	if err != nil {
		return err
	}

	user, err := db.Find[User](r.Context(), query.Table("users", func(statement *query.Builder) {
		statement.Where("email", in.Email)
	}))
	if err != nil && !errors.Is(err, database.ErrNoRows) {
		return err
	}

	found := err == nil
	hashed := dummyHash
	if found {
		hashed = user.PasswordHash
	}
	ok, err := hasher.CheckRaw([]byte(in.Password), hashed)
	if err != nil {
		return err
	}
	if !found || !ok {
		return auth.ErrUnauthenticated
	}

	subject, err := driver.Subject(user) // the user driver of the wiring above
	if err != nil {
		return err
	}

	factor := auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
	outcome, err := guard.Begin(r, subject, factor)
	if err != nil {
		return err
	}

	return outcome.Response(w) // 204, or 202 with the methods to choose from
}

r.With(auth.RequireLevel(auth.LevelMulti)).Post("/payouts", payout)
r.With(guard.RequireFresh(10 * time.Minute)).Delete("/account", destroy)

Browsers send session cookies on cross-site requests, so install csrf.Middleware whenever Guard authenticates browser cookies.

Deleted users

Sessions outlive accounts. Guard.Authenticator asks the provider on every request, and a user that is deleted (ErrUserNotFound) or disabled (ErrUserDisabled) becomes anonymous instead of failing with a 500.

API keys

Look the key up by a non-secret id or hash, and compare secrets in constant time. Bearer validates the header, not your application's key format: even a one-byte token reaches the verifier. This application uses an eight-byte lookup prefix and stores the full token's SHA-256 hash in key.Hash. Reject short tokens before slicing them:

auth.Bearer(func(ctx context.Context, token string) (auth.Identity, error) {
	const prefixLength = 8
	if len(token) < prefixLength {
		return auth.Identity{}, auth.ErrUnauthenticated
	}

	key, err := keys.ByPrefix(ctx, token[:prefixLength])
	if err != nil {
		return auth.Identity{}, err
	}

	sum := sha256.Sum256([]byte(token))
	if subtle.ConstantTimeCompare(sum[:], key.Hash) != 1 {
		return auth.Identity{}, auth.ErrUnauthenticated
	}

	return auth.NewIdentity(key.OwnerSubject, func(principal *auth.IdentityBuilder) {
		principal.Scopes(key.Scopes...)
	}), nil
})

keys.ByPrefix is application code. It must reject unknown or revoked keys with an error other than ErrNoCredentials, which would allow anonymous fallback. Bearer wraps lookup failures as 401 responses while retaining their causes; do not include tokens in errors that can reach logs.

JWT bearer tokens

Verify the signature and claims in the verify function and build the identity from the claims without a database call. The trade-off is revocation lag: a token stays valid until it expires, so keep lifetimes short.

OAuth2 and OIDC

The arkoren.dev/ark/oauth/oauthauth package logs users in through Guard.Begin with a federated factor and verifies OIDC bearer tokens; auth does not import it. arkoren.dev/ark/federation maps its external identities to local subjects.

Subjects

A subject is the stable text reference of a user: 1 to 255 bytes of printable ASCII without spaces. It is case sensitive and compared bytewise. ValidateSubject checks the rule; ErrInvalidSubject reports a violation. NewUserDriver converts between a typed identifier and its subject: strings are used as is, integers become decimal digits, and types implementing encoding.TextMarshaler and (through a pointer) encoding.TextUnmarshaler use their text form. Parsing is canonical: a subject that does not render back to itself, such as "007" or "+1" for an integer, is an invalid subject.

Looking up users

A UserDriver finds one UserRecord by subject. Wrap it with NewUserProvider and call UserProvider.Find. A missing user is ErrUserNotFound; a user that exists but may not act is ErrUserDisabled. Only ErrUserNotFound proves a user is deleted, so cleanup code must never treat any other error as deletion.

Forgetting users

Packages that store data about users register a hook with UserProvider.OnForget. UserProvider.Forget runs the hooks in registration order in the caller's context, so hooks join the caller's database transaction. The first error stops the run and is returned. When every hook succeeded, Forget emits UserForgotten on the bus given to UserProviderBuilder.Events; without a bus nothing is emitted.

Events

With MiddlewareBuilder.Events, Require publishes Rejected ("http.auth.rejected") with the method of every anonymous request it rejects. The response defaults to 401; ErrorResponse can replace it. Paths are not published because they can contain identifiers or credentials. Clients control the event rate, so listeners must be cheap and a rate limiter should sit in front of Require. Payloads carry no identity, credentials, query, or cause. Event contexts still retain request context values; listeners must select safe attributes. These payload limits do not change HTTP problem instance rendering.

Guard.LogoutHandler, built with LogoutBuilder.Events, publishes LoggedOut ("auth.user.logged-out") after a logged-in user logged out. It carries only the subject.

UserForgotten ("auth.user.forgotten") carries only the subject. It means the forget hooks completed, not that a surrounding transaction committed.

Drivers and tests

arkoren.dev/core/auth/memoryauth is an in-memory user driver and arkoren.dev/core/auth/authtest holds the conformance suites: one for every user driver and one for every Authenticator.

Example:

driver, err := auth.NewUserDriver(loadUser, func(user User) int64 { return user.ID })
if err != nil {
	return err
}
users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(app.Events())
})
if err != nil {
	return err
}
record, err := users.Find(ctx, "42")

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUserNotFound reports that no user has the subject. Only this error
	// proves a user is deleted: code that removes data of deleted users must act
	// on it and on nothing else, so a disabled user's data is never removed.
	// A subject that cannot be parsed is [ErrInvalidSubject], never this error.
	//
	// Example:
	//
	//	if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrUserNotFound) {
	//		return users.Forget(ctx, subject)
	//	}
	ErrUserNotFound = errors.New("auth: user not found")

	// ErrUserDisabled reports that the user exists but may not act, for example
	// a suspended account. The user is not deleted: keep its data.
	//
	// Example:
	//
	//	if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrUserDisabled) {
	//		return nil // Skip the user, keep the data.
	//	}
	ErrUserDisabled = errors.New("auth: user disabled")
)
View Source
var CredentialEnrolled = event.NewTopic[CredentialEnrolledEvent]("auth.credential.enrolled")

CredentialEnrolled is published by the modules that enroll credentials (a TOTP authenticator, a passkey, a password) after a first or a new enrolment, with event.Bus.Emit, so an application can tell users that a way to prove their identity was added to their account. Core itself never publishes it: only the module knows when an enrolment succeeded. Emit logs listener errors, so listeners cannot change the outcome of the enrolment.

Example:

events.Emit(ctx, auth.CredentialEnrolled, auth.CredentialEnrolledEvent{
	Subject: subject,
	Method:  auth.MethodOTP,
})
View Source
var ErrInvalidCredential = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:core:auth:invalid-credential")
	details.Title("Invalid credential")
	details.Detail("The credential is not valid.")
	details.Status(http.StatusForbidden)
})

ErrInvalidCredential is the 403 problem for a credential that did not check out: a wrong code or password, or a method the user is not enrolled in. The two look the same on purpose, so a client cannot probe which methods a user has. A Credential.Verify returns an error wrapping it to say "wrong input": the attempt then stays counted against the user's limit (see GuardBuilder.MaxAttempts). Any other error from Verify is an infrastructure failure; the guard refunds the attempt and returns the error unchanged. A locked-out user of Guard.ConfirmHandler receives it too. It is 403, not 401, because the confirm route serves signed-in users and a 401 invites login redirects that would discard their session; the challenge route uses it too, so a client handles one problem for a wrong code.

Example:

func verify(r *http.Request, subject string, input jsontext.Value) (auth.Factor, error) {
	if !checkCode(subject, input) {
		return auth.Factor{}, auth.ErrInvalidCredential
	}
	return auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}, nil
}
View Source
var ErrInvalidSubject = errors.New("auth: invalid subject")

ErrInvalidSubject reports a subject that is not 1 to 255 printable ASCII bytes without spaces, a subject that does not parse as the driver's identifier type or does not render back to itself, and an identifier type that is not a string, an integer or a text-marshaling type.

Example:

if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrInvalidSubject) {
	return err
}
View Source
var ErrNoCredentials = errors.New("auth: no credentials")

ErrNoCredentials is returned by an Authenticator when the request carries nothing it understands, so the next authenticator may try. Invalid credentials must return a different error to stop fallback.

Example:

if r.Header.Get("Authorization") == "" {
	return auth.Identity{}, auth.ErrNoCredentials
}
View Source
var ErrNoStepUpMethod = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:core:auth:no-step-up-method")
	details.Title("No step-up method")
	details.Detail("This session is too old and has no method to confirm it again. Log in again.")
	details.Status(http.StatusForbidden)
})

ErrNoStepUpMethod is the 403 problem returned by Guard.Fresh, Guard.RequireFresh and Guard.RecentLogin when the session is too old to be trusted and the user has no method with which to prove themselves again. The client's only way forward is to log in again.

Example:

if errors.Is(err, auth.ErrNoStepUpMethod) {
	// Send the user to the login page.
}
View Source
var ErrStepUpRequired = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:core:auth:step-up-required")
	details.Title("Step-up required")
	details.Detail("Additional authentication is required to access this resource.")
	details.Status(http.StatusForbidden)
})

ErrStepUpRequired is the 403 problem returned by RequireLevel, Guard.RequireFresh and Guard.Fresh when an authenticated request has not proved enough, or not recently enough. A client should ask the user for one of the methods and retry. Guard.Fresh adds a "methods" extension listing the methods the user is enrolled in, in registration order, which the client answers through Guard.ConfirmHandler; RequireLevel adds none. It is 403, not 401, because the user is authenticated and a 401 invites login redirects that would discard the session. errors.Is matches it whatever the extension.

Example:

if errors.Is(err, auth.ErrStepUpRequired) {
	// Ask the user to confirm with one of the listed methods, then retry.
}
View Source
var ErrUnauthenticated = problem.New(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-09:core:http/auth:unauthenticated")
	details.Title("Unauthenticated")
	details.Detail("Authentication is required to access this resource.")
	details.Status(http.StatusUnauthorized)
})

ErrUnauthenticated is the problem returned when a request has no authenticated identity or presents invalid credentials.

Example:

if _, err := request.Identity(r); err != nil {
	return err // renders as 401
}
View Source
var ErrUnknownMethod = problem.UnprocessableContent().Derive(func(details *problem.Builder) {
	details.Type("tag:arkoren.dev,2026-11:core:auth:unknown-method")
	details.Title("Unknown method")
	details.Detail("The method is not available here.")
})

ErrUnknownMethod is the 422 problem returned by Guard.ChallengeHandler and Guard.ConfirmHandler when the request names no method, or one that is not registered for that route or cannot be completed there (a redirect method has no Credential.Verify). It costs no attempt.

Example:

if errors.Is(err, auth.ErrUnknownMethod) {
	// Show the list of methods again.
}
View Source
var LoggedOut = event.NewTopic[LoggedOutEvent]("auth.user.logged-out")

LoggedOut ("auth.user.logged-out") is published by Guard.LogoutHandler, built with LogoutBuilder.Events, after the logout of a logged-in user succeeded. Logging out an anonymous session, or one whose login was already revoked, publishes nothing. It reports the end of one session login, not of the user's other devices (see Guard.Revoke). Emit logs listener errors instead of returning them, so a listener cannot change the response.

Example:

unsubscribe, err := events.Listen(auth.LoggedOut, onLoggedOut)
if err != nil {
	return err
}
defer unsubscribe()
View Source
var Rejected = event.NewTopic[RejectedEvent]("http.auth.rejected")

Rejected is published when Require, built with MiddlewareBuilder.Events, rejects an anonymous request. The default response is 401; ErrorResponse can override it. Every rejection publishes without deduplication, so a client controls the rate. Listeners must be cheap, and a rate limiter such as the ratelimit middleware should sit in front of Require. Requests that pass publish nothing.

Example:

unsubscribe, err := events.Listen(auth.Rejected, onRejected)
if err != nil {
	return err
}
defer unsubscribe()
View Source
var SecondFactorLocked = event.NewTopic[SecondFactorLockedEvent]("auth.second-factor.locked")

SecondFactorLocked is published by Guard.ChallengeHandler and Guard.ConfirmHandler with event.Bus.Emit, once per lockout, when a wrong credential uses up the user's GuardBuilder.MaxAttempts attempts in a window or takes their 24 hour failure budget to a multiple of it, and only when the bus was set with GuardBuilder.Events. Each lockout lasts the challenge window doubled once per MaxAttempts failures the budget already holds before this one, capped at 24 hours (at the window when that is longer). The budget expires 24 hours after its first failure; a successful challenge or Guard.Unlock clears it. When several requests race to lock, one publishes.

Anyone who knows a subject can lock it, and a locked user cannot finish a pending login, but a fresh password login only needs the first factor, so an attacker can start one after every lockout. The login route's throttle must therefore count a lockout as a failed login. Do not feed it from this event: Emit logs listener errors instead of returning them, so a failing listener would fail open. Ask Guard.LockedOut in the login route instead; it reports the lockout the guard keeps, and its error can fail the login closed. Use the event to notify. A lockout also means someone holds the password: reset it, then call Guard.Unlock.

Example:

unsubscribe, err := bus.Listen(auth.SecondFactorLocked, func(ctx context.Context, locked auth.SecondFactorLockedEvent) error {
	return notify(ctx, locked.Subject, locked.Until)
})
if err != nil {
	return err
}
defer unsubscribe()
View Source
var UserForgotten = event.NewTopic[UserForgottenEvent]("auth.user.forgotten")

UserForgotten is emitted by UserProvider.Forget with event.Bus.Emit after every hook registered with UserProvider.OnForget succeeded, and never when a hook failed. It means "forget hooks completed": the delete may still roll back with the caller's transaction. A listener whose effect needs the delete to be committed wraps that effect in Database.AfterCommit with the event context, which carries the transaction. Emit logs listener errors instead of returning them, so listeners cannot change the outcome of Forget.

Example:

unsubscribe, err := events.Listen(auth.UserForgotten, func(ctx context.Context, forgotten auth.UserForgottenEvent) error {
	return search.Remove(ctx, forgotten.Subject)
})
if err != nil {
	return err
}
defer unsubscribe()

Functions

func Middleware added in v0.3.0

func Middleware(authenticators ...Authenticator) router.Middleware

Middleware tries each authenticator in order and stores the first identity found in the request context. When all return ErrNoCredentials the request continues anonymously; use Require to reject it. Any other error is returned and the handler is not called.

Middleware copies the authenticator slice before returning, so replacing caller-owned entries cannot change the chain. Functions and their captured state remain shared.

Example:

r.Use(auth.Middleware(
	guard.Authenticator(),
	auth.Bearer(verifyKey),
))
Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/router"
)

func main() {
	apiKey := func(r *http.Request) (auth.Identity, error) {
		if r.Header.Get("X-Demo-Key") != "secret" {
			return auth.Identity{}, auth.ErrNoCredentials
		}

		return auth.NewIdentity("service-1"), nil
	}

	r := router.New()
	r.Use(auth.Middleware(apiKey))
	r.Get("/", func(w http.ResponseWriter, r *http.Request) error {
		identity, _ := auth.FromContext(r.Context())
		_, err := fmt.Fprintf(w, "subject=%q", identity.Subject())

		return err
	})

	request := httptest.NewRequest(http.MethodGet, "/", nil)
	request.Header.Set("X-Demo-Key", "secret")
	response := httptest.NewRecorder()
	r.ServeHTTP(response, request)

	fmt.Println(response.Body.String())
}
Output:
subject="service-1"

func NewContext added in v0.3.0

func NewContext(ctx context.Context, identity Identity) context.Context

NewContext returns a context carrying identity. Middleware does this for requests; call it directly in tests.

Example:

ctx := auth.NewContext(context.Background(), auth.NewIdentity("42"))
identity, ok := auth.FromContext(ctx)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	ctx := auth.NewContext(context.Background(), auth.NewIdentity("42"))

	identity, ok := auth.FromContext(ctx)

	fmt.Println(identity.Subject(), ok)
}
Output:
42 true

func Require added in v0.3.0

func Require(configure ...MiddlewareBuilderFunc) router.Middleware

Require returns a middleware that rejects requests without an Identity in the context and, with MiddlewareBuilder.Events, publishes Rejected. The default is 401 with a Bearer challenge; MiddlewareBuilder.ErrorResponse can replace both the problem and its headers. A zero ErrorResponse restores the default. Rejection events omit paths and causes; the HTTP problem's normal instance rendering and request context values are unchanged.

Example:

api := r.With(auth.Require())
Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/router"
)

func main() {
	r := router.New()
	r.With(auth.Require()).Get("/", func(http.ResponseWriter, *http.Request) error { return nil })

	response := httptest.NewRecorder()
	r.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))

	fmt.Println(response.Code, response.Header().Get("WWW-Authenticate"))
}
Output:
401 Bearer

func RequireLevel added in v0.4.0

func RequireLevel(level Level, configure ...MiddlewareBuilderFunc) router.Middleware

RequireLevel returns middleware that admits a request only when its Identity has at least level (see Identity.Level). A request without an identity is rejected like Require does, with the same configuration (MiddlewareBuilder.ErrorResponse and MiddlewareBuilder.Events apply to that case only, and the callbacks run once); an identity that is too weak gets ErrStepUpRequired, for example a single-factor session on a route that needs LevelMulti. Install it after Middleware. It reads the identity from the context, so it also works for authenticators other than Guard.Authenticator, such as tokens that carry factors.

Example:

r.With(auth.RequireLevel(auth.LevelMulti)).Post("/payouts", payout)
Example
package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/router"
)

func main() {
	handler := auth.RequireLevel(auth.LevelMulti)(router.Handler(func(http.ResponseWriter, *http.Request) error {
		return nil
	}))

	identity := auth.NewIdentity("1", func(principal *auth.IdentityBuilder) {
		principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
	})
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	err := handler(httptest.NewRecorder(), r.WithContext(auth.NewContext(r.Context(), identity)))

	fmt.Println(errors.Is(err, auth.ErrStepUpRequired))
}
Output:
true

func RequireSession added in v0.8.0

func RequireSession(configure ...MiddlewareBuilderFunc) router.Middleware

RequireSession returns middleware that admits a request only when its identity comes from a browser session (Identity.Session), which only Guard.Authenticator sets. Mount every route that enrolls, changes or confirms a credential behind it: a bearer token, however it was issued, is rejected with ErrUnauthenticated even though it is authenticated. A request without an identity is rejected like Require does, with the same configuration. Install it after Middleware.

Example:

r.With(auth.RequireSession()).Post("/account/password", changePassword)
Example
package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/router"
)

func main() {
	handler := auth.RequireSession()(router.Handler(func(http.ResponseWriter, *http.Request) error {
		return nil
	}))

	token := auth.NewIdentity("1")
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	err := handler(httptest.NewRecorder(), r.WithContext(auth.NewContext(r.Context(), token)))

	fmt.Println(errors.Is(err, auth.ErrUnauthenticated))
}
Output:
true

func UserFromContext added in v0.3.0

func UserFromContext[U any](ctx context.Context) (U, bool)

UserFromContext returns the application user of type U that the authenticator attached to the identity in ctx, by type-asserting UserRecord.Value of Identity.Record. The boolean is false when there is no identity, no record value, or the value has another type, so a mismatch fails closed.

Example:

if user, ok := auth.UserFromContext[User](r.Context()); ok {
	_ = user.ID
}
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// user is the test user type.
type user struct {
	Name string
}

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Record(auth.UserRecord{Subject: "42", Value: user{Name: "ann"}})
	})
	ctx := auth.NewContext(context.Background(), identity)

	found, ok := auth.UserFromContext[user](ctx)
	_, wrong := auth.UserFromContext[*user](ctx)

	fmt.Println(found.Name, ok, wrong)
}
Output:
ann true false

func ValidateSubject

func ValidateSubject(subject string) error

ValidateSubject returns nil when subject is 1 to 255 bytes of printable ASCII without spaces, the OpenID Connect "sub" rule minus space because some database collations ignore trailing spaces. Store subjects in a column compared bytewise. Otherwise it returns an error wrapping ErrInvalidSubject.

Example:

if err := auth.ValidateSubject("usr_9f1c"); err != nil {
	return err
}
Example
package main

import (
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.ValidateSubject("usr_9f1c"))
	fmt.Println(errors.Is(auth.ValidateSubject("has space"), auth.ErrInvalidSubject))
}
Output:
<nil>
true

Types

type Authenticator added in v0.3.0

type Authenticator func(r *http.Request) (Identity, error)

Authenticator resolves who is acting on a request. It returns ErrNoCredentials when the request has no credentials it handles, which lets the next authenticator try. Any other error stops the chain.

Only return an Identity after verifying credentials. A client-supplied identity header alone is not proof of identity.

The example uses an existing router r and your application's verifyToken function, with signature func(context.Context, string) (auth.Identity, error). The verifier must validate the token before returning an identity and return an error other than ErrNoCredentials for an invalid, expired, or revoked token. Bearer parses the header and delegates verification to that function.

Example:

authenticate := auth.Bearer(verifyToken)
r.Use(auth.Middleware(authenticate), auth.Require())
Example
package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
)

func main() {
	var authenticate auth.Authenticator = func(r *http.Request) (auth.Identity, error) {
		if r.Header.Get("X-Demo-Key") != "secret" {
			return auth.Identity{}, auth.ErrNoCredentials
		}

		return auth.NewIdentity("service-1"), nil
	}

	r := httptest.NewRequest(http.MethodGet, "/", nil)
	_, err := authenticate(r)

	fmt.Println(errors.Is(err, auth.ErrNoCredentials))
}
Output:
true

func Bearer added in v0.3.0

func Bearer(verify func(ctx context.Context, token string) (Identity, error)) Authenticator

Bearer returns an Authenticator for "Authorization: Bearer <token>" requests. Without an Authorization header it returns ErrNoCredentials. A malformed header, or an error from verify, becomes ErrUnauthenticated with a `WWW-Authenticate: Bearer error="invalid_token"` challenge and the cause attached. If verify returns ErrNoCredentials it is passed on.

Example:

r.Use(auth.Middleware(auth.Bearer(func(ctx context.Context, token string) (auth.Identity, error) {
	key, err := keys.Lookup(ctx, token)
	if err != nil {
		return auth.Identity{}, err
	}

	return auth.NewIdentity(key.OwnerSubject), nil
})))
Example
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
)

func main() {
	authenticate := auth.Bearer(func(_ context.Context, token string) (auth.Identity, error) {
		if token != "good" {
			return auth.Identity{}, errors.New("unknown token")
		}

		return auth.NewIdentity("service-1"), nil
	})

	request := httptest.NewRequest(http.MethodGet, "/", nil)
	request.Header.Set("Authorization", "Bearer good")
	identity, err := authenticate(request)

	fmt.Println(identity.Subject(), err)
}
Output:
service-1 <nil>

type Credential added in v0.8.0

type Credential struct {
	// Method names the credential in requests and in [Outcome.Methods]. It is an
	// RFC 8176 value or the module's own; it must not be empty. A registry holds
	// each method once. The factor [Credential.Verify] returns is recorded under
	// this method whatever it sets.
	Method Method

	// Kind is what the credential proves and the default for the factor Verify
	// returns. Verify may return another Kind (a passkey that checked user
	// verification can report [KindInherence]); the session then keeps both.
	Kind Kind

	// Enrolled reports whether subject has this credential. It must not be nil.
	// A true answer makes the method available to the user: it parks logins and
	// is listed in challenges. An error stops the operation that asked, so a
	// failing lookup never loosens a rule.
	Enrolled func(ctx context.Context, subject string) (bool, error)

	// Verify checks the method's input, the request body without its "method"
	// member, for subject and returns the factor it proved. At is set by the
	// guard. An error wrapping [ErrInvalidCredential] means the input was wrong;
	// any other error is an infrastructure failure that refunds the attempt.
	// Verify must not write the response or touch the session. A nil Verify marks
	// a redirect method (for example an external provider): it is listed with
	// the other methods but completed through its own route, so the challenge
	// and confirm handlers answer [ErrUnknownMethod] for it.
	Verify func(r *http.Request, subject string, input jsontext.Value) (Factor, error)
}

Credential is one way a user proves themselves again, registered with GuardBuilder.SecondFactor to finish a parked login or with GuardBuilder.StepUp to re-prove a logged-in user. A module that owns a method (a password, a TOTP authenticator, a passkey) exports its Credential and the application registers it, so core never imports the module and a third-party module cooperates exactly like ours.

Example:

credential := auth.Credential{
	Method: auth.MethodOTP,
	Kind:   auth.KindPossession,
	Enrolled: func(ctx context.Context, subject string) (bool, error) {
		return authenticators.Has(ctx, subject)
	},
	Verify: func(r *http.Request, subject string, input jsontext.Value) (auth.Factor, error) {
		var body struct {
			Code string `json:"code"`
		}
		if err := json.Unmarshal(input, &body); err != nil || !authenticators.Check(r.Context(), subject, body.Code) {
			return auth.Factor{}, auth.ErrInvalidCredential
		}
		return auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}, nil
	},
}
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	credential := auth.Credential{
		Method:   auth.MethodOTP,
		Kind:     auth.KindPossession,
		Enrolled: func(context.Context, string) (bool, error) { return true, nil },
	}

	fmt.Println(credential.Method, credential.Kind, credential.Verify == nil)
}
Output:
otp possession true

type CredentialEnrolledEvent added in v0.8.0

type CredentialEnrolledEvent struct {
	// Subject is the user who enrolled the credential.
	Subject string

	// Method is the method of the enrolled credential, such as [MethodOTP].
	Method Method
}

CredentialEnrolledEvent reports that a user registered a credential. It carries only the subject and the method, never the credential's secret or any personal data.

Example:

unsubscribe, err := events.Listen(auth.CredentialEnrolled, func(ctx context.Context, enrolled auth.CredentialEnrolledEvent) error {
	return notify(ctx, enrolled.Subject, string(enrolled.Method))
})
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	enrolled := auth.CredentialEnrolledEvent{Subject: "1", Method: auth.MethodOTP}

	fmt.Println(enrolled.Subject, enrolled.Method)
}
Output:
1 otp

type External added in v0.8.0

type External struct {
	// Issuer identifies the system that made the assertion, such as the OIDC
	// issuer URL. Together with Subject it names the external account.
	Issuer string

	// Subject is the issuer's stable identifier of the account. It is unique
	// only within Issuer and is not a local subject (see [ValidateSubject]).
	Subject string

	// Email is the address the issuer reports, or "" when it reports none. Match
	// accounts by it only when EmailVerified is true.
	Email string

	// EmailVerified reports whether the issuer vouches that the user controls
	// Email.
	EmailVerified bool

	// Claims holds the remaining verified claims. The resolver owns it after the
	// call; verifiers must not share the map with later requests.
	Claims map[string]any
}

External is an identity asserted by another system, for example the verified claims of an OpenID Connect ID token. It is the shared vocabulary between the module that verifies the assertion (such as ark/oauth) and the module that maps it to a local user: neither imports the other, and core contains no provider interface. An External is a value the verifier already checked; the resolver must still decide what it is allowed to do, in particular whether to trust Email (see EmailVerified).

Example:

external := auth.External{
	Issuer:        "https://accounts.example.com",
	Subject:       "1089",
	Email:         "ada@example.com",
	EmailVerified: true,
}
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	external := auth.External{
		Issuer:        "https://accounts.example.com",
		Subject:       "1089",
		Email:         "ada@example.com",
		EmailVerified: true,
	}

	fmt.Println(external.Issuer, external.EmailVerified)
}
Output:
https://accounts.example.com true

type Factor added in v0.3.0

type Factor struct {
	// Method is how the factor was verified.
	Method Method `json:"method"`

	// Kind is what the factor proves. [Identity.Level] is derived from it.
	Kind Kind `json:"kind"`

	// At is when this server verified the factor. [Guard] sets it from its own
	// clock whatever the caller passed, so a provider's claim about when the user
	// authenticated never makes a factor fresh. The zero time (an identity built
	// by hand) means unknown and is never fresh.
	At time.Time `json:"at"`
}

Factor records one verified proof of identity.

Example:

factor := auth.Factor{
	Method: auth.MethodPassword,
	Kind:   auth.KindKnowledge,
	At:     time.Now(),
}
Example
package main

import (
	"fmt"
	"time"

	"arkoren.dev/core/auth"
)

func main() {
	factor := auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession, At: time.Unix(0, 0)}

	fmt.Println(factor.Method, factor.Kind)
}
Output:
otp possession

type Guard added in v0.7.0

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

Guard turns "this person proved X" into a logged-in browser session. Every login method (password, OAuth, SAML, passkey) calls Guard.Begin after it verified its credential. Begin either logs the user in or, when the user is enrolled in a registered second-factor Credential, parks the login in a pending state in which the request stays anonymous until Guard.ChallengeHandler verifies one of the user's methods. A logged-in user re-proves themselves with Guard.ConfirmHandler against the registered step-up credentials. The factors recorded along the way give Identity.Level, and RequireLevel and Guard.RequireFresh protect routes with them.

A Guard stores one session record (subject, factors, credential version and a login-record ID) under one session key and a pending login under a second, so a login can never be half written. Every transition (Begin, a challenge, a confirmation, Logout) regenerates the session ID, which prevents session fixation.

All methods read the session from the request context with the handle chosen by GuardBuilder.Handle, so session.Middleware must run first; without a session they return session.ErrNoSession (the authenticator returns ErrNoCredentials). Methods change the session in memory; it is saved by the session middleware, so change it before the response headers are written. Concurrent use is safe: a Guard is immutable after construction.

Create one with NewGuard. In an application the build order is user provider, arks, NewGuard, handlers.

Releases before v0.7.0 named this type Login (and NewGuard NewLogin). Before v0.8.0 modules also drove a pending login with Pending, Complete and Fail and a logged-in session with Confirm; those are now internal to the two handlers.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.SecondFactor(totp.Credential()).StepUp(passwords.Credential(), totp.Credential())
})
if err != nil {
	return err
}
r.Use(session.Middleware(store), auth.Middleware(guard.Authenticator()))
Example
guard := exampleGuard()
r := exampleRequest()

outcome, err := guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
identity, _ := guard.Authenticator()(r)

fmt.Println(outcome.Complete(), err, identity.Subject(), identity.Level() == auth.LevelSingle)
Output:
true <nil> 1 true
Example (RateLimitKey)

ExampleGuard_rateLimitKey pins the rate-limit key the package documentation recommends: the client IP without its ephemeral port.

key := ratelimit.TrustedProxyKey()
first, second := exampleRequest(), exampleRequest()
first.RemoteAddr = "198.51.100.7:40001"
second.RemoteAddr = "198.51.100.7:40002"

fmt.Println("ip:"+key(first), key(first) == key(second))
Output:
ip:198.51.100.7 true

func NewGuard added in v0.7.0

func NewGuard(provider *UserProvider, store *cache.Cache, configure ...GuardBuilderFunc) (*Guard, error)

NewGuard returns a Guard over provider. store is the cache the application also gives to session.Middleware; it keeps each user's login records (see Guard.Logins). NewGuard registers Guard.RevokeAll with UserProvider.OnForget, so forgetting a user ends their sessions. It returns an error when provider or store is nil, when GuardBuilder.ChallengeTTL, GuardBuilder.MaxAttempts, GuardBuilder.MaxLogins, GuardBuilder.SessionLifetime or GuardBuilder.FreshFor is not positive, when GuardBuilder.ClientIP is nil, or when a second-factor or step-up Credential has an empty method or a nil Enrolled, or repeats a method of its registry. Construction does no I/O and the callbacks run once, in order.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.ChallengeTTL(10 * time.Minute)
	policy.SecondFactor(totp.Credential())
})
Example
package main

import (
	"context"
	"fmt"
	"time"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/service/cache"
	"arkoren.dev/core/service/cache/memorycache"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, err := auth.NewUserProvider(exampleDriver())

	if err != nil {
		panic(err)
	}

	guard, err := auth.NewGuard(users, cache.New(memorycache.New()), func(policy *auth.GuardBuilder) {
		policy.ChallengeTTL(10 * time.Minute)
	})

	fmt.Println(guard != nil, err)
}
Output:
true <nil>

func (*Guard) Authenticator added in v0.7.0

func (guard *Guard) Authenticator() Authenticator

Authenticator returns the Authenticator to pass to Middleware. It reads only the logged-in session record, never a pending login, so a half-logged-in request stays anonymous. It looks the subject up with the provider on every request and builds an Identity carrying the stored factors and the provider's UserRecord, so UserFromContext returns its Value. It is the only code that sets Identity.Session.

A missing session, an absent or unreadable record, a deleted or disabled user (ErrUserNotFound, ErrUserDisabled), a credential version that no longer matches UserRecord.Version and a login record that was revoked, expired or dropped (see Guard.Revoke) all return ErrNoCredentials, which makes the request anonymous. The version comparison is constant time. Other provider errors and errors reading the login records from the store pass through and stop the chain. The check costs one cache read per request; when the record's SeenAt is older than five minutes the authenticator also tries to refresh it, ignoring a failed write.

Example:

r.Use(session.Middleware(store), auth.Middleware(guard.Authenticator()))
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

handler := auth.Middleware(guard.Authenticator())(func(_ http.ResponseWriter, r *http.Request) error {
	user, _ := auth.UserFromContext[exampleUser](r.Context())
	fmt.Println(user.Role)

	return nil
})

_ = handler(httptest.NewRecorder(), r)
Output:
admin

func (*Guard) Begin added in v0.7.0

func (guard *Guard) Begin(r *http.Request, subject string, factors ...Factor) (Outcome, error)

Begin is the single entry for every login method. Call it after the method verified its credential, passing every factor the login proved: a password login passes one, a passkey that proved possession and inherence passes two. The guard stamps each factor with its own clock (see Factor.At). Begin looks subject up with the provider first: a deleted or disabled user is ErrUnauthenticated, and other provider errors, including ErrInvalidSubject, are returned unchanged. Passing no factor is an error.

When the session is already logged in as subject, Begin adds the factors to the logged-in session (a factor with the same Method and Kind replaces the older one), keeps the login record, skips the second-factor rules, regenerates the session ID and returns a complete outcome. The user already passed every check, so a logged-in user who connects a provider or re-authenticates keeps the factors they have and is never challenged again. Because the login record stays, Guard.RecentLogin does not see such a silent re-login as a new login. A different subject, an anonymous session and a pending login take the path below.

Otherwise, when the factors already reach LevelMulti, Begin logs the user in without a challenge. If not, it asks every credential registered with GuardBuilder.SecondFactor whether the user is enrolled. With no enrolled method it logs the user in; otherwise it replaces any logged-in user with a pending login that expires after GuardBuilder.ChallengeTTL, regenerates the session ID and returns an outcome that is not complete: the request stays anonymous until Guard.ChallengeHandler verifies a method. An error from an Enrolled function fails the login with that error and changes nothing.

Logging in creates a LoginRecord for the device (see Guard.Logins) and removes the record of the login the session replaces, so Begin can also return the cache or lock errors of the record store; the session is then unchanged. A parked login creates its record when the challenge succeeds.

Begin does not verify the credential: call it only after it checked out.

Example:

outcome, err := guard.Begin(r, subject, auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
if err != nil {
	return err
}
return outcome.Response(w) // 204, or 202 with the methods to choose from
Example
guard := exampleGuard()
r := exampleRequest()

outcome, err := guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(outcome.Complete(), err)

_, err = guard.Begin(r, "2", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(errors.Is(err, auth.ErrUnauthenticated))
Output:
true <nil>
true

func (*Guard) ChallengeHandler added in v0.8.0

func (guard *Guard) ChallengeHandler() router.Handler

ChallengeHandler returns the handler of the route that finishes a parked login (see Guard.Begin). It takes a JSON body {"method": "otp", ...}: "method" names one of the methods registered with GuardBuilder.SecondFactor and the other members are that method's input, passed to Credential.Verify. In order, it:

  1. finds the pending login, answering ErrUnauthenticated without one;
  2. decodes the body and answers ErrUnknownMethod (422) for a missing, unregistered or redirect-only method;
  3. reserves one of the user's GuardBuilder.MaxAttempts attempts, shared across all methods and sessions, and answers ErrUnauthenticated once they are used up, discarding the pending login;
  4. answers ErrInvalidCredential for a method the user is not enrolled in, as for a wrong code;
  5. calls Verify. A wrong code (ErrInvalidCredential) keeps the attempt counted, rotates the session ID, and discards the pending login on the last attempt; any other error refunds the attempt and is returned;
  6. on success logs the user in with the factors proved at Begin plus the verified one (creating the LoginRecord), clears the attempt count, rotates the session ID and answers 204.

The attempt limit lives in the shared store, not the session, so a new session, a new Begin or requests forking one pending cookie in parallel cannot reset or exceed it. A lockout lets anyone who knows the subject delay that user's second factor, so also rate-limit by address. The handler needs session.Middleware but not Require.

Example:

web.Post("/login/second-factor", guard.ChallengeHandler())
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

wrong := exampleChallenge(guard.ChallengeHandler(), r, `{"method":"otp","code":"bad"}`)
right := exampleChallenge(guard.ChallengeHandler(), r, `{"method":"otp","code":"ok"}`)
identity, _ := guard.Authenticator()(r)

fmt.Println(errors.Is(wrong, auth.ErrInvalidCredential), right, identity.Level() == auth.LevelMulti)
Output:
true <nil> true

func (*Guard) ConfirmHandler added in v0.8.0

func (guard *Guard) ConfirmHandler() router.Handler

ConfirmHandler returns the handler of the route that lets a logged-in user prove themselves again. It works like Guard.ChallengeHandler against the methods registered with GuardBuilder.StepUp, with the same body, order, shared attempt count and refund rule, except that there is no pending login: it requires an Identity with Identity.Session in the request context (install Middleware with Guard.Authenticator before it), answering ErrUnauthenticated otherwise, so a bearer token can never confirm. A user who used up their attempts, or who is locked out (the lockout blocks step-up too, and lasts up to 24 hours; see GuardBuilder.MaxAttempts and Guard.Unlock), gets ErrInvalidCredential, like a wrong code. On success it records the factor on the session (a factor with the same Method and Kind replaces the older one, so Guard.Fresh passes), gives back the attempt it reserved, rotates the session ID and answers 204. It leaves the count of wrong codes alone, so confirming one method never resets the limit on guessing another. The session this guard holds must be logged in as the identity's subject, otherwise the answer is ErrUnauthenticated.

Example:

web.With(auth.RequireSession()).Post("/confirm", guard.ConfirmHandler())
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.StepUp(exampleOTP)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

handler := auth.Middleware(guard.Authenticator())(guard.ConfirmHandler())
err := exampleChallenge(handler, r, `{"method":"otp","code":"ok"}`)
identity, _ := guard.Authenticator()(r)

fmt.Println(err, len(identity.Factors()))
Output:
<nil> 2

func (*Guard) Fresh added in v0.8.0

func (guard *Guard) Fresh(r *http.Request) error

Fresh reports whether the request's identity proved itself recently enough, with the window of GuardBuilder.FreshFor (15 minutes by default). It is the check behind Guard.RequireFresh, for handlers that decide inside the route.

The rule: fresh means a factor of one of the user's enrolled GuardBuilder.StepUp methods that this server verified within the window. A user enrolled in no step-up method cannot prove anything else, so any factor within the window counts, which makes a federated-only user fresh right after logging in. A silent re-login through a provider adds a factor that is not a step-up method, so it never refreshes a user who has a password or an authenticator. A factor with an unknown (zero) or future time is not fresh.

It returns nil when fresh; ErrStepUpRequired with the user's enrolled step-up methods in its "methods" extension when the user can step up; and ErrNoStepUpMethod when they cannot and must log in again. A request without an identity is ErrUnauthenticated. An error from a credential's Enrolled passes through, so a failing lookup never relaxes the rule.

Example:

if err := guard.Fresh(r); err != nil {
	return err
}
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

handler := auth.Middleware(guard.Authenticator())(func(_ http.ResponseWriter, r *http.Request) error {
	fmt.Println(guard.Fresh(r))

	return nil
})

_ = handler(httptest.NewRecorder(), r)
Output:
<nil>

func (*Guard) LockedOut added in v0.9.0

func (guard *Guard) LockedOut(ctx context.Context, subject string) (bool, error)

LockedOut reports whether subject is inside a second-factor lockout, the escalating block that Guard.ChallengeHandler and Guard.ConfirmHandler start when a user uses up their GuardBuilder.MaxAttempts (see SecondFactorLocked). While it lasts every challenge or confirmation of the subject fails without verifying anything, in any session. It only reads the lockout entry, which expires on its own: it reserves no attempt, counts no failure and never starts or extends a lockout, so it is safe to call on every request. A cache failure is returned with false; decide for yourself whether to fail closed.

Use it for control flow, such as a login route that must not refund a login throttle while the user is locked, because a correct password then only parks a pending login that cannot finish. Do not use SecondFactorLocked for that: event.Bus.Emit logs listener errors instead of returning them, so a failing listener would fail open.

Example:

locked, err := guard.LockedOut(ctx, subject)
if err != nil {
	return err
}
if locked {
	return errors.New("second factor locked")
}

func (*Guard) Logins added in v0.7.0

func (guard *Guard) Logins(r *http.Request) ([]LoginRecord, error)

Logins returns the login records of the request's user, oldest first, with LoginRecord.Current set on the record of this request's own login. It returns ErrUnauthenticated when the session holds no logged-in user, its user was deleted or disabled, its credential version no longer matches UserRecord.Version (the checks of Guard.Authenticator) or its own login was revoked, and session.ErrNoSession without a session. Mount it behind Require.

Example:

records, err := guard.Logins(r)
if err != nil {
	return err
}
return response.JSON(w, http.StatusOK, records)
Example
guard := exampleGuard()
first := exampleRequest()
_, _ = guard.Begin(first, "1", examplePassword)
_, _ = guard.Begin(exampleRequest(), "1", examplePassword)

records, _ := guard.Logins(first)

fmt.Println(len(records), records[0].Current, records[1].Current)
Output:
2 true false

func (*Guard) LoginsOf added in v0.7.0

func (guard *Guard) LoginsOf(ctx context.Context, subject string) ([]LoginRecord, error)

LoginsOf returns the login records of subject, oldest first, for administration. It returns an error wrapping ErrInvalidSubject for an invalid subject and no records, not an error, for a user without logins. The records are personal data.

Example:

records, err := guard.LoginsOf(ctx, subject)
if err != nil {
	return err
}
fmt.Println(len(records), "devices")
Example
guard := exampleGuard()
_, _ = guard.Begin(exampleRequest(), "1", examplePassword)

records, err := guard.LoginsOf(context.Background(), "1")

fmt.Println(len(records), err)
Output:
1 <nil>

func (*Guard) Logout added in v0.7.0

func (guard *Guard) Logout(r *http.Request) error

Logout removes the logged-in session record, its login record and any pending login, even stale or unreadable ones, and regenerates the session ID. Other session data and its lifetime stay; use session.Session.Destroy to remove the whole session.

Example:

if err := guard.Logout(r); err != nil {
	return err
}
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

fmt.Println(guard.Logout(r))

_, err := guard.Authenticator()(r)
fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output:
<nil>
true

func (*Guard) LogoutHandler added in v0.7.0

func (guard *Guard) LogoutHandler(configure ...LogoutBuilderFunc) router.Handler

LogoutHandler returns the handler of the logout route, the single owner of that route. It reads the identity that Middleware stored, calls Guard.Logout (which ends the logged-in session, its login record and any pending login, and regenerates the session ID), publishes LoggedOut when the request had an identity, and answers 204 No Content, or 303 See Other to LogoutBuilder.Redirect.

Logging out a session without a logged-in user succeeds and publishes nothing. A request without a session returns session.ErrNoSession (500, a wiring mistake). A nil guard or an unsafe redirect target is a configuration error returned on every request, before any session change. Other Guard.Logout errors are returned unchanged and publish nothing. The callbacks run once, when LogoutHandler is called, so build the handler at startup rather than per request.

Register it for POST only, behind CSRF protection: a GET logout lets any page log users out. Token clients log out on their own route, since a bearer token is a different credential.

Example:

web.Post("/logout", guard.LogoutHandler())

web.Post("/sign-out", guard.LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Redirect("/")
}))
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
w := httptest.NewRecorder()

err := auth.Middleware(guard.Authenticator())(guard.LogoutHandler())(w, r)
_, authErr := guard.Authenticator()(r)

fmt.Println(err, w.Code, errors.Is(authErr, auth.ErrNoCredentials))
Output:
<nil> 204 true

func (*Guard) MustAccept added in v0.8.0

func (guard *Guard) MustAccept(method Method)

MustAccept panics unless method is registered in the GuardBuilder.SecondFactor or GuardBuilder.StepUp registry. A module that cannot work without its method being accepted by the application's guard (a TOTP module whose enrolment routes assume challenges accept "otp") calls it at composition time, so a miswired application fails at startup instead of leaving users unable to log in. It reads only the immutable settings and is safe for concurrent use.

Example:

guard.MustAccept(auth.MethodOTP)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})

guard.MustAccept(auth.MethodOTP)

fmt.Println("accepted")
Output:
accepted

func (*Guard) Pending added in v0.7.0

func (guard *Guard) Pending(r *http.Request) (PendingLogin, error)

Pending returns the login parked by Guard.Begin: the subject and the second-factor methods the user can use now. It is read-only: it spends no attempt, so a page can call it freely to render the choice of methods (see Guard.PendingHandler). It returns ErrUnauthenticated when there is no pending login, it expired (which also clears it), the user was deleted or disabled, its UserRecord.Version changed (for example by a password change) in the meantime (which discards it), or the user is locked out by GuardBuilder.MaxAttempts. Other provider, store and Enrolled errors pass through.

Example:

pending, err := guard.Pending(r)
if err != nil {
	return err
}
fmt.Println(pending.Methods)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

_, first := guard.Pending(r)
_, second := guard.Pending(r)

fmt.Println(first, second)
Output:
<nil> <nil>

func (*Guard) PendingHandler added in v0.8.0

func (guard *Guard) PendingHandler() router.Handler

PendingHandler returns the handler of the route that tells a client which second-factor methods it can use: GET answers 200 with {"methods":["otp"]}. It calls Guard.Pending, so it spends no attempt, and returns its errors; an anonymous request without a pending login gets ErrUnauthenticated. Mount it on the same router stage as the login route, without Require.

Example:

web.Get("/login/second-factor", guard.PendingHandler())
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)
recorder := httptest.NewRecorder()

err := guard.PendingHandler()(recorder, r)

fmt.Println(recorder.Code, strings.TrimSpace(recorder.Body.String()), err)
Output:
200 {"methods":["otp"]} <nil>

func (*Guard) RecentLogin added in v0.8.0

func (guard *Guard) RecentLogin(r *http.Request, within time.Duration) error

RecentLogin reports whether the request's session was created, by a login and not by a later Guard.Begin of the same user, within the last within. It is the check for actions that need a new login rather than freshness, such as exchanging a session for a long-lived device token: a silent re-login by the same subject keeps the login record and its creation time, so it cannot extend the window, and neither can Guard.ConfirmHandler. It returns nil when the login is recent; ErrNoStepUpMethod when it is older, or within is zero or less, because only a new login helps; and ErrUnauthenticated when the session holds no logged-in user, its user was deleted or disabled, its credential version no longer matches UserRecord.Version or its own login was revoked. It returns session.ErrNoSession without a session and passes store errors through.

Example:

if err := guard.RecentLogin(r, 5*time.Minute); err != nil {
	return err
}
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

fmt.Println(guard.RecentLogin(r, 5*time.Minute))
Output:
<nil>

func (*Guard) RequireFresh added in v0.8.0

func (guard *Guard) RequireFresh(maxAge time.Duration, configure ...MiddlewareBuilderFunc) router.Middleware

RequireFresh returns middleware that admits a request only when Guard.Fresh passes with the window maxAge instead of the guard's GuardBuilder.FreshFor, so a long-lived session cannot delete an account without a recent password or second factor. A maxAge of zero or less admits nothing. Failures are those of Guard.Fresh. A request without an identity is rejected like Require does, with the same configuration. Install it after Middleware.

Example:

r.With(guard.RequireFresh(10 * time.Minute)).Delete("/account", destroy)
Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/router"
	"arkoren.dev/core/service/cache"
	"arkoren.dev/core/service/cache/memorycache"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

// exampleGuard returns a login over exampleDriver; policy callbacks configure it.
func exampleGuard(configure ...auth.GuardBuilderFunc) *auth.Guard {
	users, err := auth.NewUserProvider(exampleDriver())

	if err != nil {
		panic(err)
	}

	guard, err := auth.NewGuard(users, cache.New(memorycache.New()), configure...)

	if err != nil {
		panic(err)
	}

	return guard
}

func main() {
	guard := exampleGuard()
	handler := guard.RequireFresh(10 * time.Minute)(router.Handler(func(http.ResponseWriter, *http.Request) error {
		return nil
	}))

	identity := auth.NewIdentity("1", func(principal *auth.IdentityBuilder) {
		principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge, At: time.Now()})
	})
	r := httptest.NewRequest(http.MethodGet, "/", nil)

	fmt.Println(handler(httptest.NewRecorder(), r.WithContext(auth.NewContext(r.Context(), identity))))
}
Output:
<nil>

func (*Guard) Revoke added in v0.7.0

func (guard *Guard) Revoke(ctx context.Context, subject string, ids ...string) error

Revoke logs the devices with the given record IDs out: each device's next request is anonymous, because the authenticator no longer finds its record. Unknown IDs are ignored, so it is idempotent. It returns an error wrapping ErrInvalidSubject for an invalid subject, and cache or lock errors; after an error nothing is guaranteed to have been revoked, so retry.

Example:

if err := guard.Revoke(r.Context(), subject, r.PathValue("id")); err != nil {
	return err
}
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)
records, _ := guard.Logins(r)

fmt.Println(guard.Revoke(context.Background(), "1", records[0].ID))

_, err := guard.Authenticator()(r)
fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output:
<nil>
true

func (*Guard) RevokeAll added in v0.7.0

func (guard *Guard) RevokeAll(ctx context.Context, subject string) error

RevokeAll logs every device of subject out by deleting the subject's record list. It returns an error wrapping ErrInvalidSubject for an invalid subject. NewGuard registers it with UserProvider.OnForget, so forgetting a user ends their sessions.

Example:

if err := guard.RevokeAll(ctx, subject); err != nil {
	return err
}
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

fmt.Println(guard.RevokeAll(context.Background(), "1"))

records, _ := guard.LoginsOf(context.Background(), "1")
fmt.Println(len(records))
Output:
<nil>
0

func (*Guard) RevokeOthers added in v0.7.0

func (guard *Guard) RevokeOthers(r *http.Request) error

RevokeOthers logs every device of the request's user out except the one that made the request. It returns ErrUnauthenticated, revoking nothing, when the session holds no logged-in user, its user was deleted or disabled, its credential version no longer matches UserRecord.Version or its own login was revoked, and session.ErrNoSession without a session.

Example:

if err := guard.RevokeOthers(r); err != nil {
	return err
}
Example
guard := exampleGuard()
mine, other := exampleRequest(), exampleRequest()
_, _ = guard.Begin(mine, "1", examplePassword)
_, _ = guard.Begin(other, "1", examplePassword)

fmt.Println(guard.RevokeOthers(mine))

_, err := guard.Authenticator()(other)
fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output:
<nil>
true

func (*Guard) Unlock added in v0.9.0

func (guard *Guard) Unlock(ctx context.Context, subject string) error

Unlock ends the second-factor lockout of subject at once and forgets its escalation: it deletes the lockout, the 24 hour failure budget and the current window's attempt count, so the user has GuardBuilder.MaxAttempts fresh attempts and the next lockout starts again at one window. Call it where the application has proven the user another way: after a password reset, from an administrator's console, or from a recovery flow. It is safe to call for a subject that is not locked.

A lockout is not only an attacker's slowdown: anyone who holds the password can start pending logins and spend the attempts, chaining lockouts of up to 24 hours each, which locks the real user out of the second factor and of step-up. Treat a SecondFactorLocked event as a sign that the password is known to someone else, and reset it when you unlock. It returns the first cache error. The lockout entry is deleted last, so a partial failure leaves the user locked (never unlocked with the old escalation still counted); call it again.

Example:

if err := guard.Unlock(ctx, subject); err != nil {
	return err
}

type GuardBuilder added in v0.7.0

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

GuardBuilder configures NewGuard before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic. Methods return the same draft, and retaining it cannot change a published guard.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.ChallengeTTL(10 * time.Minute).MaxAttempts(3)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.ChallengeTTL(time.Minute).MaxAttempts(3).SecondFactor(exampleOTP)
})

outcome, err := guard.Begin(exampleRequest(), "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

fmt.Println(outcome.Complete(), err)
Output:
false <nil>

func (*GuardBuilder) ChallengeTTL added in v0.7.0

func (policy *GuardBuilder) ChallengeTTL(ttl time.Duration) *GuardBuilder

ChallengeTTL sets how long a pending login (see Guard.Begin) accepts its second factor. The default is five minutes. NewGuard rejects a value of zero or less. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.ChallengeTTL(10 * time.Minute)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP).ChallengeTTL(10 * time.Minute)
})
r := exampleRequest()

outcome, err := guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

fmt.Println(outcome.Complete(), err)
Output:
false <nil>

func (*GuardBuilder) ClientIP added in v0.7.0

func (policy *GuardBuilder) ClientIP(find func(*http.Request) string) *GuardBuilder

ClientIP sets how the address of a login record is found. The default is the host of r.RemoteAddr, which behind a reverse proxy is the proxy. Behind a proxy, pass a function that trusts forwarded headers only from your proxies: ratelimit.TrustedProxyKey (package core/http/middleware/ratelimit) returns such a function. It reports IPv4 addresses as they are but reduces IPv6 addresses to their /64 prefix, which is what the record then stores. The result is cut to 255 bytes. NewGuard rejects nil. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.ClientIP(ratelimit.TrustedProxyKey(netip.MustParsePrefix("10.0.0.0/8")))
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.ClientIP(ratelimit.TrustedProxyKey(netip.MustParsePrefix("10.0.0.0/8")))
})
r := exampleRequest()
r.RemoteAddr = "10.0.0.1:4711"
r.Header.Set("X-Forwarded-For", "198.51.100.2")
_, _ = guard.Begin(r, "1", examplePassword)

records, _ := guard.Logins(r)

fmt.Println(records[0].IP)
Output:
198.51.100.2

func (*GuardBuilder) Devices added in v0.7.0

func (policy *GuardBuilder) Devices(enabled bool) *GuardBuilder

Devices selects whether login records keep the User-Agent and client address of each login, which is what makes the device list readable. The default is true. With false the records hold only IDs and times. Both values are personal data; they are never put in telemetry or events. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.Devices(false)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.Devices(false)
})
r := exampleRequest()
r.Header.Set("User-Agent", "Firefox")
_, _ = guard.Begin(r, "1", examplePassword)

records, _ := guard.Logins(r)

fmt.Printf("%q\n", records[0].UserAgent)
Output:
""

func (*GuardBuilder) Events added in v0.9.0

func (policy *GuardBuilder) Events(bus *event.Bus) *GuardBuilder

Events sets the bus that receives SecondFactorLocked when a user is locked out of the second factor. Nil, the default, publishes nothing. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.Events(app.Events())
})

func (*GuardBuilder) FreshFor added in v0.8.0

func (policy *GuardBuilder) FreshFor(window time.Duration) *GuardBuilder

FreshFor sets how recent a factor must be for Guard.Fresh to accept it. The default is 15 minutes. Guard.RequireFresh takes its own window per route. NewGuard rejects a value of zero or less. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.FreshFor(5 * time.Minute)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.FreshFor(5 * time.Minute)
})

fmt.Println(guard != nil)
Output:
true

func (*GuardBuilder) Handle added in v0.7.0

func (policy *GuardBuilder) Handle(handle session.Handle) *GuardBuilder

Handle selects the request session bridge shared with session.Middleware, so one application can run several independent sessions. Zero, the default, selects the default bridge. It changes neither cookie nor storage policy. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.Handle(adminSession)
})
Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/session"
	"arkoren.dev/core/service/cache"
	"arkoren.dev/core/service/cache/memorycache"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

// exampleGuard returns a login over exampleDriver; policy callbacks configure it.
func exampleGuard(configure ...auth.GuardBuilderFunc) *auth.Guard {
	users, err := auth.NewUserProvider(exampleDriver())

	if err != nil {
		panic(err)
	}

	guard, err := auth.NewGuard(users, cache.New(memorycache.New()), configure...)

	if err != nil {
		panic(err)
	}

	return guard
}

func main() {
	handle := session.NewHandle()
	guard := exampleGuard(func(policy *auth.GuardBuilder) {
		policy.Handle(handle)
	})

	r := httptest.NewRequest(http.MethodGet, "/", nil)
	r = r.WithContext(session.NewContextFor(r.Context(), handle, session.New(time.Now().Add(time.Hour), map[string]any{})))

	outcome, err := guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

	fmt.Println(outcome.Complete(), err)
}
Output:
true <nil>

func (*GuardBuilder) MaxAttempts added in v0.7.0

func (policy *GuardBuilder) MaxAttempts(attempts int) *GuardBuilder

MaxAttempts sets how many credential checks, each reserved by Guard.ChallengeHandler or Guard.ConfirmHandler before the credential is verified, one user gets within a GuardBuilder.ChallengeTTL window, across all methods and sessions, before a pending login is discarded and the user is locked out of the second factor and of step-up. The first lockout lasts the window. Every wrong second-factor code also counts against a 24 hour budget per user that lasts across windows (a wrong step-up code counts only when it uses up the window's attempts, so occasional typos never add up): each time it grows by MaxAttempts, or a window's attempts are used up, a lockout starts that is twice as long as the previous one (window x 2^n, capped at 24 hours, or at the window when that is longer). So staying just under the limit in every window does not avoid the lockout. The budget expires 24 hours after its first failure (not after the last), and a successful challenge or Guard.Unlock clears it. Lockouts chain: anyone who knows the password can keep a user locked out of the second factor and of step-up for up to 24 hours at a time, so treat a lockout as a sign that the password is compromised and reset it. SecondFactorLocked reports each lockout (see GuardBuilder.Events). A check that fails with an infrastructure error is refunded. The default is five. NewGuard rejects a value of zero or less. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.MaxAttempts(3)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP).MaxAttempts(2)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

handler := guard.ChallengeHandler()
wrong := func() error {
	body := strings.NewReader(`{"method":"otp","code":"bad"}`)

	return handler(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/", body).WithContext(r.Context()))
}

fmt.Println(errors.Is(wrong(), auth.ErrInvalidCredential))
fmt.Println(errors.Is(wrong(), auth.ErrInvalidCredential))
fmt.Println(errors.Is(wrong(), auth.ErrUnauthenticated))
Output:
true
true
true

func (*GuardBuilder) MaxLogins added in v0.7.0

func (policy *GuardBuilder) MaxLogins(limit int) *GuardBuilder

MaxLogins sets how many login records one user keeps. The default is 50. A new login beyond it drops the oldest record, which logs that device out. NewGuard rejects a value of zero or less. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.MaxLogins(10)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.MaxLogins(1)
})
first, second := exampleRequest(), exampleRequest()
_, _ = guard.Begin(first, "1", examplePassword)
_, _ = guard.Begin(second, "1", examplePassword)

_, err := guard.Authenticator()(first)

fmt.Println(errors.Is(err, auth.ErrNoCredentials))
Output:
true

func (*GuardBuilder) SecondFactor added in v0.7.0

func (policy *GuardBuilder) SecondFactor(credentials ...Credential) *GuardBuilder

SecondFactor registers credentials that may finish a parked login. A user who is enrolled in any of them, and whose login did not already prove two kinds of factor, must present one of their enrolled methods before Guard.Begin logs them in; Guard.ChallengeHandler verifies it. Core never imports the module that owns the credential: it receives plain functions in a Credential. The call may be repeated; credentials keep registration order, which is the order of Outcome.Methods. NewGuard rejects a duplicate method within this registry, an empty method and a nil Credential.Enrolled. The same credential may also be registered with GuardBuilder.StepUp.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.SecondFactor(totp.Credential())
})
Example
enrolled := map[string]bool{"1": true}

guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(credential(auth.MethodOTP, auth.KindPossession, func(subject string) (bool, error) {
		return enrolled[subject], nil
	}))
})

outcome, err := guard.Begin(exampleRequest(), "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

fmt.Println(outcome.Complete(), err)
Output:
false <nil>

func (*GuardBuilder) SessionLifetime added in v0.7.0

func (policy *GuardBuilder) SessionLifetime(lifetime time.Duration) *GuardBuilder

SessionLifetime tells the guard the maximum session lifetime configured on session.Middleware with session.Builder.MaxLifetime, which the session package does not expose to other packages. A user's list of login records lives that long after its last write, and a record older than it is never listed and is removed by the next write, so no record outlives its sessions. The default is session.DefaultMaxLifetime; set it when the middleware uses another value. NewGuard rejects a value of zero or less. The setting replaces the previous value on this draft.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.SessionLifetime(7 * 24 * time.Hour)
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SessionLifetime(7 * 24 * time.Hour)
})

outcome, err := guard.Begin(exampleRequest(), "1", examplePassword)

fmt.Println(outcome.Complete(), err)
Output:
true <nil>

func (*GuardBuilder) StepUp added in v0.8.0

func (policy *GuardBuilder) StepUp(credentials ...Credential) *GuardBuilder

StepUp registers credentials that may re-prove a logged-in user: Guard.ConfirmHandler verifies one and records the factor on the session, and Guard.Fresh counts only these methods as fresh when the user has one enrolled. Register the methods a user can use to prove themselves again, such as the password and an authenticator, not a federated login. The call may be repeated; credentials keep registration order, which is the order of the methods in ErrStepUpRequired. NewGuard applies the same checks as for GuardBuilder.SecondFactor.

Example:

guard, err := auth.NewGuard(users, store, func(policy *auth.GuardBuilder) {
	policy.StepUp(passwords.Credential(), totp.Credential())
})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.StepUp(exampleOTP)
})

guard.MustAccept(auth.MethodOTP)

fmt.Println(guard != nil)
Output:
true

type GuardBuilderFunc added in v0.7.0

type GuardBuilderFunc = func(*GuardBuilder)

GuardBuilderFunc configures a GuardBuilder.

Example:

policy := auth.GuardBuilderFunc(func(policy *auth.GuardBuilder) {
	policy.MaxAttempts(3)
})
guard, err := auth.NewGuard(users, store, policy)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/service/cache"
	"arkoren.dev/core/service/cache/memorycache"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

// exampleGuard returns a login over exampleDriver; policy callbacks configure it.
func exampleGuard(configure ...auth.GuardBuilderFunc) *auth.Guard {
	users, err := auth.NewUserProvider(exampleDriver())

	if err != nil {
		panic(err)
	}

	guard, err := auth.NewGuard(users, cache.New(memorycache.New()), configure...)

	if err != nil {
		panic(err)
	}

	return guard
}

func main() {
	policy := auth.GuardBuilderFunc(func(policy *auth.GuardBuilder) {
		policy.MaxAttempts(3)
	})

	fmt.Println(exampleGuard(policy) != nil)
}
Output:
true

type Identity added in v0.3.0

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

Identity is who is acting: a subject, how it was authenticated and what it may do. It is an immutable value that carries no application user type, so any package can read it from a context with FromContext. Build one with NewIdentity. The zero Identity has an empty subject and no factors.

Getters return copies of slices and maps, so callers cannot change an identity after it is built.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
	principal.Scopes("posts:write")
})
fmt.Println(identity.Subject(), identity.Level() == auth.LevelSingle)
Example
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(password, otp).Scopes("posts:write")
})

fmt.Println(identity.Subject(), identity.Level() == auth.LevelMulti, identity.Scopes())
Output:
42 true [posts:write]

func FromContext added in v0.3.0

func FromContext(ctx context.Context) (Identity, bool)

FromContext returns the Identity stored in ctx. The boolean reports whether one was found. It needs no knowledge of the application's user type.

Example:

if identity, ok := auth.FromContext(r.Context()); ok {
	_ = identity.Subject()
}
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	_, ok := auth.FromContext(context.Background())

	fmt.Println(ok)
}
Output:
false

func NewIdentity added in v0.3.0

func NewIdentity(subject string, configure ...IdentityBuilderFunc) Identity

NewIdentity publishes an immutable Identity for subject. Callbacks run once in order on one fresh draft; nil entries panic. NewIdentity does not validate subject: authenticators that take it from untrusted input should check it with ValidateSubject first.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
})
ctx := auth.NewContext(ctx, identity)
Example
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(password)
})

fmt.Println(identity.Subject(), identity.Level() == auth.LevelSingle)
Output:
42 true

func (Identity) Actor added in v0.3.0

func (identity Identity) Actor() string

Actor returns the subject acting on behalf of the identity, or "" when the identity acts for itself.

Example:

fmt.Println(auth.NewIdentity("42").Actor() == "")
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Actor("support-7")
	})

	fmt.Println(identity.Actor())
}
Output:
support-7

func (Identity) Factors added in v0.3.0

func (identity Identity) Factors() []Factor

Factors returns a copy of the verified factors, in the order they were added.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
})
fmt.Println(len(identity.Factors()))
Example
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(password)
})

fmt.Println(identity.Factors()[0].Method)
Output:
pwd

func (Identity) Level added in v0.3.0

func (identity Identity) Level() Level

Level derives the authentication level from the factors. No factors is LevelNone. Factors of at least two distinct kinds among KindKnowledge, KindPossession and KindInherence are LevelMulti; two passwords are not. KindFederated and unknown kinds never count toward LevelMulti, so any other non-empty set of factors is LevelSingle.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(auth.Factor{Method: "federated", Kind: auth.KindFederated})
})
fmt.Println(identity.Level() == auth.LevelSingle)
Example
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(password, password)
})

fmt.Println(identity.Level() == auth.LevelSingle)
Output:
true

func (Identity) Record added in v0.3.0

func (identity Identity) Record() UserRecord

Record returns what the user provider knew about the user when the identity was built; the zero record if none was attached. The claims map is a copy.

Example:

record := auth.NewIdentity("42").Record()
fmt.Println(record.Value == nil)
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Record(auth.UserRecord{Subject: "42", Version: "v1"})
	})

	fmt.Println(identity.Record().Version)
}
Output:
v1

func (Identity) Scopes added in v0.3.0

func (identity Identity) Scopes() []string

Scopes returns a copy of the granted scopes.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Scopes("read")
})
fmt.Println(identity.Scopes())
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Scopes("read")
	})

	fmt.Println(identity.Scopes())
}
Output:
[read]

func (Identity) Session added in v0.8.0

func (identity Identity) Session() bool

Session reports whether the identity comes from a browser session, which only Guard.Authenticator can set. Credential routes of every module check it (see RequireSession and Guard.ConfirmHandler) because an identity carried by a bearer token must not enroll, change or confirm credentials. An identity built with NewIdentity is never a session.

Example:

identity := auth.NewIdentity("42")
fmt.Println(identity.Session()) // false
Example
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

identity, _ := guard.Authenticator()(r)

fmt.Println(identity.Session(), auth.NewIdentity("1").Session())
Output:
true false

func (Identity) Subject added in v0.3.0

func (identity Identity) Subject() string

Subject returns the stable subject of the user.

Example:

fmt.Println(auth.NewIdentity("42").Subject())
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.NewIdentity("42").Subject())
}
Output:
42

type IdentityBuilder added in v0.3.0

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

IdentityBuilder configures NewIdentity before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft, and retaining it cannot change a published identity.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Scopes("read").Actor("support-7")
})
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Scopes("read").Actor("support-7")
	})

	fmt.Println(identity.Scopes(), identity.Actor())
}
Output:
[read] support-7

func (*IdentityBuilder) Actor added in v0.3.0

func (principal *IdentityBuilder) Actor(actor string) *IdentityBuilder

Actor sets the subject acting on behalf of the identity, for example a support agent impersonating a user. The default, empty, means the identity acts for itself. The setting replaces the previous value on this draft.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Actor("support-7")
})
fmt.Println(identity.Actor())
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Actor("support-7")
	})

	fmt.Println(identity.Actor())
}
Output:
support-7

func (*IdentityBuilder) Factors added in v0.3.0

func (principal *IdentityBuilder) Factors(factors ...Factor) *IdentityBuilder

Factors appends verified factors. The slice is copied, so later edits by the caller do not change the identity.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(
		auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge},
		auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession},
	)
})
fmt.Println(identity.Level() == auth.LevelMulti)
Example
identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Factors(password, otp)
})

fmt.Println(identity.Level() == auth.LevelMulti)
Output:
true

func (*IdentityBuilder) Record added in v0.3.0

func (principal *IdentityBuilder) Record(record UserRecord) *IdentityBuilder

Record attaches what the user provider knows about the user, including the application's own user in UserRecord.Value, which UserFromContext and gate rules read. The claims map is copied. The setting replaces the previous value on this draft.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Record(auth.UserRecord{Subject: "42", Value: User{ID: 42}})
})
fmt.Println(identity.Record().Subject)
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Record(auth.UserRecord{Subject: "42", Value: "ann"})
	})

	fmt.Println(identity.Record().Value)
}
Output:
ann

func (*IdentityBuilder) Scopes added in v0.3.0

func (principal *IdentityBuilder) Scopes(scopes ...string) *IdentityBuilder

Scopes appends granted scopes. The slice is copied, so later edits by the caller do not change the identity. Scopes are opaque strings; use gate.HasScopes to require them.

Example:

identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
	principal.Scopes("posts:read", "posts:write")
})
fmt.Println(identity.Scopes())
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	identity := auth.NewIdentity("42", func(principal *auth.IdentityBuilder) {
		principal.Scopes("posts:read", "posts:write")
	})

	fmt.Println(identity.Scopes())
}
Output:
[posts:read posts:write]

type IdentityBuilderFunc added in v0.3.0

type IdentityBuilderFunc = func(*IdentityBuilder)

IdentityBuilderFunc configures an IdentityBuilder.

Example:

var policy auth.IdentityBuilderFunc = func(principal *auth.IdentityBuilder) {
	principal.Scopes("read")
}
identity := auth.NewIdentity("42", policy)
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	policy := auth.IdentityBuilderFunc(func(principal *auth.IdentityBuilder) {
		principal.Scopes("read")
	})

	fmt.Println(auth.NewIdentity("42", policy).Scopes())
}
Output:
[read]

type Kind added in v0.3.0

type Kind string

Kind classifies what a Factor proves, following the usual three authentication categories plus an externally asserted one. The values are our own strings.

Identity.Level counts distinct kinds: two different kinds among KindKnowledge, KindPossession and KindInherence make a multi-factor identity. KindFederated never counts toward that, because it only reports that another provider authenticated the user.

Example:

factor := auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.KindKnowledge, auth.KindPossession, auth.KindInherence, auth.KindFederated)
}
Output:
knowledge possession inherence federated
const (
	// KindKnowledge is something the user knows, such as a password.
	KindKnowledge Kind = "knowledge"

	// KindPossession is something the user has, such as a hardware key.
	KindPossession Kind = "possession"

	// KindInherence is something the user is, such as a fingerprint.
	KindInherence Kind = "inherence"

	// KindFederated marks an authentication performed by an external identity
	// provider. It never contributes to [LevelMulti], however many federated
	// factors an identity has, because Arkoren cannot see which factors the
	// provider required.
	KindFederated Kind = "federated"
)

type Level added in v0.3.0

type Level int

Level summarizes how strongly an Identity was authenticated. It is derived from the identity's factors by Identity.Level, never set directly.

Example:

identity := auth.NewIdentity("42")
if identity.Level() < auth.LevelSingle {
	return auth.ErrUnauthenticated
}
Example
fmt.Println(levelOf() == auth.LevelNone, levelOf(password) == auth.LevelSingle, levelOf(password, otp) == auth.LevelMulti)
Output:
true true true
const (
	// LevelNone means the identity has no factors.
	LevelNone Level = iota

	// LevelSingle means the identity has factors, but not two distinct
	// knowledge, possession or inherence kinds.
	LevelSingle

	// LevelMulti means the identity has factors of at least two distinct kinds
	// among [KindKnowledge], [KindPossession] and [KindInherence].
	LevelMulti
)

type LoggedOutEvent added in v0.6.0

type LoggedOutEvent struct {
	// Subject is the subject of the identity that logged out.
	Subject string
}

LoggedOutEvent reports that a logged-in user logged out. It carries only the subject, never the session ID, login record or other personal data.

Example:

unsubscribe, err := events.Listen(auth.LoggedOut, func(ctx context.Context, out auth.LoggedOutEvent) error {
	logger.InfoContext(ctx, "logged out", "subject", out.Subject)
	return nil
})
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.LoggedOutEvent{Subject: "1"}.Subject)
}
Output:
1

type LoginRecord added in v0.5.0

type LoginRecord struct {
	// ID identifies the login. It is random, stays the same when the session ID
	// rotates and is what [Guard.Revoke] takes.
	ID string `json:"id"`

	// CreatedAt is when the user logged in, in UTC.
	CreatedAt time.Time `json:"created_at"`

	// SeenAt is when the login last authenticated a request, in UTC. It is
	// refreshed at most once per five minutes and on a best-effort basis, so it
	// can lag by that much or more.
	SeenAt time.Time `json:"seen_at"`

	// UserAgent is the User-Agent request header at login, truncated to 255
	// bytes. It is empty when [GuardBuilder.Devices] is false.
	UserAgent string `json:"user_agent,omitzero"`

	// IP is the client address at login, from [GuardBuilder.ClientIP], cut to 255
	// bytes. It is empty when [GuardBuilder.Devices] is false.
	IP string `json:"ip,omitzero"`

	// Current is true for the record of the request's own login. Only
	// [Guard.Logins] sets it; it is never stored, so it appears in JSON only
	// when true.
	Current bool `json:"current,omitzero"`
}

LoginRecord is one login of one user on one device, as listed by Guard.Logins and Guard.LoginsOf. It holds personal data (user agent and address): show it to its owner and administrators only, and never put it in telemetry or events.

Example:

records, err := guard.Logins(r)
if err != nil {
	return err
}
for _, record := range records {
	fmt.Println(record.UserAgent, record.IP, record.SeenAt, record.Current)
}
Example
guard := exampleGuard()
r := exampleRequest()
r.Header.Set("User-Agent", "Firefox")
r.RemoteAddr = "203.0.113.7:4711"
_, _ = guard.Begin(r, "1", examplePassword)

records, _ := guard.Logins(r)

fmt.Println(records[0].UserAgent, records[0].IP, records[0].Current)
Output:
Firefox 203.0.113.7 true

type LogoutBuilder added in v0.6.0

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

LogoutBuilder configures Guard.LogoutHandler before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft, and retaining it cannot change a published handler.

Example:

r.Post("/logout", guard.LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Redirect("/").Events(events)
}))
Example
guard := exampleGuard()
handler := guard.LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Redirect("/").Events(event.New())
})
w := httptest.NewRecorder()

err := handler(w, exampleRequest())

fmt.Println(err, w.Code, w.Header().Get("Location"))
Output:
<nil> 303 /

func (*LogoutBuilder) Events added in v0.6.0

func (logout *LogoutBuilder) Events(events *event.Bus) *LogoutBuilder

Events sets the bus that receives LoggedOut. Nil, the default, publishes nothing. The bus is a shared service, not copied. This setting replaces the previous value on the construction draft.

Example:

r.Post("/logout", guard.LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Events(events)
}))
Example
bus := event.New()
_, _ = bus.Listen(auth.LoggedOut, func(_ context.Context, out auth.LoggedOutEvent) error {
	fmt.Println("logged out", out.Subject)

	return nil
})
guard := exampleGuard()
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

handler := auth.Middleware(guard.Authenticator())(guard.LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Events(bus)
}))
_ = handler(httptest.NewRecorder(), r)
Output:
logged out 1

func (*LogoutBuilder) Redirect added in v0.6.0

func (logout *LogoutBuilder) Redirect(target string) *LogoutBuilder

Redirect makes the handler answer 303 See Other with target as Location instead of 204 No Content, which suits a server-rendered application. The target must be a safe relative path (see response.ValidateRedirectTarget): Guard.LogoutHandler checks it once at construction, and an unsafe target makes the handler return response.ErrUnsafeRedirect on every request before any session change. The empty string, the default, answers 204. This setting replaces the previous value on the construction draft.

Example:

r.Post("/logout", guard.LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Redirect("/")
}))
Example
handler := exampleGuard().LogoutHandler(func(logout *auth.LogoutBuilder) {
	logout.Redirect("/goodbye")
})
w := httptest.NewRecorder()

err := handler(w, exampleRequest())

fmt.Println(err, w.Code, w.Header().Get("Location"))
Output:
<nil> 303 /goodbye

type LogoutBuilderFunc added in v0.6.0

type LogoutBuilderFunc = func(*LogoutBuilder)

LogoutBuilderFunc configures a LogoutBuilder.

Example:

var policy auth.LogoutBuilderFunc = func(logout *auth.LogoutBuilder) {
	logout.Redirect("/")
}
r.Post("/logout", guard.LogoutHandler(policy))
Example
policy := auth.LogoutBuilderFunc(func(logout *auth.LogoutBuilder) {
	logout.Redirect("/")
})
w := httptest.NewRecorder()

err := exampleGuard().LogoutHandler(policy)(w, exampleRequest())

fmt.Println(err, w.Code)
Output:
<nil> 303

type Method added in v0.3.0

type Method string

Method names how a Factor was verified. The constants of this package are Authentication Method Reference values of RFC 8176 ("pwd", "otp", "hwk", "swk"). Core defines no other names: a module that verifies something RFC 8176 does not cover, such as a recovery code or a federated login, declares its own Method constant. Before v0.8.0 core also defined MethodRecovery and MethodFederated. Applications may use further strings.

Example:

factor := auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.MethodPassword, auth.MethodOTP, auth.MethodHardwareKey, auth.MethodSoftwareKey)
}
Output:
pwd otp hwk swk
const (
	// MethodPassword is a password check ("pwd", RFC 8176).
	MethodPassword Method = "pwd"

	// MethodOTP is a one-time password such as TOTP ("otp", RFC 8176).
	MethodOTP Method = "otp"

	// MethodHardwareKey is proof of possession of a hardware-secured key
	// ("hwk", RFC 8176).
	MethodHardwareKey Method = "hwk"

	// MethodSoftwareKey is proof of possession of a software-stored key
	// ("swk", RFC 8176).
	MethodSoftwareKey Method = "swk"
)

type MiddlewareBuilder added in v0.3.0

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

MiddlewareBuilder configures Require before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic. Retaining the draft cannot change published settings. Methods return the same draft.

Example:

r := router.New()
r.Use(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
	authenticator.ErrorResponse(problem.Unauthorized("Bearer"))
}))
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/foundation/problem"
)

func main() {
	middleware := auth.Require(func(authenticator *auth.MiddlewareBuilder) {
		authenticator.ErrorResponse(problem.Unauthorized("Basic"))
	})

	fmt.Println(middleware != nil)
}
Output:
true

func (*MiddlewareBuilder) ErrorResponse added in v0.3.0

func (authenticator *MiddlewareBuilder) ErrorResponse(response problem.Details) *MiddlewareBuilder

ErrorResponse is the problem returned for anonymous requests. Zero uses ErrUnauthenticated with a "WWW-Authenticate: Bearer" challenge.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
	authenticator.ErrorResponse(problem.Forbidden())
}))
Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/http/router"
	"arkoren.dev/foundation/problem"
)

func main() {
	r := router.New()
	r.With(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
		authenticator.ErrorResponse(problem.Unauthorized("Basic"))
	})).Get("/", func(http.ResponseWriter, *http.Request) error { return nil })

	response := httptest.NewRecorder()
	r.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))

	fmt.Println(response.Header().Get("WWW-Authenticate"))
}
Output:
Basic

func (*MiddlewareBuilder) Events added in v0.3.0

func (authenticator *MiddlewareBuilder) Events(bus *event.Bus) *MiddlewareBuilder

Events receives Rejected when Require rejects a request. The default, nil, publishes nothing.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
	authenticator.Events(event.New())
}))
Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
	"arkoren.dev/core/http/router"
)

func main() {
	bus := event.New()
	_, _ = bus.Listen(auth.Rejected, func(_ context.Context, rejected auth.RejectedEvent) error {
		fmt.Println("rejected", rejected.Method)

		return nil
	})

	r := router.New()
	r.With(auth.Require(func(authenticator *auth.MiddlewareBuilder) {
		authenticator.Events(bus)
	})).Get("/", func(http.ResponseWriter, *http.Request) error { return nil })
	r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
}
Output:
rejected GET

type MiddlewareBuilderFunc added in v0.3.0

type MiddlewareBuilderFunc = func(*MiddlewareBuilder)

MiddlewareBuilderFunc edits one Require draft synchronously. Callbacks run directly once in order; nil entries panic and expanded nil/empty slices omit edits. The completed settings detach from the draft, not event services or captures.

Example:

var policy auth.MiddlewareBuilderFunc = func(authenticator *auth.MiddlewareBuilder) {
	authenticator.Events(events)
}
r.Use(auth.Require(policy))
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/foundation/problem"
)

func main() {
	policy := auth.MiddlewareBuilderFunc(func(authenticator *auth.MiddlewareBuilder) {
		authenticator.ErrorResponse(problem.Forbidden())
	})

	fmt.Println(auth.Require(policy) != nil)
}
Output:
true

type Outcome added in v0.8.0

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

Outcome is the result of Guard.Begin: either the user is logged in, or the login is parked until a second factor is verified. A login method returns it to the client with Outcome.Response, so every method answers a parked login the same way. The zero Outcome is not complete and has no methods.

Example:

outcome, err := guard.Begin(r, subject, auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
if err != nil {
	return err
}
return outcome.Response(w)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})

outcome, err := guard.Begin(exampleRequest(), "1", examplePassword)

fmt.Println(outcome.Complete(), outcome.Methods(), err)
Output:
false [otp] <nil>

func (Outcome) Challenge added in v0.8.0

func (outcome Outcome) Challenge() SecondFactorChallenge

Challenge returns the body that asks the client for a second factor. For a complete login its methods are empty; use Outcome.Response unless you render the challenge yourself.

Example:

body := outcome.Challenge()
fmt.Println(body.SecondFactor.Methods)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
outcome, _ := guard.Begin(exampleRequest(), "1", examplePassword)

fmt.Println(outcome.Challenge().SecondFactor.Methods)
Output:
[otp]

func (Outcome) Complete added in v0.8.0

func (outcome Outcome) Complete() bool

Complete reports whether the user is logged in. When false, the login is parked and the request stays anonymous until a second factor is verified.

Example:

if outcome.Complete() {
	// Redirect into the application.
}
Example
outcome, _ := exampleGuard().Begin(exampleRequest(), "1", examplePassword)

fmt.Println(outcome.Complete())
Output:
true

func (Outcome) Methods added in v0.8.0

func (outcome Outcome) Methods() []Method

Methods returns a copy of the user's enrolled second-factor methods, in registration order. It is empty when the login is complete.

Example:

fmt.Println(outcome.Methods()) // [otp]
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
outcome, _ := guard.Begin(exampleRequest(), "1", examplePassword)

fmt.Println(outcome.Methods())
Output:
[otp]

func (Outcome) Response added in v0.8.0

func (outcome Outcome) Response(w http.ResponseWriter) error

Response writes the standard answer of a login route: 204 No Content when the login is complete, otherwise 202 Accepted with the JSON of Outcome.Challenge. The session cookie travels with it through the session middleware. It returns the error of the response writer.

Example:

outcome, err := guard.Begin(r, subject, factor)
if err != nil {
	return err
}
return outcome.Response(w)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
outcome, _ := guard.Begin(exampleRequest(), "1", examplePassword)
recorder := httptest.NewRecorder()

err := outcome.Response(recorder)

fmt.Println(recorder.Code, strings.TrimSpace(recorder.Body.String()), err)
Output:
202 {"second_factor":{"methods":["otp"]}} <nil>

type PendingLogin added in v0.8.0

type PendingLogin struct {
	// Subject is the user waiting to finish the login. It is for server-side use
	// only: the pending request is anonymous, so never send it to the client.
	Subject string

	// Methods are the user's enrolled second-factor methods, in registration order,
	// read when Pending ran.
	Methods []Method
}

PendingLogin describes a login parked by Guard.Begin: who is waiting and which second-factor methods they can use.

Example:

pending, err := guard.Pending(r)
if err != nil {
	return err
}
fmt.Println(pending.Subject, pending.Methods)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(exampleOTP)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", examplePassword)

pending, err := guard.Pending(r)

fmt.Println(pending.Subject, pending.Methods, err)
Output:
1 [otp] <nil>

type RejectedEvent added in v0.3.0

type RejectedEvent struct {
	// Method is the client-controlled HTTP method, not a route or user identity.
	// Applications must not place secrets in custom method names.
	//
	// Example:
	//	logger.InfoContext(ctx, "authentication required", "method", rejected.Method)
	Method string
}

RejectedEvent reports anonymous rejection without request paths, which can contain identifiers or credentials. It carries no user, credential, header, query, or cause. Its event context still contains the request's context values.

Example:

unsubscribe, err := events.Listen(auth.Rejected, func(ctx context.Context, rejected auth.RejectedEvent) error {
	logger.InfoContext(ctx, "authentication required", "method", rejected.Method)
	return nil
})
if err != nil {
	return err
}
defer unsubscribe()
Example
package main

import (
	"fmt"
	"net/http"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.RejectedEvent{Method: http.MethodGet}.Method)
}
Output:
GET

type Resolver added in v0.8.0

type Resolver func(ctx context.Context, external External) (subject string, err error)

Resolver maps an External identity to the local subject of a user, creating or linking the user when the application's policy says so. It is the only code that decides which local account an outside assertion may log into, so it owns account-takeover decisions such as linking by email. It returns an error wrapping ErrUnauthenticated to refuse the login; any other error is an operational failure. The returned subject must satisfy ValidateSubject.

Example:

var resolve auth.Resolver = func(ctx context.Context, external auth.External) (string, error) {
	subject, err := links.Find(ctx, external.Issuer, external.Subject)
	if err != nil {
		return "", err
	}
	return subject, nil
}
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	var resolve auth.Resolver = func(_ context.Context, external auth.External) (string, error) {
		if !external.EmailVerified {
			return "", auth.ErrUnauthenticated
		}

		return "1", nil
	}

	subject, err := resolve(context.Background(), auth.External{Issuer: "https://accounts.example.com", Subject: "1089", EmailVerified: true})

	fmt.Println(subject, err)
}
Output:
1 <nil>

type SecondFactorChallenge added in v0.8.0

type SecondFactorChallenge struct {
	// SecondFactor holds what the client needs to continue the login.
	SecondFactor struct {
		// Methods lists the user's enrolled second-factor methods, in
		// registration order. It is never empty in a challenge from [Guard.Begin].
		Methods []Method `json:"methods"`
	} `json:"second_factor"`
}

SecondFactorChallenge is the body of the 202 response that tells a client its login needs a second factor, and which methods the user may choose from, in registration order. Outcome.Challenge returns it, and the client answers with a request to Guard.ChallengeHandler.

Example:

challenge := auth.SecondFactorChallenge{}
challenge.SecondFactor.Methods = []auth.Method{auth.MethodOTP}
body, err := json.Marshal(challenge) // {"second_factor":{"methods":["otp"]}}
Example
package main

import (
	"encoding/json/v2"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	var challenge auth.SecondFactorChallenge
	challenge.SecondFactor.Methods = []auth.Method{auth.MethodOTP, auth.MethodHardwareKey}

	body, _ := json.Marshal(challenge)

	fmt.Println(string(body))
}
Output:
{"second_factor":{"methods":["otp","hwk"]}}

type SecondFactorLockedEvent added in v0.9.0

type SecondFactorLockedEvent struct {
	// Subject is the user whose second factor and step-up are locked.
	Subject string

	// Until is when the lockout ends, in UTC. Until then every challenge or
	// confirmation of the subject fails without verifying anything, in any
	// session.
	Until time.Time
}

SecondFactorLockedEvent reports that a user used up their second-factor attempts and is locked out. It carries the subject and the end of the lockout, never a code, credential or request detail.

Example:

unsubscribe, err := events.Listen(auth.SecondFactorLocked, func(ctx context.Context, locked auth.SecondFactorLockedEvent) error {
	return notify(ctx, locked.Subject, locked.Until)
})

type TypedUserDriver

type TypedUserDriver[K comparable, U any] struct {
	// contains filtered or unexported fields
}

TypedUserDriver is a UserDriver that adapts an application's typed loader. It converts subjects to the identifier type K, loads the user U, and builds the UserRecord from it. Create it with NewUserDriver.

Example:

driver, err := auth.NewUserDriver(loadUser, func(user User) int64 { return user.ID })
subject, err := driver.Subject(User{ID: 42}) // "42"
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	driver := exampleDriver()

	record, err := driver.Find(context.Background(), "1")

	fmt.Println(record.Value.(exampleUser).Role, err)
}
Output:
admin <nil>

func NewUserDriver

func NewUserDriver[K comparable, U any](
	load func(context.Context, K) (U, error),
	id func(U) K,
	configure ...UserDriverBuilderFunc[U],
) (*TypedUserDriver[K, U], error)

NewUserDriver returns a TypedUserDriver that loads users with load and identifies them with id. K must be a string kind, an integer kind, or a type implementing both encoding.TextMarshaler and (through its pointer) encoding.TextUnmarshaler, such as UUID, xid and ULID types; any other K fails with an error wrapping ErrInvalidSubject so the mistake surfaces at setup. It also fails for a nil load or id. Construction callbacks configure UserDriverBuilder.

load reports a deleted user with ErrUserNotFound (or an error wrapping it); returning a nil pointer with a nil error counts as not found too. Other loader errors pass through unchanged.

Example:

driver, err := auth.NewUserDriver(
	func(ctx context.Context, id int64) (User, error) { return store.User(ctx, id) },
	func(user User) int64 { return user.ID },
	func(driver *auth.UserDriverBuilder[User]) {
		driver.Disabled(func(user User) bool { return user.Suspended })
	},
)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
	)

	if err != nil {
		panic(err)
	}

	record, _ := driver.Find(context.Background(), "9")

	fmt.Println(record.Subject)
}
Output:
9

func (*TypedUserDriver[K, U]) Find

func (driver *TypedUserDriver[K, U]) Find(ctx context.Context, subject string) (UserRecord, error)

Find implements UserDriver. It parses subject canonically (an error wrapping ErrInvalidSubject otherwise, never ErrUserNotFound), calls the loader, and returns ErrUserNotFound for a nil pointer with a nil error and ErrUserDisabled when the Disabled function reports the user. The record's Value is the loaded U.

Example:

record, err := driver.Find(ctx, "42")
if err != nil {
	return err
}
user := record.Value.(User)
Example
package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	_, err := exampleDriver().Find(context.Background(), "+1")

	fmt.Println(errors.Is(err, auth.ErrInvalidSubject))
}
Output:
true

func (*TypedUserDriver[K, U]) Subject

func (driver *TypedUserDriver[K, U]) Subject(user U) (string, error)

Subject returns the subject of user, derived from the identifier function. It returns an error wrapping ErrInvalidSubject when the identifier does not render to a valid subject, such as an empty string.

Example:

subject, err := driver.Subject(user)
if err != nil {
	return err
}
err = users.Forget(ctx, subject)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	subject, err := exampleDriver().Subject(exampleUser{ID: 42})

	fmt.Println(subject, err)
}
Output:
42 <nil>

type UserDriver

type UserDriver interface {
	// Find returns the record of subject.
	//
	// Example:
	//
	//	record, err := driver.Find(ctx, "42")
	Find(ctx context.Context, subject string) (UserRecord, error)
}

UserDriver finds users by subject. Implementations must return an error wrapping ErrInvalidSubject for a subject that fails ValidateSubject, ErrUserNotFound for a missing user and ErrUserDisabled for a disabled one, with the record's Subject set to the argument. They must be safe for concurrent use. The conformance suite is arkoren.dev/core/auth/authtest.

Example:

type directory struct{}

func (directory) Find(ctx context.Context, subject string) (auth.UserRecord, error) {
	return auth.UserRecord{}, auth.ErrUserNotFound
}
Example
package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/auth/memoryauth"
)

func main() {
	var driver auth.UserDriver = memoryauth.New()

	_, err := driver.Find(context.Background(), "1")

	fmt.Println(errors.Is(err, auth.ErrUserNotFound))
}
Output:
true

type UserDriverBuilder

type UserDriverBuilder[U any] struct {
	// contains filtered or unexported fields
}

UserDriverBuilder configures NewUserDriver before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft. A nil function leaves the corresponding setting off.

Example:

driver, err := auth.NewUserDriver(loadUser, userID, func(driver *auth.UserDriverBuilder[User]) {
	driver.Version(func(user User) string { return user.PasswordVersion })
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	driver, _ := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Version(func(user exampleUser) string { return "v1" }).
				Claims(func(user exampleUser) map[string]any { return map[string]any{"id": user.ID} }).
				Disabled(func(user exampleUser) bool { return false })
		},
	)

	record, _ := driver.Find(context.Background(), "5")

	fmt.Println(record.Version, record.Claims["id"])
}
Output:
v1 5

func (*UserDriverBuilder[U]) Claims

func (builder *UserDriverBuilder[U]) Claims(claims func(U) map[string]any) *UserDriverBuilder[U]

Claims sets the function that derives UserRecord.Claims from a user. It replaces the previous value on the construction draft.

Example:

driver.Claims(func(user User) map[string]any { return map[string]any{"role": user.Role} })
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	record, _ := exampleDriver().Find(context.Background(), "1")

	fmt.Println(record.Claims)
}
Output:
map[role:admin]

func (*UserDriverBuilder[U]) Disabled

func (builder *UserDriverBuilder[U]) Disabled(disabled func(U) bool) *UserDriverBuilder[U]

Disabled sets the function that reports a user that exists but may not act; TypedUserDriver.Find then returns ErrUserDisabled. It replaces the previous value on the construction draft.

Example:

driver.Disabled(func(user User) bool { return user.SuspendedAt != nil })
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	_, err := exampleDriver().Find(context.Background(), "2")

	fmt.Println(err)
}
Output:
auth: user disabled

func (*UserDriverBuilder[U]) Version

func (builder *UserDriverBuilder[U]) Version(version func(U) string) *UserDriverBuilder[U]

Version sets the function that derives UserRecord.Version from a user. It replaces the previous value on the construction draft.

Example:

driver.Version(func(user User) string { return user.PasswordVersion })
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	driver, _ := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Version(func(user exampleUser) string { return fmt.Sprint("v", user.ID) })
		},
	)

	record, _ := driver.Find(context.Background(), "3")

	fmt.Println(record.Version)
}
Output:
v3

type UserDriverBuilderFunc

type UserDriverBuilderFunc[U any] = func(*UserDriverBuilder[U])

UserDriverBuilderFunc configures a UserDriverBuilder.

Example:

var policy auth.UserDriverBuilderFunc[User] = func(driver *auth.UserDriverBuilder[User]) {
	driver.Version(func(user User) string { return user.PasswordVersion })
}
driver, err := auth.NewUserDriver(loadUser, userID, policy)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	policy := auth.UserDriverBuilderFunc[exampleUser](func(driver *auth.UserDriverBuilder[exampleUser]) {
		driver.Version(func(user exampleUser) string { return "v1" })
	})

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
		policy,
	)

	fmt.Println(driver != nil, err)
}
Output:
true <nil>

type UserForgottenEvent

type UserForgottenEvent struct {
	// Subject is the subject passed to [UserProvider.Forget].
	Subject string
}

UserForgottenEvent reports that every forget hook of a user completed. It carries only the subject, never personal data.

Example:

unsubscribe, err := events.Listen(auth.UserForgotten, func(ctx context.Context, forgotten auth.UserForgottenEvent) error {
	logger.InfoContext(ctx, "user forgotten", "subject", forgotten.Subject)
	return nil
})
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	forgotten := auth.UserForgottenEvent{Subject: "42"}

	fmt.Println(auth.UserForgotten.Name(), forgotten.Subject)
}
Output:
auth.user.forgotten 42

type UserProvider

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

UserProvider looks users up through a UserDriver and coordinates cleanup when a user is forgotten. It is safe for concurrent use.

Example:

users, err := auth.NewUserProvider(driver)
if err != nil {
	return err
}
record, err := users.Find(ctx, "42")

func NewUserProvider

func NewUserProvider(driver UserDriver, configure ...UserProviderBuilderFunc) (*UserProvider, error)

NewUserProvider returns a provider over driver. It returns an error when driver is nil. Construction callbacks configure UserProviderBuilder.

Example:

users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(app.Events())
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, err := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
		users.Events(event.New())
	})

	if err != nil {
		panic(err)
	}

	record, err := users.Find(context.Background(), "1")

	fmt.Println(record.Subject, record.Claims["role"], err)
}
Output:
1 admin <nil>

func (*UserProvider) Find

func (provider *UserProvider) Find(ctx context.Context, subject string) (UserRecord, error)

Find returns the record of subject from the driver. Errors are the driver's: see UserDriver for ErrInvalidSubject, ErrUserNotFound and ErrUserDisabled.

Example:

record, err := users.Find(ctx, subject)
if errors.Is(err, auth.ErrUserNotFound) {
	return nil // The user was deleted.
}
Example
package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, _ := auth.NewUserProvider(exampleDriver())

	_, err := users.Find(context.Background(), "2")
	fmt.Println(errors.Is(err, auth.ErrUserDisabled))

	_, err = users.Find(context.Background(), "3")
	fmt.Println(errors.Is(err, auth.ErrUserNotFound))
}
Output:
true
true

func (*UserProvider) Forget

func (provider *UserProvider) Forget(ctx context.Context, subject string) error

Forget removes the data of a user by running every hook registered with UserProvider.OnForget synchronously in ctx, in registration order, so the hooks join a transaction carried by ctx. The first hook error stops the run and is returned unchanged; hook panics propagate. It returns an error wrapping ErrInvalidSubject without running hooks for an invalid subject. After every hook succeeded it emits UserForgotten on the configured bus, and never after a failure. Forget does not look the user up.

Example:

err := db.WithTransaction(ctx, func(ctx context.Context) error {
	if err := removeAccount(ctx, id); err != nil {
		return err
	}
	return users.Forget(ctx, subject)
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	events := event.New()
	users, _ := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
		users.Events(events)
	})

	_, _ = events.Listen(auth.UserForgotten, func(_ context.Context, forgotten auth.UserForgottenEvent) error {
		fmt.Println("forgotten:", forgotten.Subject)

		return nil
	})

	fmt.Println(users.Forget(context.Background(), "1"))
}
Output:
forgotten: 1
<nil>

func (*UserProvider) OnForget

func (provider *UserProvider) OnForget(hook func(ctx context.Context, subject string) error)

OnForget registers hook to delete the data a package keeps about a user. Hooks run in registration order by UserProvider.Forget. Deletes should be idempotent, so there are no names and no duplicate check. It is safe to call concurrently with Forget; a Forget already running uses the hooks registered before it started. It panics when hook is nil.

Example:

users.OnForget(func(ctx context.Context, subject string) error {
	return subscriptions.DeleteBySubject(ctx, subject)
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, _ := auth.NewUserProvider(exampleDriver())

	users.OnForget(func(_ context.Context, subject string) error {
		fmt.Println("delete subscriptions of", subject)

		return nil
	})
	users.OnForget(func(_ context.Context, subject string) error {
		fmt.Println("delete sessions of", subject)

		return nil
	})

	_ = users.Forget(context.Background(), "1")
}
Output:
delete subscriptions of 1
delete sessions of 1

type UserProviderBuilder

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

UserProviderBuilder configures NewUserProvider before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft, and retaining it cannot change a published provider.

Example:

users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(app.Events())
})

func (*UserProviderBuilder) Events

func (builder *UserProviderBuilder) Events(events *event.Bus) *UserProviderBuilder

Events sets the bus that receives UserForgotten. Nil, the default, emits nothing. The bus is a shared service, not copied.

This setting replaces the previous value on the construction draft.

Example:

users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(event.New())
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	events := event.New()
	users, _ := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
		users.Events(events)
	})

	_, _ = events.Listen(auth.UserForgotten, func(context.Context, auth.UserForgottenEvent) error {
		fmt.Println("event received")

		return nil
	})

	_ = users.Forget(context.Background(), "1")
}
Output:
event received

type UserProviderBuilderFunc

type UserProviderBuilderFunc = func(*UserProviderBuilder)

UserProviderBuilderFunc configures a UserProviderBuilder.

Example:

var policy auth.UserProviderBuilderFunc = func(users *auth.UserProviderBuilder) {
	users.Events(events)
}
users, err := auth.NewUserProvider(driver, policy)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	policy := auth.UserProviderBuilderFunc(func(users *auth.UserProviderBuilder) {
		users.Events(event.New())
	})

	users, err := auth.NewUserProvider(exampleDriver(), policy)

	fmt.Println(users != nil, err)
}
Output:
true <nil>

type UserRecord

type UserRecord struct {
	// Subject is the user's subject as passed to Find.
	Subject string

	// Version is an opaque string that changes whenever the user changes in a
	// way that should invalidate what was derived from it, such as a password
	// version. Empty means the driver has no version.
	Version string

	// Claims are application-defined attributes of the user. Treat the map as
	// read only: drivers may share it.
	Claims map[string]any

	// Value is the driver's own user value, such as the application's user
	// struct. Its type is whatever the driver documents; nil if none.
	Value any
}

UserRecord is what a UserDriver knows about one user.

Example:

record, err := users.Find(ctx, "42")
if err != nil {
	return err
}
fmt.Println(record.Subject, record.Version, record.Claims["role"])
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	record, _ := exampleDriver().Find(context.Background(), "1")

	fmt.Println(record.Subject, record.Claims["role"], record.Value.(exampleUser).ID)
}
Output:
1 admin 1

Directories

Path Synopsis
Package authtest provides conformance suites for auth.UserDriver and auth.Authenticator implementations, modeled on testing/fstest.
Package authtest provides conformance suites for auth.UserDriver and auth.Authenticator implementations, modeled on testing/fstest.
Package gate authorizes the authenticated user with plain Go rules.
Package gate authorizes the authenticated user with plain Go rules.
Package memoryauth provides an in-memory auth.UserDriver for tests, local development and single-process applications.
Package memoryauth provides an in-memory auth.UserDriver for tests, local development and single-process applications.

Jump to

Keyboard shortcuts

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