auth

package
v0.3.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: 16 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. Share one auth.NewSessionIdentity(loadUser) across authentication, login, and logout. Its identifier type must be a string, an integer, or a text type, because the identifier becomes the identity's subject. Check its Err during setup and handle login/logout 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.

Session authentication uses the temporary SessionIdentity bridge: it binds the identifier type K, the user loader and a session.Handle, stores the raw K in the session and builds an identity whose subject is K as text and whose record holds the loaded user. K must be a string, an integer or a text type (see below); SessionIdentity.Err reports anything else. Zero definitions and nil loaders are invalid configuration; callbacks still run once in order. A later zero handle restores default lookup. Loaders are not invoked during construction. Invalid definitions stop middleware fallback. Handles do not isolate cookies, storage or users. One physical session has one identity slot ("arkoren:auth:user"), so definitions with the same K can still mix realms, and compatible persisted JSON may decode across types.

Wiring

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

r := router.New()
identity := auth.NewSessionIdentity(loadUser)
if err := identity.Err(); err != nil {
	return err
}
r.Use(session.Middleware(store))
r.Use(csrf.Middleware())
r.Use(auth.Middleware(identity.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", login)
r.Post("/logout", logout)

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

Where loadUser resolves the stored identifier:

func loadUser(ctx context.Context, id int) (User, error) {
	user, err := db.Find[User](ctx, query.Table("users", func(statement *query.Builder) {
		statement.Where("id", id)
	}))
	if errors.Is(err, database.ErrNoRows) {
		return User{}, auth.ErrNoCredentials // deleted user: anonymous
	}
	return user, err
}

Login and logout

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 login(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
	}
	if err := identity.Login(request.MustSession(r), user.ID); err != nil {
		return err
	}

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

func logout(w http.ResponseWriter, r *http.Request) error {
	if err := identity.Logout(request.MustSession(r)); err != nil {
		return err
	} // or Destroy() to drop all data
	return response.Status(w, http.StatusNoContent)
}

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

Deleted users

Sessions outlive accounts. Return ErrNoCredentials from the load function when the user no longer exists; the request 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 driver/oauth/oauthauth package plugs into auth without auth importing it. See its package documentation for the setup; it is updated for the non-generic Authenticator in a later release.

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.

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 ErrInvalidSessionIdentity = errors.New("auth: invalid session identity")

ErrInvalidSessionIdentity reports a zero definition, a nil loader or an identifier type K that cannot be converted to a subject (see ErrInvalidSubject; the latter error is wrapped too). It is a configuration error, not a credential rejection, so middleware fails closed.

Example:

if err := identity.Err(); errors.Is(err, auth.ErrInvalidSessionIdentity) {
	return err
}
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 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 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(
	auth.NewSessionIdentity(loadUser).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 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

	// Kind is what the factor proves. [Identity.Level] is derived from it.
	Kind Kind

	// At is when the factor was verified. The zero time means unknown.
	At time.Time
}

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 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 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 SessionBuilder added in v0.3.0

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

SessionBuilder selects the request session for NewSessionIdentity. Methods return the same draft. Callbacks run once in order, even with a nil loader; nil callback entries panic. Publication copies the completed selection.

Example:

identity := auth.NewSessionIdentity(loadUser, func(authenticator *auth.SessionBuilder) {
	authenticator.Handle(applicationSession)
})
r.Use(auth.Middleware(identity.Authenticator()))
Example
package main

import (
	"context"
	"fmt"

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

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

func main() {
	handle := session.NewHandle()
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{}, nil
	}, func(binding *auth.SessionBuilder) {
		binding.Handle(handle)
	})

	fmt.Println(identity.Err())
}
Output:
<nil>

func (*SessionBuilder) Handle added in v0.3.0

func (authenticator *SessionBuilder) Handle(handle session.Handle) *SessionBuilder

Handle selects the request bridge shared with session middleware. Zero resets the default. It changes neither cookie nor storage policy.

Example:

identity := auth.NewSessionIdentity(loadUser, func(authenticator *auth.SessionBuilder) {
	authenticator.Handle(applicationSession)
})
_ = identity.Err()
Example
package main

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

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

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

// exampleSession returns a fresh session for the examples.
func exampleSession() *session.Session {
	return session.New(time.Now().Add(time.Hour), map[string]any{})
}

func main() {
	handle := session.NewHandle()
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{}, nil
	}, func(binding *auth.SessionBuilder) {
		binding.Handle(handle)
	})
	current := exampleSession()

	request := httptest.NewRequest(http.MethodGet, "/", nil)
	request = request.WithContext(session.NewContextFor(request.Context(), handle, current))
	found, err := identity.Session(request.Context())

	fmt.Println(found == current, err)
}
Output:
true <nil>

type SessionBuilderFunc added in v0.3.0

type SessionBuilderFunc = func(*SessionBuilder)

SessionBuilderFunc configures the session bridge captured by NewSessionIdentity. Policies run once in order on a shared draft, even for an invalid loader; a nil policy panics. This alias also accepts ordinary function values.

Example:

policy := auth.SessionBuilderFunc(func(authenticator *auth.SessionBuilder) {
	authenticator.Handle(applicationSession)
})
identity := auth.NewSessionIdentity(loadUser, policy)
if err := identity.Err(); err != nil {
	return err
}
r.Use(auth.Middleware(identity.Authenticator()))
Example
package main

import (
	"context"
	"fmt"

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

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

func main() {
	policy := auth.SessionBuilderFunc(func(binding *auth.SessionBuilder) {
		binding.Handle(session.NewHandle())
	})
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{}, nil
	}, policy)

	fmt.Println(identity.Err())
}
Output:
<nil>

type SessionIdentity added in v0.3.0

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

SessionIdentity binds the login identifier K, user loader U and session bridge in one immutable definition. It is a temporary bridge to the non-generic Identity: SessionIdentity.Authenticator builds an identity whose subject is K converted by the NewUserDriver rules and whose record holds the loaded U, so K must be a string, an integer or a text type. Zero is invalid. Copies share functions and their captures, not mutable construction drafts. All definitions use the existing arkoren:auth:user slot: a physical session supports one identity, and another definition using the same K can still mix realms. Compatible persisted JSON may decode across types; incompatible in-memory types fail closed.

Example:

identity := auth.NewSessionIdentity(loadUser)
r.Use(auth.Middleware(identity.Authenticator()))
Example
package main

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

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

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

// exampleSession returns a fresh session for the examples.
func exampleSession() *session.Session {
	return session.New(time.Now().Add(time.Hour), map[string]any{})
}

func main() {
	identity := auth.NewSessionIdentity(func(_ context.Context, id string) (user, error) {
		return user{Name: id}, nil
	})
	current := exampleSession()
	_ = identity.Login(current, "ann")

	request := httptest.NewRequest(http.MethodGet, "/", nil)
	request = request.WithContext(session.NewContext(request.Context(), current))
	resolved, err := identity.Authenticator()(request)

	fmt.Println(resolved.Subject(), err)
}
Output:
ann <nil>

func NewSessionIdentity added in v0.3.0

func NewSessionIdentity[K, U any](
	load func(ctx context.Context, id K) (U, error),
	configure ...SessionBuilderFunc,
) SessionIdentity[K, U]

NewSessionIdentity publishes an immutable identity definition without calling load. A nil loader is invalid, but construction callbacks still run once in order. Nil callback entries panic. Retained drafts cannot change the result; function captures remain caller-owned. Check Err during application setup.

Example:

identity := auth.NewSessionIdentity(loadUser)
if err := identity.Err(); err != nil {
	return err
}
r.Use(auth.Middleware(identity.Authenticator()))
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.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{Name: "ann"}, nil
	})

	fmt.Println(identity.Err())
}
Output:
<nil>

func (SessionIdentity[K, U]) Authenticator added in v0.3.0

func (identity SessionIdentity[K, U]) Authenticator() Authenticator

Authenticator loads U from the stored K and returns an Identity whose subject is K formatted as a subject and whose UserRecord carries the subject and U in Value, so UserFromContext returns U. The identity has no factors. Missing sessions, absent identifiers and incompatible stored types yield ErrNoCredentials. Loader errors pass through unchanged. A stored K that does not format as a valid subject, such as an empty string, fails closed with ErrInvalidSubject, never ErrNoCredentials. Invalid definitions instead return the configuration error before lookup, preventing middleware credential fallback.

Example:

r.Use(auth.Middleware(identity.Authenticator()))
Example
package main

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

	"arkoren.dev/core/auth"
)

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

func main() {
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{Name: "ann"}, nil
	})

	_, err := identity.Authenticator()(httptest.NewRequest(http.MethodGet, "/", nil))

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

func (SessionIdentity[K, U]) Err added in v0.3.0

func (identity SessionIdentity[K, U]) Err() error

Err validates the definition without looking up a session or invoking its loader. Zero and nil-loader definitions return ErrInvalidSessionIdentity, and so does an identifier type K that cannot be a subject, with the cause (ErrInvalidSubject) wrapped.

Example:

if err := identity.Err(); err != nil {
	return err
}
Example
package main

import (
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

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

func main() {
	var zero auth.SessionIdentity[int, user]

	fmt.Println(errors.Is(zero.Err(), auth.ErrInvalidSessionIdentity))
}
Output:
true

func (SessionIdentity[K, U]) Login added in v0.3.0

func (identity SessionIdentity[K, U]) Login(current *session.Session, id K) error

Login stores the user identifier in current and regenerates the session ID to prevent session fixation. Call it after verifying the credentials. A failed field write is returned before rotating the ID; callers must stop login. Invalid definitions fail before mutation; nil sessions return ErrNoSession. The explicit session is not checked against the definition's handle. Other data, creation time and expiry remain unchanged.

Example:

sess := request.MustSession(r)
if err := identity.Login(sess, user.ID); err != nil {
	return err
}
Example
package main

import (
	"context"
	"fmt"
	"time"

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

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

// exampleSession returns a fresh session for the examples.
func exampleSession() *session.Session {
	return session.New(time.Now().Add(time.Hour), map[string]any{})
}

func main() {
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{}, nil
	})
	current := exampleSession()
	before := current.ID()

	err := identity.Login(current, 7)

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

func (SessionIdentity[K, U]) Logout added in v0.3.0

func (identity SessionIdentity[K, U]) Logout(current *session.Session) error

Logout removes even a stale, wrongly typed identifier and rotates the session ID. Other data and lifetime remain unchanged; use current.Destroy for full removal. Invalid definitions fail before mutation, nil returns ErrNoSession, and deletion errors precede rotation. Explicit sessions are not handle-checked.

Example:

if err := identity.Logout(request.MustSession(r)); err != nil {
	return err
}
Example
package main

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

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

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

// exampleSession returns a fresh session for the examples.
func exampleSession() *session.Session {
	return session.New(time.Now().Add(time.Hour), map[string]any{})
}

func main() {
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{}, nil
	})
	current := exampleSession()
	_ = identity.Login(current, 7)

	err := identity.Logout(current)

	request := httptest.NewRequest(http.MethodGet, "/", nil)
	request = request.WithContext(session.NewContext(request.Context(), current))
	_, authErr := identity.Authenticator()(request)

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

func (SessionIdentity[K, U]) Session added in v0.3.0

func (identity SessionIdentity[K, U]) Session(ctx context.Context) (*session.Session, error)

Session resolves exactly the selected request bridge once. It returns ErrInvalidSessionIdentity before lookup for invalid definitions and session.ErrNoSession for absent or nil sessions. It does not load a user, inspect an identifier, mutate state or fall back to the default session.

Example:

current, err := identity.Session(r.Context())
if err != nil {
	return err
}
_ = current
Example
package main

import (
	"context"
	"errors"
	"fmt"

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

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

func main() {
	identity := auth.NewSessionIdentity(func(_ context.Context, id int) (user, error) {
		return user{}, nil
	})

	_, err := identity.Session(context.Background())

	fmt.Println(errors.Is(err, session.ErrNoSession))
}
Output:
true

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