auth

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 24 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. Every login method calls Begin with the subject and the factor it verified; Begin logs the user in, or parks a pending login when a registered SecondFactor check says a second factor is needed (finish with Pending, Fail and Complete). A session already logged in as that subject keeps its login instead: Begin adds the factor like Confirm and skips the second-factor checks (before v0.6.0 it replaced the factors). Confirm records a fresh factor on a logged-in session. 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 RequireFresh protect routes by the factors of the identity, so they also work for tokens. 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)
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()
		}

		return "ip:" + r.RemoteAddr
	})
}))

r.Post("/login", signIn)
r.Post("/logout", guard.LogoutHandler())

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 the verified Factor. Begin looks the user up with the provider (a deleted or disabled user is ErrUnauthenticated) and asks each check registered with GuardBuilder.SecondFactor, so core never imports the package that knows whether a user is enrolled. If none says yes the user is logged in and Begin returns true. Otherwise the login is parked as pending and the request stays anonymous: the handler asks for the second factor, reads the user with Guard.Pending, reports a wrong code with Guard.Fail (the pending login is discarded after GuardBuilder.MaxAttempts) and finishes with Guard.Complete, which is single use. GuardBuilder.ChallengeTTL bounds the wait. Guard.Confirm records a fresh factor on a logged-in session, such as a re-entered password. Every transition regenerates the session ID.

A session that is already logged in as the subject keeps its login: Begin then adds the factor like Confirm and skips the second-factor checks, 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 Complete) 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.

RequireLevel and RequireFresh protect routes by the factors of the identity in the context, so they also work for tokens that carry factors. Too weak or too old is ErrStepUpRequired (403); no identity is rejected like Require. A factor dated in the future is not fresh.

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}
	complete, err := guard.Begin(r, subject, factor)
	if err != nil {
		return err
	}
	if !complete {
		return response.Status(w, http.StatusAccepted) // ask for the second factor
	}

	return response.Status(w, http.StatusNoContent)
}

r.With(auth.RequireLevel(auth.LevelMulti)).Post("/payouts", payout)
r.With(auth.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 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 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 and RequireFresh when an authenticated request has not proved enough, or not recently enough. A client should ask the user for the missing factor and retry. It is 403, not 401, because the user is authenticated and a 401 invites login redirects that would discard the session.

Example:

if errors.Is(err, auth.ErrStepUpRequired) {
	// Ask the user to confirm, 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 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 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 RequireFresh added in v0.4.0

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

RequireFresh returns middleware that admits a request only when one of its identity's factors was verified within maxAge, so a long-lived session cannot delete an account without a recent password or second factor; Guard.Confirm records such a factor. A factor with an unknown (zero) or future time is not fresh. A maxAge of zero or less admits nothing. Anonymous requests and failures are those of RequireLevel.

Example:

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

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

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

func main() {
	handler := auth.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 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 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 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 the factor was verified. The zero time means unknown.
	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 a registered second-factor check says the user needs one, parks the login in a pending state in which the request stays anonymous until Guard.Complete. The factors recorded along the way give Identity.Level, and RequireLevel and 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, Complete, Fail, Confirm, 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). The methods, session keys, events and stored record formats did not change.

Example:

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

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

fmt.Println(complete, err, identity.Subject(), identity.Level() == auth.LevelSingle)
Output:
true <nil> 1 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 or GuardBuilder.SessionLifetime is not positive, or when a second-factor check or GuardBuilder.ClientIP is nil. 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(factors.Enrolled)
})
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.

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, factor Factor) (complete bool, err error)

Begin is the single entry for every login method. Call it after the method verified its credential, passing the verified factor; a zero factor.At means now. It first looks subject up with the provider: a deleted or disabled user is ErrUnauthenticated, and other provider errors, including ErrInvalidSubject, are returned unchanged.

When the session is already logged in as subject, Begin behaves like Guard.Confirm: it adds factor to the logged-in session (a factor of the same Method replaces the older one), keeps the login record, skips the second-factor checks, regenerates the session ID and returns true. 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. Before v0.6.0 Begin replaced the factors in this case, and parked the login when a second factor was enrolled. A different subject, an anonymous session and a pending login keep the behavior below.

Otherwise it asks each GuardBuilder.SecondFactor check. When none says yes it logs the user in with factor, regenerates the session ID and returns true. Otherwise it replaces any logged-in user with a pending login that expires after GuardBuilder.ChallengeTTL, regenerates the session ID and returns false: the request stays anonymous until Guard.Complete. The caller then asks for the second factor. A check error 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 login that is parked creates its record at Guard.Complete.

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

Example:

complete, err := guard.Begin(r, subject, auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
if err != nil {
	return err
}
if !complete {
	return response.Status(w, http.StatusAccepted) // Ask for the second factor.
}
Example
guard := exampleGuard()
r := exampleRequest()

complete, err := guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})
fmt.Println(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) Complete added in v0.7.0

func (guard *Guard) Complete(r *http.Request, factor Factor) error

Complete finishes a pending login after the second factor verified: it logs the user in with the factors verified at Guard.Begin plus factor (a zero factor.At means now), creates the LoginRecord of the device as Guard.Begin does, regenerates the session ID and consumes the pending login, so a second call returns ErrUnauthenticated. The errors are those of Guard.Pending plus the cache and lock errors of the record store; on any error nothing is logged in.

Complete does not verify the factor: call it only after it checked out.

Example:

if _, err := guard.Pending(r); err != nil {
	return err
}
if !verifyCode(code) {
	return guard.Fail(r)
}
return guard.Complete(r, auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession})
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(needsSecondFactor)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

err := guard.Complete(r, auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession})
identity, _ := guard.Authenticator()(r)

fmt.Println(err, identity.Level() == auth.LevelMulti)
Output:
<nil> true

func (*Guard) Confirm added in v0.7.0

func (guard *Guard) Confirm(r *http.Request, factor Factor) error

Confirm records a freshly verified factor on the logged-in session and regenerates the session ID. Use it to re-check a password before a sensitive change, which satisfies RequireFresh, or to add a second factor later so RequireLevel passes. A factor with the same Method as a recorded one replaces it, so each method appears once with its latest time; a zero factor.At means now. It returns ErrUnauthenticated when the session holds no logged-in user.

Confirm does not verify the factor: call it only after it checked out.

Example:

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

err := guard.Confirm(r, auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession})
identity, _ := guard.Authenticator()(r)

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

func (*Guard) Fail added in v0.7.0

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

Fail counts one wrong second-factor attempt on the pending login and regenerates the session ID. When the count reaches GuardBuilder.MaxAttempts the pending login is discarded and the next Guard.Pending returns ErrUnauthenticated. It returns ErrUnauthenticated when there is no pending login. The count lives in the session, so it limits one browser session only; rate-limit by user or address as well.

Example:

if !verifyCode(code) {
	if err := guard.Fail(r); err != nil {
		return err
	}
	return problem.Unauthorized()
}
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(needsSecondFactor)
	policy.MaxAttempts(1)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

fmt.Println(guard.Fail(r))

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

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 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) Pending added in v0.7.0

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

Pending returns the user waiting for a second factor, as parked by Guard.Begin. It returns ErrUnauthenticated when there is no pending login, it expired (which also clears it) or the user was deleted, disabled or had its UserRecord.Version changed, for example by a password change, in the meantime (which discards it). Other provider errors pass through. Pending does not consume the login, so a handler can read the user, check a code and report a wrong one with Guard.Fail.

Example:

user, err := guard.Pending(r)
if err != nil {
	return err
}
ok := verifyCode(user.Subject, code)
Example
guard := exampleGuard(func(policy *auth.GuardBuilder) {
	policy.SecondFactor(needsSecondFactor)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

user, err := guard.Pending(r)

fmt.Println(user.Subject, err)
Output:
1 <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 when the session holds no logged-in user or its own login was revoked (nothing is revoked then), 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

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(needsSecondFactor)
})

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

fmt.Println(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(needsSecondFactor).ChallengeTTL(10 * time.Minute)
})
r := exampleRequest()

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

fmt.Println(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) 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{})))

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

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

func (*GuardBuilder) MaxAttempts added in v0.7.0

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

MaxAttempts sets how many calls to Guard.Fail discard a pending login. 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(needsSecondFactor).MaxAttempts(2)
})
r := exampleRequest()
_, _ = guard.Begin(r, "1", auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge})

_ = guard.Fail(r)
_, err := guard.Pending(r)
fmt.Println(err)

_ = guard.Fail(r)
_, err = guard.Pending(r)
fmt.Println(errors.Is(err, auth.ErrUnauthenticated))
Output:
<nil>
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(check func(ctx context.Context, subject string) (bool, error)) *GuardBuilder

SecondFactor registers a check that reports whether subject must present a second factor before Guard.Begin logs them in, for example an "is two-factor enrolled" lookup of an ark. Core receives plain functions, so it never imports the package that owns the answer. It may be called several times: one yes from any check is enough to require a second factor, and the first error stops the login and is returned by Begin. A nil check makes NewGuard fail.

Example:

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

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

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

fmt.Println(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)
})

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

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

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
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

// password, otp, hardware and federated are factors reused by the level tests.
var (
	password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
	otp      = auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
)

func main() {
	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
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

// password, otp, hardware and federated are factors reused by the level tests.
var password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}

func main() {
	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
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

// password, otp, hardware and federated are factors reused by the level tests.
var password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}

func main() {
	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: auth.MethodFederated, Kind: auth.KindFederated})
})
fmt.Println(identity.Level() == auth.LevelSingle)
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

// password, otp, hardware and federated are factors reused by the level tests.
var password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}

func main() {
	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) 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
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

// password, otp, hardware and federated are factors reused by the level tests.
var (
	password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
	otp      = auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
)

func main() {
	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
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

// password, otp, hardware and federated are factors reused by the level tests.
var (
	password = auth.Factor{Method: auth.MethodPassword, Kind: auth.KindKnowledge}
	otp      = auth.Factor{Method: auth.MethodOTP, Kind: auth.KindPossession}
)

// levelOf builds an identity with factors and returns its level.
func levelOf(factors ...auth.Factor) auth.Level {
	return auth.NewIdentity("1", func(principal *auth.IdentityBuilder) {
		principal.Factors(factors...)
	}).Level()
}

func main() {
	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 values "pwd", "otp", "hwk" and "swk" are the Authentication Method Reference values of RFC 8176; MethodRecovery and MethodFederated are Arkoren's own values, which RFC 8176 does not define. 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, auth.MethodRecovery, auth.MethodFederated)
}
Output:
pwd otp hwk swk recovery federated
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"

	// MethodRecovery is a single-use recovery code. It is an Arkoren value, not
	// an RFC 8176 one.
	MethodRecovery Method = "recovery"

	// MethodFederated is authentication by an external identity provider. It is
	// an Arkoren value, not an RFC 8176 one.
	MethodFederated Method = "federated"
)

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