egauth

package module
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 78 Imported by: 2 modules, 1 package

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

README

egauth

Go Reference CI

A misuse-resistant authentication library for Go: one validated composition object, one deny-by-default route builder, and CI guards that keep both honest.

About this project — please read. egauth was built mostly through "vibe coding" (AI-assisted development). egauth's security review to date is an AI-driven audit only; it has not had an independent third-party human security audit, and that risk is accepted for v1.0 — pin a reviewed commit, commission your own audit, or wait if that trade-off is unacceptable. I wrote it because I wanted a library like this for my own projects. "AI-audited" is not a synonym for "audited", so weigh the status accordingly before using it for anything sensitive. The full audit status, scope, and escape hatch live in AUDIT.md.

Comments, reviews, issues, and security audits are genuinely welcome. For anything security-sensitive see SECURITY.md.

The idea

Authentication bugs are usually configuration bugs: a cookie set up differently on two handlers, a gate added to one route and forgotten on its sibling, an option the constructor silently ignored. egauth removes those by construction:

  • One composition object. egauth.New takes a single egauth.Config and returns an egauth.Auth. It owns every policy object, store handle and background worker. No handler, cookie, issuer or limiter is ever wired by hand.
  • Validated at startup. Every field carries a tag that New enforces. All problems are returned together, as one error. There is no request-time "misconfigured" answer.
  • Deny by default. The only way to serve your own routes is Auth.Routes. A route is Protect, Optional, ProtectAPI or Public, and every other request is a 404. The gate set of each kind is fixed by the library.
  • Opt-outs in one place. Every weakening of a default lives in egauth.InsecureOptOuts, needs a written reason, and shows up in Auth.Posture.
  • Sealed session state. What a login proved (factors, assurance time, must-change, remember-me) is minted once, sealed, stored on every artefact and replayed. Later steps can add a factor, never re-derive or upgrade one.
  • Guarded in CI. Static guards (tools/archtest), behavioural journeys (internal/journeytest) and documentation guards (tools/doclint) fail the build when a contribution reopens one of these doors. See CONTRIBUTING.md.

Install

go get github.com/JLugagne/egauth
go get github.com/JLugagne/egauth/adapters/pgx

The second module holds the PostgreSQL stores and keeps the driver out of your dependency graph when you do not use it. Go 1.26 or newer.

Quick start

memstore keeps everything in memory, so this runs without a database. The example registers a password user, confirms the emailed link, logs in, calls a protected route, refreshes and logs out.

key := make([]byte, 32)
_, _ = rand.Read(key)
seed := make([]byte, 32)
_, _ = rand.Read(seed)
k, _ := kek.NewLocal(key)
signer, _ := signing.EdDSA("k1", seed)
mail := inbox{links: make(chan string, 1)}

auth, err := egauth.New(egauth.Config[struct{}]{
	PublicOrigin: "http://localhost:8080",
	Proxy:        egauth.DirectClients(),
	Storage:      memstore.New(k),
	KEK:          k,
	Sessions:     egauth.JWT(egauth.StaticKeys(signer)),
	Transport:    egauth.Bearer,
	Admin:        egauth.RoleAdmin("admin"),
	Email:        mail,
	Pages:        egauth.Pages{Login: "/login", AfterLogin: "/", ConfirmRegistration: "/confirm", PasswordReset: "/reset", SecurityRevert: "/revert"},
	Modules:      egauth.Modules{Password: &egauth.PasswordModule{}},
})
if err != nil {
	fmt.Println("new:", err)
	return
}
defer func() { _ = auth.Close() }()

h, err := auth.Routes().
	Protect("GET /me", func(w http.ResponseWriter, _ *http.Request, _ egauth.Principal[struct{}]) {
		_, _ = fmt.Fprintln(w, "hello")
	}).
	Build()
if err != nil {
	fmt.Println("routes:", err)
	return
}

call := func(method, path, token string, body map[string]any, hdr ...string) (*httptest.ResponseRecorder, map[string]any) {
	var payload strings.Reader
	if body != nil {
		raw, _ := json.Marshal(body)
		payload = *strings.NewReader(string(raw))
	}
	req := httptest.NewRequest(method, "http://localhost:8080"+path, &payload)
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	req.Header.Set("Origin", "http://localhost:8080")
	req.Header.Set(egauth.HeaderTransport, "bearer")
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	for i := 0; i+1 < len(hdr); i += 2 {
		req.Header.Set(hdr[i], hdr[i+1])
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	var out map[string]any
	_ = json.Unmarshal(rec.Body.Bytes(), &out)
	return rec, out
}

const email, password = "ada@example.com", "tapir-granite-velvet-orbit-29"
rec, begin := call("POST", "/auth"+egauth.PathRegister, "", map[string]any{egauth.FieldIdentifier: email, egauth.FieldPassword: password})
fmt.Println("register:", rec.Code)

link, _ := url.Parse(<-mail.links)
bind, _ := begin[egauth.FieldBind].(string)
rec, _ = call("POST", "/auth"+egauth.PathRegisterConfirm, "", map[string]any{egauth.FieldToken: link.Query().Get(egauth.FieldToken), egauth.FieldBind: bind})
fmt.Println("confirm:", rec.Code)

rec, _ = call("POST", "/auth"+egauth.PathLogin, "", map[string]any{egauth.FieldIdentifier: email, egauth.FieldPassword: password})
access, refresh := rec.Header().Get("X-Egauth-Access-Token"), rec.Header().Get("X-Egauth-Refresh-Token")
fmt.Println("login:", rec.Code)

rec, _ = call("GET", "/me", access, nil)
fmt.Println("me:", rec.Code)

rec, _ = call("POST", "/auth"+egauth.PathRefresh, "", nil, "X-Egauth-Refresh-Token", refresh)
access, refresh = rec.Header().Get("X-Egauth-Access-Token"), rec.Header().Get("X-Egauth-Refresh-Token")
fmt.Println("refresh:", rec.Code)

rec, _ = call("POST", "/auth"+egauth.PathLogout, access, nil)
fmt.Println("logout:", rec.Code)

rec, _ = call("POST", "/auth"+egauth.PathRefresh, "", nil, "X-Egauth-Refresh-Token", refresh)
fmt.Println("refresh after logout:", rec.Code)
// Output:
// register: 202
// confirm: 200
// login: 200
// me: 200
// refresh: 200
// logout: 200
// refresh after logout: 401

Declaring routes

Routes mounts the auth endpoints under the base path and serves exactly what you declare.

var auth *egauth.Auth[struct{}]
var page, report, adminDisable egauth.PrincipalHandler[struct{}]
var health http.Handler

h, err := auth.Routes().
	Optional("GET /", page).
	Protect("POST /admin/disable/{id}", adminDisable,
		egauth.RequireAnyRole("admin"), egauth.RequireMFA(), egauth.RequireFreshAuth(egauth.Fresh5m)).
	ProtectAPI("GET /api/report", report, egauth.Kinds("automation"), egauth.RequireAnyScope("report:read")).
	Public("GET /healthz", health).
	Build()
if err != nil {
	return
}
_ = http.ListenAndServe("localhost:8080", h)
Declaration Who is served
Protect an established human session that passes every session gate
Optional everyone; a caller failing any Protect gate is presented as anonymous
ProtectAPI an API key of a declared kind; sessions are refused
Public everyone, without authentication

Session-only requirements (egauth.RequireMFA, egauth.RequireFreshAuth) do not compile on a ProtectAPI route.

Production storage

pgxstore.New fills every egauth.Storage field from one pool. pgxstore.Migrate is expand-only and idempotent.

ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
	log.Fatal(err)
}
defer pool.Close()

if err := pgxstore.Migrate(ctx, pool); err != nil {
	log.Fatal(err)
}
storage, err := pgxstore.New(ctx, pool)
if err != nil {
	log.Fatal(err)
}

auth, err := egauth.New(egauth.Config[struct{}]{
	PublicOrigin: "https://auth.example.com",
	Proxy:        egauth.DirectClients(),
	Storage:      storage,
	KEK:          kekFromEnv("EGAUTH_KEK"),
	Sessions:     egauth.JWT(egauth.StaticKeys(signerFromEnv("EGAUTH_SIGNING_SEED"))),
	Admin:        egauth.RoleAdmin("admin"),
	Email:        mailer{},
	Pages:        egauth.Pages{Login: "/login", AfterLogin: "/", ConfirmRegistration: "/confirm", PasswordReset: "/reset", SecurityRevert: "/revert"},
	Modules:      egauth.Modules{Password: &egauth.PasswordModule{}},
})
if err != nil {
	log.Fatal(err)
}
defer func() { _ = auth.Close() }()

What you get

Module (field of egauth.Modules) Capability
Password register by verified email, login, reset, change; Argon2id with a policy and breach-check seam
MagicLink, LoginCode emailed link or emailed and texted codes as primary factors
Passkey WebAuthn with discoverable credentials and user verification required
OAuth, External OIDC and OAuth2 providers (12 built in), or an external primary factor
MFA TOTP and recovery codes; enrollment is read from stored state, never from configuration
Verification email, phone and recovery-email verification
SelfDelete, APIKeys account self-deletion and kind-scoped API keys

Sessions run on egauth.JWT (short-lived access tokens, rotating refresh tokens) or egauth.Stateful (server-side sessions). Both pass the same backend suite. Cookies, Bearer tokens or both are selected with egauth.Config.Transport. Tenancy is single-tenant, by subdomain, or resolved from the request.

Resource servers that only verify tokens use egauth.NewResourceServer.

Upgrading from v0.16

v0.17 is a breaking redesign and a session cutover: every user logs in again and outstanding emailed links stop working. Credentials carry over. The steps are in CHANGELOG.md under "Upgrading", and the secret upgrade is shown here:

ctx := context.Background()
var storage egauth.Storage
var oldKey, newKey []byte

legacy, err := kek.LegacyLocalV016(oldKey)
if err != nil {
	return
}
current, err := kek.NewLocal(newKey)
if err != nil {
	return
}
report, err := egauth.UpgradeSecretsV016(ctx, storage, legacy, current)
if err != nil {
	return
}
fmt.Println(report)

Reference application

examples/fullstack composes password, magic link, passkey, TOTP, self-delete and API keys with New and Routes, on in-memory storage:

go run github.com/JLugagne/egauth/examples/fullstack@latest

Documentation

Document Purpose
llms.txt and .llms/ compact, machine-readable reference
SECURITY.md secret handling, guarantees and consumer responsibilities
docs/ developer manual sources
CONTRIBUTING.md the invariants and the guard that enforces each
CHANGELOG.md, RELEASING.md releases

Stability

Pre-1.0: the API may change between minor versions until it settles. Pin a tag in go.mod for reproducible builds. The packages proposed for the v1 freeze are analysed in ADR 0001.

Before v1, egauth targets the newest major Go release as its minimum toolchain, and the go directive moves up each time a new major release ships. From v1 it is pinned for the life of the major version.

Documentation

Overview

Package egauth is a misuse-resistant authentication library for Go. A deployment is one validated composition object, built by New from one Config, and the application's own routes are declared through Auth.Routes, a deny-by-default builder. No handler, cookie, issuer, limiter or gate is wired by hand, so no two of them can disagree.

Composition

New checks the whole configuration at once and returns every problem joined: required fields, bounds, module dependencies, origins, store durability, the key-encryption key against existing data, the limiter, and any v0.16 secret that has not been upgraded. It never answers "misconfigured" at request time. The returned Auth owns every policy object, store handle and background worker until Close.

Config.Modules enables features: Password, MagicLink, LoginCode, Passkey, OAuth, External, MFA, Verification, SelfDelete and APIKeys. A nil module is off, and at least one primary module is required. Config.Storage comes from memstore.New for tests and development, or from pgxstore.New in the adapters/pgx module for production.

Routes

Auth.Routes returns a builder. Protect serves an established human session, Optional serves everyone and presents a caller that fails a Protect gate as anonymous, ProtectAPI serves API keys of declared kinds, and Public serves everyone. Build returns the handler to serve at the server root: it mounts the auth endpoints under Config.BasePath and answers 404 to every request that is not declared. Handlers receive a Principal as an argument; it is never read from context.

Sessions

What a login proved is minted once, sealed, stored on every artefact and replayed: later steps can add a factor, never re-derive one. Multi-factor enrollment is read from stored state, so configuration cannot lower the floor. Revocation is derived from a per-subject security epoch, which the stores bump atomically with every security mutation.

Opting out

Every weakening of a default lives in InsecureOptOuts, needs a written reason, and is listed by Auth.Posture. Nothing else loosens a gate.

Packages

memstore    in-memory Storage for tests and single-instance development
kek         key-encryption keys that seal secrets at rest, with mandatory associated data
signing     JWT signers and verifiers, and JWKS encoding
principal   the Subject, Caller, TenantID and Factor values shared with applications
event       the security-event Sink seam (slog and OpenTelemetry adapters)
passwords   password hashing, policy and breach-check seams, with Argon2id references
federation  identity-provider specs, with 12 built-in providers in federation/providers
store       store contracts, each with memory and pgx implementations and a contract suite
egauthtest  test doubles: clock, mailbox, identity provider, principals
webauthntest a software WebAuthn authenticator for passkey tests

Security and stability

The threat model, the secret-handling model and the consumer responsibilities are in SECURITY.md; the quick start is in README.md. The API is pre-1.0 and still settling; pin a tag in go.mod for reproducible builds.

Audit status: egauth's security review to date is an AI-driven audit only; it has not had an independent third-party human security audit, and that risk is accepted for v1.0 — pin a reviewed commit, commission your own audit, or wait if that trade-off is unacceptable. "AI-audited" is not a synonym for "audited". See AUDIT.md for the full review scope and the cautious-user escape hatch.

Index

Examples

Constants

View Source
const (
	RememberUserChoice = core.RememberUserChoice
	RememberAlways     = core.RememberAlways
	RememberNever      = core.RememberNever
)

Remember-me policies.

View Source
const (
	PathSession                    = routes.Session
	PathLogout                     = routes.Logout
	PathLogoutEverywhere           = routes.LogoutEverywhere
	PathReauth                     = routes.Reauth
	PathRefresh                    = routes.Refresh
	PathExchange                   = routes.Exchange
	PathResourceToken              = routes.ResourceToken
	PathSecurityRevert             = routes.SecurityRevert
	PathJWKS                       = routes.JWKS
	PathRegister                   = routes.Register
	PathRegisterConfirm            = routes.RegisterConfirm
	PathLogin                      = routes.Login
	PathPasswordForgot             = routes.PasswordForgot
	PathPasswordReset              = routes.PasswordReset
	PathPasswordChange             = routes.PasswordChange
	PathMagicLinkRequest           = routes.MagicLinkRequest
	PathMagicLink                  = routes.MagicLink
	PathCodeRequest                = routes.CodeRequest
	PathCodeVerify                 = routes.CodeVerify
	PathPasskeyLoginBegin          = routes.PasskeyLoginBegin
	PathPasskeyLoginFinish         = routes.PasskeyLoginFinish
	PathPasskeyRegisterBegin       = routes.PasskeyRegisterBegin
	PathPasskeyRegisterFinish      = routes.PasskeyRegisterFinish
	PathPasskeyCredentials         = routes.PasskeyCredentials
	PathPasskeyCredentialsRename   = routes.PasskeyCredentialsRename
	PathPasskeyCredentialsDelete   = routes.PasskeyCredentialsDelete
	PathOAuthBegin                 = routes.OAuthBegin
	PathOAuthCallback              = routes.OAuthCallback
	PathOAuthLink                  = routes.OAuthLink
	PathExternalLogin              = routes.ExternalLogin
	PathMFAChallenge               = routes.MFAChallenge
	PathMFAPasskeyBegin            = routes.MFAPasskeyBegin
	PathMFAPasskeyFinish           = routes.MFAPasskeyFinish
	PathMFATOTPEnroll              = routes.MFATOTPEnroll
	PathMFATOTPConfirm             = routes.MFATOTPConfirm
	PathMFATOTPDisable             = routes.MFATOTPDisable
	PathMFARecoveryCodesRegenerate = routes.MFARecoveryCodesRegenerate
	PathEmailVerifyRequest         = routes.EmailVerifyRequest
	PathEmailVerify                = routes.EmailVerify
	PathEmailChange                = routes.EmailChange
	PathEmailChangeConfirm         = routes.EmailChangeConfirm
	PathPhoneVerifyRequest         = routes.PhoneVerifyRequest
	PathPhoneVerify                = routes.PhoneVerify
	PathRecoveryEmail              = routes.RecoveryEmail
	PathRecoveryEmailConfirm       = routes.RecoveryEmailConfirm
	PathAccountDelete              = routes.AccountDelete
)

Endpoint paths, relative to the configured base path. Parameterised segments use {name}.

View Source
const (
	FieldIdentifier   = routes.FieldIdentifier
	FieldPassword     = routes.FieldPassword
	FieldNewPassword  = routes.FieldNewPassword
	FieldRemember     = routes.FieldRemember
	FieldReturnTo     = routes.FieldReturnTo
	FieldCode         = routes.FieldCode
	FieldFactor       = routes.FieldFactor
	FieldEmail        = routes.FieldEmail
	FieldPhone        = routes.FieldPhone
	FieldToken        = routes.FieldToken
	FieldFlow         = routes.FieldFlow
	FieldHandle       = routes.FieldHandle
	FieldBind         = routes.FieldBind
	FieldCredentialID = routes.FieldCredentialID
	FieldNickname     = routes.FieldNickname
	FieldConfirm      = routes.FieldConfirm
	FieldCaptchaToken = routes.FieldCaptchaToken
	FieldResource     = routes.FieldResource
)

Request field names accepted by the endpoints; any other form or JSON field is ignored.

View Source
const (
	Fresh5m  = routes.Fresh5m
	Fresh15m = routes.Fresh15m
	Fresh1h  = routes.Fresh1h
)

Freshness bounds.

View Source
const DefaultAPIKeyLifetime = 90 * 24 * time.Hour

DefaultAPIKeyLifetime is what keys.DefaultExpiry() resolves to for APIKeyRequest.Lifetime.

View Source
const HeaderTransport = routes.HeaderTransport

HeaderTransport selects Bearer transport on a login request, when the configuration allows it.

View Source
const MaxAppClaimsBytes = 2048

MaxAppClaimsBytes caps the JSON encoding of AppClaims, in bytes.

View Source
const PathWellKnown = routes.WellKnown

PathWellKnown is the discovery document path, served at the host root outside the base path.

View Source
const StartupTimeout = 30 * time.Second

StartupTimeout bounds every blocking call New makes.

Variables

View Source
var (
	// ErrClosed is returned by Ready after Close.
	ErrClosed = errors.New("egauth: closed")
	// ErrForbidden is returned by a facade when the caller may not act on the target.
	ErrForbidden = errors.New("egauth: forbidden")
	// ErrReauthRequired is returned by a facade when the caller's session is not fresh within
	// SessionPolicy.ReauthWindow or lacks the second factor its subject enrolled.
	ErrReauthRequired = errors.New("egauth: reauthentication required")
	// ErrAPIKeyCaller is returned by every facade method for an API-key caller.
	ErrAPIKeyCaller = errors.New("egauth: API-key callers cannot use this method")
	// ErrResourceTokenCaller is returned by every facade method for the Caller of a ResourceServer
	// route: a resource token is a short-lived, audience-bound delegation, never a first-party
	// session, so it cannot administer accounts, keys or tenants.
	ErrResourceTokenCaller = errors.New("egauth: resource-token callers cannot use this method")
	// ErrSessionEnded is returned by every facade method for a session Caller whose session is no
	// longer live: logged out, revoked, reissued or past its absolute lifetime. Callers are taken
	// per request; take a new one from the next request's Principal.
	ErrSessionEnded = errors.New("egauth: the caller's session has ended")
	// ErrSystemCallerInRequest is returned by every facade method for a System caller used while
	// serving a request.
	ErrSystemCallerInRequest = errors.New("egauth: system caller used inside a request")
	// ErrTenantMismatch is returned when a session caller targets another tenant.
	ErrTenantMismatch = errors.New("egauth: tenant mismatch")
	// ErrClaimsNotSubset is returned by APIKeys.Create when the requested roles, scopes or groups
	// exceed the caller's current claims.
	ErrClaimsNotSubset = errors.New("egauth: requested claims exceed the caller's")
)
View Source
var (
	// ErrInvalidRequest is returned, joined with the reason, by a facade method given an incomplete
	// or out-of-bounds request: a nil user id, a malformed email, an unknown API-key kind, a zero
	// keys.Expiry. Nothing was changed.
	ErrInvalidRequest = errors.New("egauth: invalid facade request")
	// ErrFacadeUnavailable is returned by a facade method that needs a module, backend or store the
	// deployment leaves off: API keys without Modules.APIKeys, temporary passwords without
	// Modules.Password, key provisioning without TenantKeys, runtime providers without
	// OAuthModule.PerTenant.
	ErrFacadeUnavailable = errors.New("egauth: the deployment does not enable what this facade method needs")
	// ErrStorageUnavailable replaces a store, KEK or session-backend failure in the methods whose
	// errors are documented as safe to show the caller (Tenants.SetOAuthProvider): the cause, which
	// can name database users, hosts and addresses, goes to the event sink only. Retry later.
	ErrStorageUnavailable = errors.New("egauth: storage unavailable, retry later")
	// ErrProviderLinked is returned, joined with ErrInvalidRequest, by Tenants.SetOAuthProvider for a
	// spec whose Issuer, JWKSURL, TokenURL or UserInfoURL differ from those the provider name's
	// linked identities were made under: those links would stop resolving, and must not resolve to
	// another provider. Register the new provider under a new name and let users link it.
	ErrProviderLinked = errors.New("egauth: the provider name has identities linked under another configuration")
	// ErrTenantNotServed is returned by System for a tenant the deployment's Tenancy can never serve:
	// a non-zero tenant under SingleTenant, the zero tenant under multi-tenancy, or a tenant that
	// cannot form a host label under TenantBySubdomain.
	ErrTenantNotServed = errors.New("egauth: the deployment cannot serve this tenant")
)
View Source
var ErrIdentifiersHeld = errors.New("egauth: v0.16 identifiers remain that v0.17 cannot represent or that collide")

ErrIdentifiersHeld is returned by UpgradeIdentifiersV016, with the report, when a v0.16 identifier could not be made canonical. It does not stop New: a held account stays readable by subject and accepts only protective changes (disable, forced password change, security revert, temporary password, removing a factor, a link, the phone or the recovery email, deletion). Email, phone and password changes and factor additions answer 409 identifier_repair_required, and no login finds it by the held identifier, until an operator repairs the stored value and runs the upgrade again.

View Source
var ErrUnknownSubject = errors.New("egauth: claims source does not know the subject")

ErrUnknownSubject returned by a ClaimsSource ends the subject's session at the next renewal instead of keeping stale claims.

View Source
var ErrUpgradeIncomplete = errors.New("egauth: v0.16 secrets remain that no legacy associated data opens")

ErrUpgradeIncomplete is returned by UpgradeSecretsV016, with the report, when a v0.16 row opens under no candidate associated data and so stays in place. New refuses to start until the row is repaired or deleted.

Functions

func TestHookResolve added in v0.17.0

func TestHookResolve[C any](cfg Config[C]) (*configcheck.Resolved, []*configcheck.Error)

TestHookResolve applies the defaults registry to a copy of cfg and returns the resolved view with every validation error. Called from outside package egauthtest it returns no view and a single error.

Types

type APIKeyInfo added in v0.17.0

type APIKeyInfo struct {
	ID        uuid.UUID
	Kind      string
	Name      string
	Owner     principal.Subject
	Roles     []string
	Scopes    []string
	Groups    []string
	CreatedAt time.Time
	ExpiresAt time.Time
}

APIKeyInfo describes an API key without its secret. Roles, Scopes and Groups are the claims the key was granted, a subset of its owner's; ExpiresAt is zero for a key that never expires.

type APIKeyModule added in v0.17.0

type APIKeyModule struct {
	Kinds  []string `egauth:"required,nonempty,each=token"`
	Prefix string   `egauth:"default=api_key_prefix,token"`
}

APIKeyModule enables API keys of the declared kinds. Kinds are unique tokens; ProtectAPI accepts only these. Prefix, the visible lead of every issued key, is a token too.

type APIKeyRequest added in v0.17.0

type APIKeyRequest struct {
	Kind                  string
	Name                  string
	Roles, Scopes, Groups []string
	Lifetime              keys.Expiry
}

APIKeyRequest describes a key to issue. Kind is one of APIKeyModule.Kinds and Name a printable label of at most 128 bytes. Roles, Scopes and Groups must each be a subset of the caller's current AppClaims; a key never carries Custom, which comes from its owner at every use. The zero Lifetime is invalid: pass keys.ExpireAfter, keys.NeverExpire or keys.DefaultExpiry.

type APIKeySecret added in v0.17.0

type APIKeySecret struct {
	Info APIKeyInfo
	// contains filtered or unexported fields
}

APIKeySecret is a newly issued key: its description and its secret, which is shown once and never stored. It renders the secret as REDACTED under fmt, slog and JSON; only Reveal returns it.

func (APIKeySecret) Format added in v0.17.0

func (s APIKeySecret) Format(f fmt.State, _ rune)

func (APIKeySecret) GoString added in v0.17.0

func (s APIKeySecret) GoString() string

func (APIKeySecret) LogValue added in v0.17.0

func (s APIKeySecret) LogValue() slog.Value

func (APIKeySecret) MarshalJSON added in v0.17.0

func (s APIKeySecret) MarshalJSON() ([]byte, error)

func (APIKeySecret) Reveal added in v0.17.0

func (s APIKeySecret) Reveal() string

Reveal returns the key to hand to its client; never log or persist it.

func (APIKeySecret) String added in v0.17.0

func (s APIKeySecret) String() string

type APIKeys added in v0.17.0

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

APIKeys issues and revokes the API keys of the calling user. Only a session caller has keys: a System caller gets ErrForbidden, an API-key caller ErrAPIKeyCaller and a resource-token caller ErrResourceTokenCaller. Every method needs a live session (ErrSessionEnded otherwise) fresh within SessionPolicy.ReauthWindow and multi-factor when its subject enrolled a second factor. It returns ErrFacadeUnavailable when Modules.APIKeys is nil.

func (*APIKeys) Create added in v0.17.0

Create issues a key owned by the caller. It returns ErrClaimsNotSubset when a requested role, scope or group is not among the caller's current claims, and ErrInvalidRequest for an unknown kind, an over-long name or one that is not printable UTF-8 (controls, format and bidi characters are refused), a blank claim, or a Lifetime that is zero or already over.

func (*APIKeys) List added in v0.17.0

func (k *APIKeys) List(ctx context.Context, by principal.Caller) ([]APIKeyInfo, error)

List returns the caller's keys that are neither revoked nor expired.

func (*APIKeys) Revoke added in v0.17.0

func (k *APIKeys) Revoke(ctx context.Context, by principal.Caller, id uuid.UUID) error

Revoke revokes the caller's key id at once. It returns store.ErrNotFound when the caller owns no such key, and nil for a key already revoked.

type APIKinds added in v0.17.0

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

APIKinds is the non-empty set of API-key kinds a ProtectAPI route accepts; every kind must be declared in APIKeyModule.Kinds. Build it with Kinds; the zero value fails Build.

func Kinds added in v0.17.0

func Kinds(kind string, more ...string) APIKinds

Kinds returns the API-key kinds a ProtectAPI route accepts.

type APIRouteOption added in v0.17.0

type APIRouteOption interface {
	// contains filtered or unexported methods
}

APIRouteOption is a requirement of a ProtectAPI route: a ClaimRequirement only, so a session-only requirement cannot be attached to an API-key route.

type APIRoutes added in v0.17.0

type APIRoutes[C any] struct {
	// contains filtered or unexported fields
}

APIRoutes is the deny-by-default builder of a resource server's routes: serve the handler Build returns at the server root and every request outside the declared routes is 404. An APIRoutes is not safe for concurrent use; the handler Build returns is.

func (*APIRoutes[C]) Build added in v0.17.0

func (rt *APIRoutes[C]) Build() (http.Handler, error)

Build validates every declaration and returns all problems joined: a pattern with no method or with a host, a pattern overlapping another declaration, an invalid requirement, a nil handler or option. It returns ErrClosed after ResourceServer.Close.

func (*APIRoutes[C]) Protect added in v0.17.0

func (rt *APIRoutes[C]) Protect(pattern string, h PrincipalHandler[C], opts ...RouteOption) *APIRoutes[C]

Protect serves h only to a Bearer resource token minted for the server's Audience whose session is still live and passes every requirement in opts, as Routes.Protect does for sessions. Session access tokens, cookies and API keys are refused. Patterns are ServeMux patterns with a method and no host.

type Accounts added in v0.17.0

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

Accounts administers the accounts of the caller's tenant. Every method needs a System caller or a live session caller (ErrSessionEnded otherwise) allowed by Config.Admin, fresh within SessionPolicy.ReauthWindow and multi-factor when its subject enrolled a second factor; RevokeSessions alone also lets a session caller act on itself. Disable, Enable, Delete and SetTemporaryPassword are applied by the identity service the auth endpoints use, which bumps the security epoch, queues the lifecycle outbox and notifies the owner; RevokeSessions and UnlockMFA act on the session backend and the MFA store directly, with no epoch bump, outbox row or notice. A user id of another tenant is never reached: the target is always the caller's tenant.

Example
package main

import (
	"context"
	"errors"

	"github.com/google/uuid"

	"github.com/JLugagne/egauth"
	"github.com/JLugagne/egauth/principal"
	"github.com/JLugagne/egauth/store"
)

func main() {
	ctx := context.Background()
	var auth *egauth.Auth[struct{}]
	var admin principal.Caller
	var user uuid.UUID

	if err := auth.Accounts().Disable(ctx, admin, user); err != nil {
		if errors.Is(err, egauth.ErrForbidden) || errors.Is(err, store.ErrNotFound) {
			return
		}
	}
}

func (*Accounts) Create added in v0.17.0

Create creates an account with a verified email in the caller's tenant. It returns ErrInvalidRequest for a malformed email, ErrFacadeUnavailable for a TemporaryPassword without Modules.Password, identity.ErrIdentifierTaken when a live account of the tenant owns it, and, under TenantKeys, keys.ErrTenantTombstoned for an erased tenant: an account created while Tenants.Erase runs is deleted again before the error returns.

func (*Accounts) Delete added in v0.17.0

func (x *Accounts) Delete(ctx context.Context, by principal.Caller, user uuid.UUID) error

Delete tombstones the account; its factors, keys and sessions are erased by the lifecycle outbox and Hooks.AccountDeleted runs before the row is removed.

func (*Accounts) Disable added in v0.17.0

func (x *Accounts) Disable(ctx context.Context, by principal.Caller, user uuid.UUID) error

Disable suspends the account: every session ends and its API keys stop working until Enable. Unknown or deleted users return store.ErrNotFound or identity.ErrTombstoned.

func (*Accounts) Enable added in v0.17.0

func (x *Accounts) Enable(ctx context.Context, by principal.Caller, user uuid.UUID) error

Enable lifts a suspension; sessions ended by Disable stay ended.

func (*Accounts) RevokeSessions added in v0.17.0

func (x *Accounts) RevokeSessions(ctx context.Context, by principal.Caller, user uuid.UUID) error

RevokeSessions ends every session of the user, like /logout-everywhere; a session caller may revoke its own sessions without the admin role. It returns store.ErrNotFound for an unknown or deleted user.

func (*Accounts) SetTemporaryPassword added in v0.17.0

func (x *Accounts) SetTemporaryPassword(ctx context.Context, by principal.Caller, user uuid.UUID) (TemporaryPassword, error)

SetTemporaryPassword replaces the user's password with a generated one the user must change at the next sign-in; every session of the user ends and the owner is notified. It returns ErrFacadeUnavailable without Modules.Password, whose sign-in alone accepts the password, and store.ErrNotFound for an unknown or deleted user.

func (*Accounts) UnlockMFA added in v0.17.0

func (x *Accounts) UnlockMFA(ctx context.Context, by principal.Caller, user uuid.UUID) error

UnlockMFA clears the TOTP and recovery-code lockouts of the user, so a locked-out user can verify a second factor again at once. It returns store.ErrNotFound for an unknown or deleted user.

type Ack added in v0.17.0

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

Ack records why an opt-out is acceptable. Build it with Acknowledge.

func Acknowledge added in v0.17.0

func Acknowledge(reason string) *Ack

Acknowledge records why an opt-out is acceptable; New rejects an empty or blank reason.

func TestHookDevelopmentAck added in v0.17.0

func TestHookDevelopmentAck(reason string) *Ack

TestHookDevelopmentAck returns an acknowledgement that New accepts only when every origin and audience is loopback, so the opt-outs of egauthtest.Config cannot reach a public deployment. It returns nil, which New refuses, unless called from package egauthtest.

func (*Ack) Reason added in v0.17.0

func (a *Ack) Reason() string

Reason returns the acknowledged reason; it is empty for a nil Ack.

type AdminPolicy added in v0.17.0

type AdminPolicy interface {
	// contains filtered or unexported methods
}

AdminPolicy says which session callers may act on other users through the facades. Build it with RoleAdmin or SelfServiceOnly.

func RoleAdmin added in v0.17.0

func RoleAdmin(role string) AdminPolicy

RoleAdmin lets a session caller whose current AppClaims.Roles holds role act on other users of its tenant. New rejects a blank role.

func SelfServiceOnly added in v0.17.0

func SelfServiceOnly() AdminPolicy

SelfServiceOnly lets no session caller act on another user; only System callers can.

type AppClaims added in v0.17.0

type AppClaims[C any] struct {
	Roles, Groups, Scopes []string
	Custom                C
}

AppClaims is the only claims surface an application controls. Its JSON encoding is capped at MaxAppClaimsBytes, which bounds the access-token cookie but cannot by itself keep it under the 4096-byte browser limit: a session whose cookie would exceed it is refused, never truncated.

type AttestationPolicy added in v0.17.0

type AttestationPolicy uint8

AttestationPolicy is the attestation conveyance requested at passkey registration. The zero value is invalid.

const (
	// AttestationNone requests no attestation statement, which keeps authenticator models private.
	AttestationNone AttestationPolicy = iota + 1
)

type Auth added in v0.17.0

type Auth[C any] struct {
	// contains filtered or unexported fields
}

Auth is the composition object: the only owner of every policy object, store and background worker of a deployment. Build it with New; it is safe for concurrent use.

func New added in v0.17.0

func New[C any](cfg Config[C]) (*Auth[C], error)

New validates the whole wiring and the deployment it points at, then starts the background work that Close stops. It returns every problem at once as an errors.Join of *ConfigError, each naming the exact field path. It checks the egauth tags of Config, the origins, the passkey relying party id against the origins, the store durabilities, the modules and the InsecureOptOuts acknowledgements, then the deployment: the schema of every store, the KEK canary, v0.16 secrets left in place, second-factor enrollments whose module is absent, OAuth discovery, the limiter and the auth route table. New bounds its own blocking calls with StartupTimeout; it takes no context so that no caller deadline can end background work.

Example
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"

	"github.com/JLugagne/egauth"
	"github.com/JLugagne/egauth/kek"
	"github.com/JLugagne/egauth/memstore"
	"github.com/JLugagne/egauth/signing"
)

type inbox struct{ links chan string }

func (m inbox) RegistrationLink(_ context.Context, msg egauth.LinkMessage) error {
	m.links <- msg.Link
	return nil
}
func (inbox) AccountExistsNotice(context.Context, egauth.NoticeMessage) error { return nil }
func (inbox) PasswordResetLink(context.Context, egauth.LinkMessage) error     { return nil }
func (inbox) MagicLink(context.Context, egauth.LinkMessage) error             { return nil }
func (inbox) LoginCode(context.Context, egauth.CodeMessage) error             { return nil }
func (inbox) EmailVerificationLink(context.Context, egauth.LinkMessage) error { return nil }
func (inbox) EmailChangeLink(context.Context, egauth.LinkMessage) error       { return nil }
func (inbox) RecoveryEmailLink(context.Context, egauth.LinkMessage) error     { return nil }
func (inbox) SecurityNotice(context.Context, egauth.SecurityNoticeMessage) error {
	return nil
}

func main() {
	key := make([]byte, 32)
	_, _ = rand.Read(key)
	seed := make([]byte, 32)
	_, _ = rand.Read(seed)
	k, _ := kek.NewLocal(key)
	signer, _ := signing.EdDSA("k1", seed)
	mail := inbox{links: make(chan string, 1)}

	auth, err := egauth.New(egauth.Config[struct{}]{
		PublicOrigin: "http://localhost:8080",
		Proxy:        egauth.DirectClients(),
		Storage:      memstore.New(k),
		KEK:          k,
		Sessions:     egauth.JWT(egauth.StaticKeys(signer)),
		Transport:    egauth.Bearer,
		Admin:        egauth.RoleAdmin("admin"),
		Email:        mail,
		Pages:        egauth.Pages{Login: "/login", AfterLogin: "/", ConfirmRegistration: "/confirm", PasswordReset: "/reset", SecurityRevert: "/revert"},
		Modules:      egauth.Modules{Password: &egauth.PasswordModule{}},
	})
	if err != nil {
		fmt.Println("new:", err)
		return
	}
	defer func() { _ = auth.Close() }()

	h, err := auth.Routes().
		Protect("GET /me", func(w http.ResponseWriter, _ *http.Request, _ egauth.Principal[struct{}]) {
			_, _ = fmt.Fprintln(w, "hello")
		}).
		Build()
	if err != nil {
		fmt.Println("routes:", err)
		return
	}

	call := func(method, path, token string, body map[string]any, hdr ...string) (*httptest.ResponseRecorder, map[string]any) {
		var payload strings.Reader
		if body != nil {
			raw, _ := json.Marshal(body)
			payload = *strings.NewReader(string(raw))
		}
		req := httptest.NewRequest(method, "http://localhost:8080"+path, &payload)
		if body != nil {
			req.Header.Set("Content-Type", "application/json")
		}
		req.Header.Set("Origin", "http://localhost:8080")
		req.Header.Set(egauth.HeaderTransport, "bearer")
		if token != "" {
			req.Header.Set("Authorization", "Bearer "+token)
		}
		for i := 0; i+1 < len(hdr); i += 2 {
			req.Header.Set(hdr[i], hdr[i+1])
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		var out map[string]any
		_ = json.Unmarshal(rec.Body.Bytes(), &out)
		return rec, out
	}

	const email, password = "ada@example.com", "tapir-granite-velvet-orbit-29"
	rec, begin := call("POST", "/auth"+egauth.PathRegister, "", map[string]any{egauth.FieldIdentifier: email, egauth.FieldPassword: password})
	fmt.Println("register:", rec.Code)

	link, _ := url.Parse(<-mail.links)
	bind, _ := begin[egauth.FieldBind].(string)
	rec, _ = call("POST", "/auth"+egauth.PathRegisterConfirm, "", map[string]any{egauth.FieldToken: link.Query().Get(egauth.FieldToken), egauth.FieldBind: bind})
	fmt.Println("confirm:", rec.Code)

	rec, _ = call("POST", "/auth"+egauth.PathLogin, "", map[string]any{egauth.FieldIdentifier: email, egauth.FieldPassword: password})
	access, refresh := rec.Header().Get("X-Egauth-Access-Token"), rec.Header().Get("X-Egauth-Refresh-Token")
	fmt.Println("login:", rec.Code)

	rec, _ = call("GET", "/me", access, nil)
	fmt.Println("me:", rec.Code)

	rec, _ = call("POST", "/auth"+egauth.PathRefresh, "", nil, "X-Egauth-Refresh-Token", refresh)
	access, refresh = rec.Header().Get("X-Egauth-Access-Token"), rec.Header().Get("X-Egauth-Refresh-Token")
	fmt.Println("refresh:", rec.Code)

	rec, _ = call("POST", "/auth"+egauth.PathLogout, access, nil)
	fmt.Println("logout:", rec.Code)

	rec, _ = call("POST", "/auth"+egauth.PathRefresh, "", nil, "X-Egauth-Refresh-Token", refresh)
	fmt.Println("refresh after logout:", rec.Code)
}
Output:
register: 202
confirm: 200
login: 200
me: 200
refresh: 200
logout: 200
refresh after logout: 401

func TestHookNew added in v0.17.0

func TestHookNew[C any](cfg Config[C], s TestSeams) (*Auth[C], error)

TestHookNew is New with seams. Like every TestHook it returns an error unless called from package egauthtest. The outbound SSRF guard stays in force: reaching a loopback provider still needs Insecure.OutboundPrivateNetwork.

func (*Auth[C]) APIKeys added in v0.17.0

func (a *Auth[C]) APIKeys() *APIKeys

APIKeys returns the API-key facade.

func (*Auth[C]) Accounts added in v0.17.0

func (a *Auth[C]) Accounts() *Accounts

Accounts returns the account administration facade.

func (*Auth[C]) Close added in v0.17.0

func (a *Auth[C]) Close() error

Close stops background work and waits for it, returning the errors of the services it closed. The wait is bounded: queued emails and texts get a few seconds to go out, then the running deliveries are cancelled and the rest are reported as event.DeliveryFailed, so a deliverer that hangs cannot hold the shutdown. Close is idempotent: only the first call stops anything and returns an error. Requests served after Close keep their security properties because every revocation check falls back to the store.

func (*Auth[C]) Posture added in v0.17.0

func (a *Auth[C]) Posture() Posture

Posture lists the set InsecureOptOuts with their acknowledged reasons, the storage durability and the live instance count.

func (*Auth[C]) Ready added in v0.17.0

func (a *Auth[C]) Ready(ctx context.Context) error

Ready reports the first unmet readiness condition: ErrClosed after Close, a store whose Ping fails (a schema older than the embedded migrations included), a revocation poll older than revoke.PollBound, a lifecycle outbox row pending for more than an hour, or a second live instance on Ephemeral state. It is safe to call from a readiness probe.

func (*Auth[C]) Routes added in v0.17.0

func (a *Auth[C]) Routes() *Routes[C]

Routes returns a new, empty builder for the application's own routes.

func (*Auth[C]) System added in v0.17.0

func (a *Auth[C]) System(tenant principal.TenantID, reason string) (principal.Caller, error)

System returns a caller for background jobs acting on tenant, the only tenant it may then act on. Every facade refuses it with ErrSystemCallerInRequest when the context descends from a request served through Routes, and every use emits event.SystemCallerUsed carrying reason; a handler the integrator mounts outside Routes is not detected, so never pass its context. reason is exported as a public event attribute, so it must name the job, never a person: 1 to 128 bytes of printable ASCII, otherwise ErrInvalidRequest. A tenant the Tenancy can never serve returns ErrTenantNotServed, here and at every use, also for a caller another Auth minted. A System caller cannot act through APIKeys, whose keys belong to a user.

func (*Auth[C]) Tenants added in v0.17.0

func (a *Auth[C]) Tenants() *Tenants

Tenants returns the tenant administration facade.

type ClaimRequirement added in v0.17.0

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

ClaimRequirement requires roles, scopes or groups of the principal's current claims. It is both a RouteOption and an APIRouteOption. The zero value is invalid and fails Build.

func RequireAllGroups added in v0.17.0

func RequireAllGroups(group string, more ...string) ClaimRequirement

RequireAllGroups requires every one of the groups; Build rejects a blank group.

func RequireAllRoles added in v0.17.0

func RequireAllRoles(role string, more ...string) ClaimRequirement

RequireAllRoles requires every one of the roles; Build rejects a blank role.

func RequireAllScopes added in v0.17.0

func RequireAllScopes(scope string, more ...string) ClaimRequirement

RequireAllScopes requires every one of the scopes; Build rejects a blank scope.

func RequireAnyGroup added in v0.17.0

func RequireAnyGroup(group string, more ...string) ClaimRequirement

RequireAnyGroup requires at least one of the groups; Build rejects a blank group.

func RequireAnyRole added in v0.17.0

func RequireAnyRole(role string, more ...string) ClaimRequirement

RequireAnyRole requires at least one of the roles; Build rejects a blank role.

func RequireAnyScope added in v0.17.0

func RequireAnyScope(scope string, more ...string) ClaimRequirement

RequireAnyScope requires at least one of the scopes; Build rejects a blank scope.

type ClaimsSource added in v0.17.0

type ClaimsSource[C any] interface {
	ClaimsFor(ctx context.Context, s principal.Subject) (AppClaims[C], error)
}

ClaimsSource is the single source of application claims, read at admission and on every renewal (every SessionPolicy.RecheckEvery). It must be safe for concurrent use. Returning ErrUnknownSubject ends the subject's sessions at the next renewal instead of keeping stale claims.

type ClientInfo added in v0.17.0

type ClientInfo struct {
	IP        netip.Addr
	UserAgent string
}

ClientInfo describes the client that triggered a security-relevant change; either field may be empty.

type CodeMessage added in v0.17.0

type CodeMessage struct {
	DeliveryID uuid.UUID
	Tenant     principal.TenantID
	To         string
	Code       string
	ExpiresAt  time.Time
}

CodeMessage carries a short numeric code the recipient types back. fmt and slog render Code as REDACTED; deliverers read the field directly.

func (CodeMessage) Format added in v0.17.0

func (m CodeMessage) Format(f fmt.State, _ rune)

Format renders m as String whatever the verb, so no verb prints Code.

func (CodeMessage) GoString added in v0.17.0

func (m CodeMessage) GoString() string

GoString renders m for %#v with Code redacted.

func (CodeMessage) LogValue added in v0.17.0

func (m CodeMessage) LogValue() slog.Value

LogValue renders m for slog with Code redacted.

func (CodeMessage) String added in v0.17.0

func (m CodeMessage) String() string

String renders m with Code redacted.

type Config added in v0.17.0

type Config[C any] struct {
	PublicOrigin string           `egauth:"required,origin"`
	BasePath     string           `egauth:"default=basepath,path"`
	ExtraOrigins []string         `egauth:"optional,each=origin"`
	SPAOrigins   []string         `egauth:"optional,each=origin"`
	Audiences    []string         `egauth:"optional,each=origin"`
	Proxy        ProxyPolicy      `egauth:"required"`
	Tenancy      Tenancy          `egauth:"default=single_tenant"`
	Storage      Storage          `egauth:"required"`
	KEK          kek.KEK          `egauth:"required"`
	Sessions     SessionBackend   `egauth:"required"`
	Transport    Transport        `egauth:"default=cookies"`
	Policy       SessionPolicy    `egauth:"optional"`
	Admin        AdminPolicy      `egauth:"required"`
	Claims       ClaimsSource[C]  `egauth:"default=empty_claims"`
	Events       event.Sink       `egauth:"default=slog_default"`
	Email        EmailDeliverer   `egauth:"required"`
	SMS          SMSDeliverer     `egauth:"module=LoginCode.SMS|Verification.Phone"`
	Pages        Pages            `egauth:"optional"`
	Modules      Modules          `egauth:"required,oneof_primary"`
	RateLimit    limiter.Limiter  `egauth:"default=storage_limiter"`
	Outbound     OutboundObserver `egauth:"optional"`
	Hooks        Hooks            `egauth:"optional"`
	Insecure     InsecureOptOuts  `egauth:"optional"`
}

Config is the whole wiring of an Auth; New is its only consumer. C is the type of the application's custom claims. The egauth tags are the validation contract: required fields must be set, default= fields take a library default when zero, and module= fields are required exactly when one of the named modules (or session backends) is enabled.

SPAOrigins are the exact origins of single-page applications served from another same-site host that is not a parent of PublicOrigin, with its scheme and registrable domain (https://app.example.com for https://auth.example.com, or a loopback development server). They require SingleTenant. The Build handler answers them with credentialed CORS only on routes classified SPA-safe, and they are the only origins whose Sec-Fetch-Site same-site requests pass the cross-site gate on those routes; auth routes that return a credential in the body stay same-origin; sessions stay HttpOnly cookies on the PublicOrigin host and token headers are never exposed to them. New refuses an origin that is cross-site, carries a {tenant} label, is a parent domain of PublicOrigin, equals another configured origin, is combined with Insecure.SharedCookieDomain, or, with passkeys, falls outside the relying party id (see PasskeyModule.RPID) (doclint:enforced-by egauth.TestConfigSPAOrigins).

func (Config[C]) Format added in v0.17.0

func (c Config[C]) Format(f fmt.State, _ rune)

Format renders c like String for every fmt verb, so no verb reaches the wiring.

func (Config[C]) GoString added in v0.17.0

func (c Config[C]) GoString() string

GoString renders c like String.

func (Config[C]) LogValue added in v0.17.0

func (c Config[C]) LogValue() slog.Value

LogValue renders c for slog like String.

func (Config[C]) MarshalJSON added in v0.17.0

func (c Config[C]) MarshalJSON() ([]byte, error)

MarshalJSON encodes the origins and the enabled modules only, like String.

func (Config[C]) String added in v0.17.0

func (c Config[C]) String() string

String renders the origins and the enabled modules only; stores, keys and deliverers are never formatted.

type ConfigError added in v0.17.0

type ConfigError struct {
	Field   string
	Problem string
}

ConfigError is one configuration problem found by New. Field is the dotted path of the offending field, with [i] for slice elements (for example "Modules.APIKeys.Kinds[0]"). New returns every problem at once as an errors.Join of *ConfigError; use errors.As to read the first one.

func (*ConfigError) Error added in v0.17.0

func (e *ConfigError) Error() string

type CreateAccountRequest added in v0.17.0

type CreateAccountRequest struct {
	Email             string
	TemporaryPassword bool
}

CreateAccountRequest describes an account an administrator creates. Its email is marked verified without any proof of ownership, so the caller must know the address belongs to the intended user: magic links, login codes and password resets reach it at once. With TemporaryPassword the library generates a password the user must change at the first sign-in, and Modules.Password is required; without it the account has no password and signs in through the other enabled modules or a password reset.

type CreatedAccount added in v0.17.0

type CreatedAccount struct {
	Subject           principal.Subject
	TemporaryPassword TemporaryPassword
}

CreatedAccount is the account Accounts.Create made. TemporaryPassword is zero unless requested.

type CredentialKind added in v0.17.0

type CredentialKind uint8

CredentialKind says what a request authenticated with. It is the PrincipalKind of the design; the legacy egauth.PrincipalKind keeps that name until the cutover deletes it.

const (
	// Anonymous is a request with no credential, or one that failed a gate of an Optional route.
	Anonymous CredentialKind = iota
	// Session is an established human session that passed every gate of its route.
	Session
	// APIKey is an API key of a kind the route accepts.
	APIKey
)

type EmailDeliverer added in v0.17.0

type EmailDeliverer interface {
	RegistrationLink(ctx context.Context, m LinkMessage) error
	AccountExistsNotice(ctx context.Context, m NoticeMessage) error
	PasswordResetLink(ctx context.Context, m LinkMessage) error
	MagicLink(ctx context.Context, m LinkMessage) error
	// LoginCode sends an emailed sign-in code; it yields the email_code factor, never sms_code.
	LoginCode(ctx context.Context, m CodeMessage) error
	EmailVerificationLink(ctx context.Context, m LinkMessage) error
	EmailChangeLink(ctx context.Context, m LinkMessage) error
	RecoveryEmailLink(ctx context.Context, m LinkMessage) error
	SecurityNotice(ctx context.Context, m SecurityNoticeMessage) error
}

EmailDeliverer sends one email per message kind. Every method must be safe for concurrent use and idempotent on DeliveryID, which is stable across retries. A kind added in a later release is a compile error in the integrator's code, not a dropped message.

type EndpointID added in v0.17.0

type EndpointID string

EndpointID names an auth endpoint by its Path* constant, relative to BasePath.

type EndpointRequest added in v0.17.0

type EndpointRequest struct {
	Endpoint     EndpointID
	Client       netip.Addr
	Tenant       principal.TenantID
	CaptchaToken string
}

EndpointRequest exposes no request body. fmt, slog and encoding/json render CaptchaToken as REDACTED.

func (EndpointRequest) Format added in v0.17.0

func (r EndpointRequest) Format(f fmt.State, _ rune)

Format renders r like String for every fmt verb, so no verb reaches CaptchaToken.

func (EndpointRequest) GoString added in v0.17.0

func (r EndpointRequest) GoString() string

GoString renders r for %#v with CaptchaToken redacted.

func (EndpointRequest) LogValue added in v0.17.0

func (r EndpointRequest) LogValue() slog.Value

LogValue renders r for slog with CaptchaToken redacted.

func (EndpointRequest) MarshalJSON added in v0.17.0

func (r EndpointRequest) MarshalJSON() ([]byte, error)

MarshalJSON encodes r with CaptchaToken redacted.

func (EndpointRequest) String added in v0.17.0

func (r EndpointRequest) String() string

String renders r with CaptchaToken redacted.

type ExternalFactor added in v0.17.0

type ExternalFactor interface {
	Name() string
	Verify(ctx context.Context, req ExternalRequest) (ExternalIdentity, error)
}

ExternalFactor is a primary factor verified by the application, for LDAP, SAML bridges or an internal SSO. POST {BasePath}/external/{Name}/login calls Verify; a success maps ExternalID to an account through the federation store, never auto-links, and still goes through the MFA policy and the account state. Name must be a token (1 to 32 of [a-z0-9_-]) unique among the factors. Implementations must be safe for concurrent use and must not log ExternalRequest.Secret.

type ExternalIdentity added in v0.17.0

type ExternalIdentity struct {
	ExternalID    string
	Email         string
	EmailVerified bool
}

ExternalIdentity is the account an ExternalFactor vouches for. ExternalID is stable for the account at the source; Email is adopted as verified only when EmailVerified is true.

type ExternalModule added in v0.17.0

type ExternalModule struct {
	Verifiers []ExternalFactor `egauth:"required,nonempty,each=external"`
}

ExternalModule enables application-verified primary factors.

type ExternalRequest added in v0.17.0

type ExternalRequest struct {
	Tenant     principal.TenantID
	Identifier string
	Secret     string
}

ExternalRequest carries no request body beyond the fixed identifier and secret fields. fmt, slog and encoding/json render Secret as REDACTED.

func (ExternalRequest) Format added in v0.17.0

func (r ExternalRequest) Format(f fmt.State, _ rune)

Format renders r like String for every fmt verb, so no verb reaches Secret.

func (ExternalRequest) GoString added in v0.17.0

func (r ExternalRequest) GoString() string

GoString renders r for %#v with Secret redacted.

func (ExternalRequest) LogValue added in v0.17.0

func (r ExternalRequest) LogValue() slog.Value

LogValue renders r for slog with Secret redacted.

func (ExternalRequest) MarshalJSON added in v0.17.0

func (r ExternalRequest) MarshalJSON() ([]byte, error)

MarshalJSON encodes r with Secret redacted.

func (ExternalRequest) String added in v0.17.0

func (r ExternalRequest) String() string

String renders r with Secret redacted.

type Freshness added in v0.17.0

type Freshness = routes.Freshness

Freshness is a reauthentication bound a route can require. The zero Freshness is invalid.

type HeldIdentifier added in v0.17.0

type HeldIdentifier struct {
	Subject principal.Subject
	Kind    identity.IdentifierKind
	Problem IdentifierProblem
}

HeldIdentifier names a held identifier without its value.

type Hooks added in v0.17.0

type Hooks struct {
	BeforeEndpoint func(ctx context.Context, req EndpointRequest) error
	AccountDeleted func(ctx context.Context, deliveryID uuid.UUID, s principal.Subject) error
	TenantErased   func(ctx context.Context, deliveryID uuid.UUID, t principal.TenantID) error
}

Hooks lets the application add checks and react to lifecycle events. BeforeEndpoint runs last in the preamble of every auth endpoint; a non-nil error refuses the request. AccountDeleted and TenantErased run from the lifecycle outbox and are retried until they return nil; the DeliveryID is stable across retries. Every hook must be safe for concurrent use.

type IdentifierProblem added in v0.17.0

type IdentifierProblem uint8

IdentifierProblem says why UpgradeIdentifiersV016 held an identifier back.

const (
	// IdentifierUnrepresentable is a value v0.17 normalisation refuses, such as a quoted local part
	// ("john doe"@example.com stored as john doe@example.com), consecutive dots, or a phone whose
	// first digit after '+' is 0. A value NewIdentifier also refuses reads as the zero Identifier.
	IdentifierUnrepresentable IdentifierProblem = iota + 1
	// IdentifierCollides is an email or phone whose canonical form (v0.17 folds compatibility
	// characters: john@ is john@) is owned by another live account of the tenant. Nothing is
	// merged: the held value stays verbatim.
	IdentifierCollides
)

type IdentifierUpgradeReport added in v0.17.0

type IdentifierUpgradeReport struct {
	Upgraded   int
	Rewritten  int
	Concurrent int
	Held       []HeldIdentifier
}

IdentifierUpgradeReport is the outcome of one UpgradeIdentifiersV016 run. Upgraded counts the accounts this run marked canonical, Rewritten the identifier values it changed, Concurrent the accounts another writer changed first, and Held lists every identifier left in place; held accounts are listed again by every run.

func UpgradeIdentifiersV016 added in v0.17.0

func UpgradeIdentifiersV016(ctx context.Context, s Storage) (IdentifierUpgradeReport, error)

UpgradeIdentifiersV016 re-normalises the email, phone and recovery email of every account a v0.16 deployment wrote, with the normalisation v0.17 applies to logins, and marks the account checked. v0.16 kept compatibility characters (NFC instead of NFKC), quoted local parts and phones that are not E.164, so without it some accounts are not found by their own identifier and a second account can register the folded address. It writes through the store's compare-and-swap, bumps no epoch, is idempotent and safe to run concurrently. An identifier that cannot be made canonical is reported and left verbatim, and the run returns ErrIdentifiersHeld after every other account was handled. A store failure or a cancelled ctx stops the run and returns it. New refuses to start while an account is unchecked, so run it once at startup, before New, after draining the v0.16 replicas.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/JLugagne/egauth"
)

func main() {
	ctx := context.Background()
	var storage egauth.Storage

	report, err := egauth.UpgradeIdentifiersV016(ctx, storage)
	switch {
	case errors.Is(err, egauth.ErrIdentifiersHeld):
		for _, h := range report.Held {
			fmt.Println("repair by hand:", h.Subject, h.Kind, h.Problem)
		}
	case err != nil:
		return
	}
	fmt.Println(report.Upgraded, report.Rewritten)
}

type ImportKeyRequest added in v0.17.0

type ImportKeyRequest struct {
	Tenant   principal.TenantID
	KeyID    string
	Alg      string
	Material []byte
	Lifetime keys.Expiry
	Overlap  keys.Expiry
}

ImportKeyRequest installs caller-supplied key material as Tenant's signer, under the rules of RenewKeysRequest. Material is what the signing constructor of Alg accepts (a PKCS#8 private key, an Ed25519 seed or raw P-256 scalar, or an HS256 secret of at least 32 bytes). It is stored only sealed with the deployment KEK under the tenant and key id as associated data; the key manager holds the opened signer in memory to sign. The request renders it as REDACTED.

func (ImportKeyRequest) Format added in v0.17.0

func (r ImportKeyRequest) Format(f fmt.State, _ rune)

func (ImportKeyRequest) GoString added in v0.17.0

func (r ImportKeyRequest) GoString() string

func (ImportKeyRequest) LogValue added in v0.17.0

func (r ImportKeyRequest) LogValue() slog.Value

func (ImportKeyRequest) MarshalJSON added in v0.17.0

func (r ImportKeyRequest) MarshalJSON() ([]byte, error)

func (ImportKeyRequest) String added in v0.17.0

func (r ImportKeyRequest) String() string

type InsecureOptOuts added in v0.17.0

type InsecureOptOuts struct {
	// NoOriginCheck disables the CSRF and fetch-metadata gate.
	NoOriginCheck *Ack
	// NoRateLimit disables the library rate limits and the limiter probe of New.
	NoRateLimit *Ack
	// NoReauthWindow drops the freshness requirement of sensitive actions; MFA still applies.
	NoReauthWindow *Ack
	// LongSessions raises the SessionPolicy.MaxLifetime bound from 90 days to 400 days.
	LongSessions *Ack
	// EphemeralState accepts Ephemeral stores on a public origin that is not loopback.
	EphemeralState *Ack
	// SharedCookieDomain drops the __Host- prefix of session cookies and scopes them to a parent
	// domain. New refuses it together with SPAOrigins: the shared cookie would reach the SPA host.
	SharedCookieDomain *SharedCookieDomain
	// OutboundPrivateNetwork lets statically configured providers reach private prefixes.
	OutboundPrivateNetwork *OutboundAllowance
	// TenantOutboundPrivateNetwork lets providers registered by a tenant reach private prefixes.
	TenantOutboundPrivateNetwork *OutboundAllowance
}

InsecureOptOuts is the only place where a default control is weakened. Every set field must carry an acknowledgement with a non-empty reason, otherwise New fails; each is listed by Auth.Posture.

type Keys added in v0.17.0

type Keys interface {
	// contains filtered or unexported methods
}

Keys selects where the JWT signing keys come from: StaticKeys or TenantKeys, never both.

func StaticKeys added in v0.17.0

func StaticKeys(active signing.Signer, verifyOnly ...signing.Verifier) Keys

StaticKeys signs with active and also accepts tokens signed by verifyOnly, for a rotation. Key ids must be distinct. An HS256 active key cannot serve resource servers, so New rejects it with a non-empty Audiences.

func TenantKeys added in v0.17.0

func TenantKeys() Keys

TenantKeys takes per-tenant signing keys from Storage.Keys, which New then requires.

type LinkMessage added in v0.17.0

type LinkMessage struct {
	DeliveryID uuid.UUID
	Tenant     principal.TenantID
	To         string
	Link       string
	ExpiresAt  time.Time
}

LinkMessage carries a one-time link built from the public origin, base path and pages. Link is a bearer credential until it expires: fmt and slog render it as REDACTED, so a console deliverer that prints the message does not log a working link. Deliverers read the field directly.

func (LinkMessage) Format added in v0.17.0

func (m LinkMessage) Format(f fmt.State, _ rune)

Format renders m as String whatever the verb, so no verb prints Link.

func (LinkMessage) GoString added in v0.17.0

func (m LinkMessage) GoString() string

GoString renders m for %#v with Link redacted.

func (LinkMessage) LogValue added in v0.17.0

func (m LinkMessage) LogValue() slog.Value

LogValue renders m for slog with Link redacted.

func (LinkMessage) String added in v0.17.0

func (m LinkMessage) String() string

String renders m with Link redacted.

type LoginCodeModule added in v0.17.0

type LoginCodeModule struct {
	Email bool
	SMS   bool
}

LoginCodeModule enables sign-in through a short code sent on the enabled channels; at least one must be enabled.

type MFAModule added in v0.17.0

type MFAModule struct {
	TOTPIssuer string `egauth:"default=totp_issuer"`
}

MFAModule enables TOTP and recovery-code enrollment and the passkey step-up. Enrollment is read from the stores, so a subject who enrolled a second factor is asked for it whatever the modules.

type MagicLinkModule added in v0.17.0

type MagicLinkModule struct{}

MagicLinkModule enables sign-in through an emailed link.

type Modules added in v0.17.0

type Modules struct {
	Password     *PasswordModule
	MagicLink    *MagicLinkModule
	LoginCode    *LoginCodeModule
	Passkey      *PasskeyModule
	OAuth        *OAuthModule
	External     *ExternalModule
	MFA          *MFAModule
	Verification *VerificationModule
	SelfDelete   *SelfDeleteModule
	APIKeys      *APIKeyModule
}

Modules enables the auth features; a nil module is off. At least one primary module (Password, MagicLink, LoginCode with a channel, Passkey, OAuth or External) must be enabled.

func (Modules) Format added in v0.17.0

func (m Modules) Format(f fmt.State, _ rune)

Format renders m like String for every fmt verb, so no verb reaches module settings.

func (Modules) GoString added in v0.17.0

func (m Modules) GoString() string

GoString renders m like String.

func (Modules) LogValue added in v0.17.0

func (m Modules) LogValue() slog.Value

LogValue renders m for slog like String.

func (Modules) MarshalJSON added in v0.17.0

func (m Modules) MarshalJSON() ([]byte, error)

MarshalJSON encodes the enabled module names only, like String.

func (Modules) String added in v0.17.0

func (m Modules) String() string

String lists the enabled modules by name; module settings are never formatted.

type NoticeMessage added in v0.17.0

type NoticeMessage struct {
	DeliveryID uuid.UUID
	Tenant     principal.TenantID
	To         string
}

NoticeMessage tells the recipient that something happened, without a secret.

type OAuthModule added in v0.17.0

type OAuthModule struct {
	Providers []federation.Provider `egauth:"optional,each=provider"`
	PerTenant bool
}

OAuthModule enables federated sign-in. Providers are fixed at New; with PerTenant, tenants register their own providers at runtime through the Tenants facade. One of the two is needed.

type OptOut added in v0.17.0

type OptOut struct {
	Name   string
	Reason string
}

OptOut is one acknowledged InsecureOptOuts field.

type OutboundAllowance added in v0.17.0

type OutboundAllowance struct {
	Prefixes []netip.Prefix
	Ack      *Ack
}

OutboundAllowance lists private prefixes outbound calls may reach. Link-local (169.254.0.0/16, fe80::/10), the IPv4 and IPv6 metadata addresses, loopback outside tests, and any prefix shorter than /8 (IPv4) or /32 (IPv6) are rejected by New.

type OutboundObserver added in v0.17.0

type OutboundObserver interface {
	OutboundStart(req *http.Request) func(resp *http.Response, err error)
}

OutboundObserver is told about every outbound request (OIDC discovery, token exchange, JWKS, breach checks). OutboundStart receives a redacted copy of the request; the returned func, when non-nil, is called once with the outcome. A panic in either is recovered and discarded.

type Pages added in v0.17.0

type Pages struct {
	Login               string `egauth:"module=Password"`
	AfterLogin          string `egauth:"module=OAuth"`
	MFA                 string `egauth:"module=OAuth"`
	Reauth              string `egauth:"optional"`
	Error               string `egauth:"module=OAuth"`
	ConfirmRegistration string `egauth:"module=Password"`
	MagicLink           string `egauth:"module=MagicLink"`
	PasswordReset       string `egauth:"module=Password"`
	VerifyEmail         string `egauth:"module=Verification.Email"`
	ConfirmEmailChange  string `egauth:"module=Verification.Email"`
	SecurityRevert      string `egauth:"required"`
}

Pages are the application pages the library links or redirects to: relative paths on the public origin, or absolute URLs on PublicOrigin or an ExtraOrigins entry. AfterLogin, MFA and Reauth must be paths on PublicOrigin (or absolute URLs reducing to one): a login lands on them through issuance, which serves no other origin. An enabled module that links to a page makes that entry required. SecurityRevert is required in every deployment, because every account can hold a verified email and so receives security notices; Email is required for the same reason. Login is the 303 target of a completed password reset; under TenantBySubdomain an absolute Login on PublicOrigin is reduced to its path so it stays on the tenant's own host.

type PasskeyModule added in v0.17.0

type PasskeyModule struct {
	DisplayName string            `egauth:"required,nonempty"`
	Attestation AttestationPolicy `egauth:"default=attestation_none"`
	RPID        string            `egauth:"optional"`
}

PasskeyModule enables WebAuthn passkeys. The relying party id is RPID when set, otherwise the host of PublicOrigin (the per-tenant host under TenantBySubdomain); New requires it to be a registrable domain and a suffix of every origin, SPAOrigins included. RPID is a lower-case domain that is the host of PublicOrigin or one of its parent domains, such as example.com for a PublicOrigin on auth.example.com and a single-page application on app.example.com; it is refused under TenantBySubdomain. A credential is bound to the relying party id it was registered under: changing RPID on a deployment makes every existing passkey unusable.

type PasswordModule added in v0.17.0

type PasswordModule struct {
	Policy       passwords.Policy        `egauth:"default=password_policy"`
	Breach       passwords.BreachChecker `egauth:"optional"`
	Registration RegistrationMode        `egauth:"default=registration_open"`
}

PasswordModule enables password sign-in, registration through a verified email, and reset. Policy runs after the library floor (8 to 1024 characters after NFKC normalisation) and Breach.

type Posture added in v0.17.0

type Posture struct {
	// OptOuts lists the set InsecureOptOuts fields in declaration order; it is empty for a
	// production configuration.
	OptOuts []OptOut
	// Durability is the one level every security store reports; New refuses a mix.
	Durability store.Durability
	// Instances is the live instance count from the last heartbeat; it is 1 until another instance
	// of the deployment is seen.
	Instances int
}

Posture is the security posture of a running Auth, for operators and for the golden-config assertion of the journey suite.

type Principal added in v0.17.0

type Principal[C any] struct {
	// contains filtered or unexported fields
}

Principal is the authenticated entity of a request, passed to handlers as an argument. The zero Principal is Anonymous. Values are produced only by the route handlers of Build (and, in tests, by egauthtest.NewPrincipal).

func TestHookAPIKeyPrincipal added in v0.17.0

func TestHookAPIKeyPrincipal[C any](info APIKeyInfo, claims AppClaims[C]) (Principal[C], error)

TestHookAPIKeyPrincipal builds an API-key Principal from info, bypassing every gate. Like TestHookSessionPrincipal it returns an error unless called from package egauthtest.

func TestHookSessionPrincipal added in v0.17.0

func TestHookSessionPrincipal[C any](attrs principal.SessionAttrs, claims AppClaims[C]) (Principal[C], error)

TestHookSessionPrincipal builds a session Principal from attrs, bypassing every gate. Its Caller is bound to no stored session, so facades refuse it with ErrSessionEnded. It checks its caller at run time and returns an error unless that caller is in package egauthtest; the repository guard test also fails on any other caller.

func (Principal[C]) APIKey added in v0.17.0

func (p Principal[C]) APIKey() (APIKeyInfo, bool)

APIKey returns the key, and false unless Kind is APIKey.

func (Principal[C]) Caller added in v0.17.0

func (p Principal[C]) Caller() principal.Caller

Caller returns the facade caller of this principal; it is the zero Caller, refused by every facade, for Anonymous. On a ResourceServer route it is a principal.CallerResourceToken, refused by every facade with ErrResourceTokenCaller although Kind is Session. A session Caller is bound to the stored session it was resumed from: facades refuse it with ErrSessionEnded once that session is logged out, revoked or reissued.

func (Principal[C]) Claims added in v0.17.0

func (p Principal[C]) Claims() AppClaims[C]

Claims returns a copy of the application claims; it is zero for Anonymous. For an API key it is the owner's current claims intersected with the key's grant.

func (Principal[C]) Kind added in v0.17.0

func (p Principal[C]) Kind() CredentialKind

Kind returns what the request authenticated with.

func (Principal[C]) Session added in v0.17.0

func (p Principal[C]) Session() (principal.SessionAttrs, bool)

Session returns the sealed session attributes, and false unless Kind is Session.

func (Principal[C]) SessionID added in v0.17.0

func (p Principal[C]) SessionID() (uuid.UUID, bool)

SessionID returns the session lineage id, stable across rotation, Reissue and reauthentication, and false unless Kind is Session.

func (Principal[C]) Subject added in v0.17.0

func (p Principal[C]) Subject() principal.Subject

Subject returns the user, or the owner of the API key; it is zero for Anonymous.

type PrincipalHandler added in v0.17.0

type PrincipalHandler[C any] func(w http.ResponseWriter, r *http.Request, p Principal[C])

PrincipalHandler serves a declared route with the principal its gates admitted.

type ProxyPolicy added in v0.17.0

type ProxyPolicy interface {
	// contains filtered or unexported methods
}

ProxyPolicy says which peers may set forwarding headers. Build it with DirectClients or TrustedProxies.

func DirectClients added in v0.17.0

func DirectClients() ProxyPolicy

DirectClients ignores every forwarding header: the client address is the TCP peer.

func TrustedProxies added in v0.17.0

func TrustedProxies(first netip.Prefix, more ...netip.Prefix) ProxyPolicy

TrustedProxies reads forwarding headers only from peers inside the prefixes. New rejects a /0, an IPv4 prefix shorter than /8, an IPv6 prefix shorter than /16, and an IPv6 prefix covering IPv4-compatible addresses or touching the IPv4-mapped or NAT64 ranges: write IPv4 proxies in IPv4 form.

type RegistrationMode added in v0.17.0

type RegistrationMode uint8

RegistrationMode says who may create an account. The zero value is invalid.

const (
	// RegistrationOpen lets anyone register; no account exists until the email is verified.
	RegistrationOpen RegistrationMode = iota + 1
	// RegistrationInviteOnly creates accounts only through the Accounts facade.
	RegistrationInviteOnly
)

type RememberMePolicy added in v0.17.0

type RememberMePolicy = core.RememberMePolicy

RememberMePolicy is applied once per login journey and sealed into the session.

type RemoveProviderRequest added in v0.17.0

type RemoveProviderRequest struct {
	Tenant principal.TenantID
	Name   string
}

RemoveProviderRequest removes the runtime provider Name of Tenant.

type RenewKeysRequest added in v0.17.0

type RenewKeysRequest struct {
	Tenant   principal.TenantID
	Alg      string
	Lifetime keys.Expiry
	Overlap  keys.Expiry
}

RenewKeysRequest generates a signing key for Tenant and makes it the signer. Alg is one of the signing.Alg* constants, EdDSA when empty. Lifetime bounds the new key and Overlap is how long the previous signer keeps verifying, at most 30 days; NeverExpire is refused for Overlap and the zero Expiry for both.

type ResourceConfig added in v0.17.0

type ResourceConfig struct {
	AuthOrigin string           `egauth:"required,origin"`
	Audience   string           `egauth:"required,origin"`
	Tenant     string           `egauth:"optional"`
	Proxy      ProxyPolicy      `egauth:"required"`
	Revocation RevocationSource `egauth:"required"`
	Events     event.Sink       `egauth:"default=slog_default"`
	Outbound   OutboundObserver `egauth:"optional"`
	Insecure   ResourceInsecure `egauth:"optional"`
}

ResourceConfig is the whole wiring of a ResourceServer; NewResourceServer is its only consumer. AuthOrigin is the exact origin of the Auth, without {tenant}: a resource server verifies one issuer. Audience must be one of the Auth's Config.Audiences. Revocation is FromStorage over the Storage the Auth uses, unless Insecure.RevocationLagUpToTTL is set and Revocation is left nil.

Tenant is the one tenant whose tokens the server accepts; empty means the zero tenant of a SingleTenant Auth. A token whose tenant differs is refused with 401 and never triggers a JWKS fetch. Set it to the tenant behind AuthOrigin for a TenantBySubdomain or TenantFromRequest Auth. NewResourceServer compares it with the tenant the Auth's discovery document reports for AuthOrigin and returns a ConfigError on a mismatch.

Proxy is validated for parity with Config.Proxy but a resource server derives no client address from it. The Auth must be reachable on a public address: there is no outbound private-network allowance in ResourceInsecure.

type ResourceInsecure added in v0.17.0

type ResourceInsecure struct {
	// RevocationLagUpToTTL accepts a resource token until it expires, up to SessionPolicy.RecheckEvery
	// after the session was revoked. It requires ResourceConfig.Revocation to be nil, and
	// NewResourceServer emits one event.InsecureConfiguration carrying the acknowledged reason.
	RevocationLagUpToTTL *Ack
}

ResourceInsecure is the only place where a resource server's default control is weakened.

type ResourceServer added in v0.17.0

type ResourceServer[C any] struct {
	// contains filtered or unexported fields
}

ResourceServer verifies the resource tokens an Auth mints for one audience and serves the routes declared on Routes. It holds no signing material: keys come from the Auth's JWKS. It is safe for concurrent use.

func NewResourceServer added in v0.17.0

func NewResourceServer[C any](cfg ResourceConfig) (*ResourceServer[C], error)

NewResourceServer validates cfg, fetches the Auth's discovery document and JWKS, and starts the revocation followers that Close stops. It returns every problem at once as an errors.Join of *ConfigError: an AuthOrigin whose issuer is another origin, an Audience the Auth does not publish, a claims type C other than the Auth's, a deployment that publishes no JWKS (HS256 or stateful sessions), or a discovery or JWKS fetch that fails. It takes no context; its blocking calls are bounded by StartupTimeout. The server fails closed with 503 on every request once the Auth's JWKS has been unreachable for more than a minute, so the Auth must be reachable at least that often.

func TestHookNewResourceServer added in v0.17.0

func TestHookNewResourceServer[C any](cfg ResourceConfig, s TestResourceSeams) (*ResourceServer[C], error)

TestHookNewResourceServer is NewResourceServer with seams and a 127.0.0.0/8 outbound allowance, so that it can reach an httptest Auth. Like every TestHook it returns an error unless called from package egauthtest.

func (*ResourceServer[C]) Close added in v0.17.0

func (rs *ResourceServer[C]) Close() error

Close stops the revocation followers and waits for them. It is idempotent. Requests served after Close keep their security properties because every revocation check falls back to the store.

func (*ResourceServer[C]) Routes added in v0.17.0

func (rs *ResourceServer[C]) Routes() *APIRoutes[C]

Routes returns a new, empty builder for the resource server's routes.

type RevocationSource added in v0.17.0

type RevocationSource interface {
	// contains filtered or unexported methods
}

RevocationSource says where a resource server learns that a session family or a subject's security epoch changed. Build it with FromStorage.

func FromStorage added in v0.17.0

func FromStorage(s Storage) RevocationSource

FromStorage verifies revocation, epochs and families against the same Storage the Auth uses. It needs Storage.Tokens and Storage.Identity; NewResourceServer rejects a Storage without them.

type RouteOption added in v0.17.0

type RouteOption interface {
	// contains filtered or unexported methods
}

RouteOption is a requirement of a Protect or Optional route: a ClaimRequirement or a SessionRequirement.

type Routes added in v0.17.0

type Routes[C any] struct {
	// contains filtered or unexported fields
}

Routes is the deny-by-default builder of the application's routes. Declare every route on it, then serve the handler returned by Build at the server root: it serves the auth endpoints under BasePath, the discovery document and exactly the declared routes; every other request is 404. A Routes is not safe for concurrent use; the handler Build returns is.

Example
package main

import (
	"net/http"

	"github.com/JLugagne/egauth"
)

func main() {
	var auth *egauth.Auth[struct{}]
	var page, report, adminDisable egauth.PrincipalHandler[struct{}]
	var health http.Handler

	h, err := auth.Routes().
		Optional("GET /", page).
		Protect("POST /admin/disable/{id}", adminDisable,
			egauth.RequireAnyRole("admin"), egauth.RequireMFA(), egauth.RequireFreshAuth(egauth.Fresh5m)).
		ProtectAPI("GET /api/report", report, egauth.Kinds("automation"), egauth.RequireAnyScope("report:read")).
		Public("GET /healthz", health).
		Build()
	if err != nil {
		return
	}
	_ = http.ListenAndServe("localhost:8080", h)
}

func (*Routes[C]) Build added in v0.17.0

func (rt *Routes[C]) Build() (http.Handler, error)

Build validates every declaration and returns all problems joined: a pattern with no method or with a host; a pattern overlapping BasePath, the discovery document or another declaration; an invalid requirement (zero Factor or Freshness, blank role, scope or group); a nil handler or option; ProtectAPI with Modules.APIKeys nil or with an undeclared or repeated kind. It returns ErrClosed after Auth.Close.

A request whose path differs from its RequestURI, as behind http.StripPrefix or a rewriting middleware, is answered 500 and reported once as event.MountMismatch.

func (*Routes[C]) Optional added in v0.17.0

func (rt *Routes[C]) Optional(pattern string, h PrincipalHandler[C], opts ...RouteOption) *Routes[C]

Optional serves h to everyone; a principal that fails any Protect gate or requirement is presented as Anonymous, never as a weaker authenticated principal.

func (*Routes[C]) Protect added in v0.17.0

func (rt *Routes[C]) Protect(pattern string, h PrincipalHandler[C], opts ...RouteOption) *Routes[C]

Protect serves h only to an established human session that passes every session gate and every requirement in opts. Patterns are ServeMux patterns with a method and no host, for example "GET /account/{id}".

func (*Routes[C]) ProtectAPI added in v0.17.0

func (rt *Routes[C]) ProtectAPI(pattern string, h PrincipalHandler[C], kinds APIKinds, opts ...APIRouteOption) *Routes[C]

ProtectAPI serves h only to an API key of one of kinds that meets every requirement in opts; session credentials are refused. Build rejects it when Modules.APIKeys is nil or a kind is not in APIKeyModule.Kinds.

func (*Routes[C]) Public added in v0.17.0

func (rt *Routes[C]) Public(pattern string, h http.Handler) *Routes[C]

Public serves h without authentication; Build lists every public pattern in one event.InsecureConfiguration event (reason "public_routes").

type SMSDeliverer added in v0.17.0

type SMSDeliverer interface {
	// LoginCode sends a texted sign-in code; it yields the sms_code factor, never email_code.
	LoginCode(ctx context.Context, m CodeMessage) error
	PhoneVerificationCode(ctx context.Context, m CodeMessage) error
	// PasswordResetCode sends a texted reset code; it never admits a session and is never accepted
	// as a sign-in code.
	PasswordResetCode(ctx context.Context, m CodeMessage) error
	SecurityNotice(ctx context.Context, m SecurityNoticeMessage) error
}

SMSDeliverer sends one text message per message kind; its contract mirrors EmailDeliverer.

type SecurityEvent added in v0.17.0

type SecurityEvent uint8

SecurityEvent classifies a security notice. Values are never renumbered or reused. An integrator must treat an unrecognised value as a generic notice and show Summary.

const (
	SecurityCredentialRotated SecurityEvent = 1
	SecurityFactorsChanged    SecurityEvent = 2
	SecurityIdentifierChanged SecurityEvent = 3
)

func (SecurityEvent) String added in v0.17.0

func (e SecurityEvent) String() string

String returns the snake_case name of e, or "invalid".

type SecurityNoticeMessage added in v0.17.0

type SecurityNoticeMessage struct {
	DeliveryID uuid.UUID
	Tenant     principal.TenantID
	To         string
	Event      SecurityEvent
	Summary    string
	RevertLink string
	OccurredAt time.Time
	Client     ClientInfo
}

SecurityNoticeMessage tells the account owner that a security-relevant change happened. Summary is library-rendered English so that an unrecognised Event still produces a meaningful message. RevertLink undoes the change for days, so fmt and slog render it as REDACTED; deliverers read the field directly.

func (SecurityNoticeMessage) Format added in v0.17.0

func (m SecurityNoticeMessage) Format(f fmt.State, _ rune)

Format renders m as String whatever the verb, so no verb prints RevertLink.

func (SecurityNoticeMessage) GoString added in v0.17.0

func (m SecurityNoticeMessage) GoString() string

GoString renders m for %#v with RevertLink redacted.

func (SecurityNoticeMessage) LogValue added in v0.17.0

func (m SecurityNoticeMessage) LogValue() slog.Value

LogValue renders m for slog with RevertLink redacted.

func (SecurityNoticeMessage) String added in v0.17.0

func (m SecurityNoticeMessage) String() string

String renders m with RevertLink redacted.

type SelfDeleteModule added in v0.17.0

type SelfDeleteModule struct{}

SelfDeleteModule lets a user delete their own account.

type SessionBackend added in v0.17.0

type SessionBackend interface {
	// contains filtered or unexported methods
}

SessionBackend selects how sessions are carried. Build it with JWT or Stateful.

func JWT added in v0.17.0

func JWT(keys Keys) SessionBackend

JWT carries sessions as short-lived access tokens signed with keys, backed by rotating refresh families in Storage.Tokens. New rejects nil keys.

func Stateful added in v0.17.0

func Stateful() SessionBackend

Stateful carries sessions as opaque handles backed by rows in Storage.Sessions.

type SessionPolicy added in v0.17.0

type SessionPolicy struct {
	IdleTimeout  time.Duration    `egauth:"default=idle_timeout,bound=le:MaxLifetime"`
	MaxLifetime  time.Duration    `egauth:"default=max_lifetime,bound=max:2160h"`
	RecheckEvery time.Duration    `egauth:"default=recheck_every,bound=max:15m"`
	ReauthWindow time.Duration    `egauth:"default=reauth_window,bound=max:1h"`
	Remember     RememberMePolicy `egauth:"default=remember_user_choice"`
}

SessionPolicy bounds session lifetimes. Defaults: idle 168h, max 720h, recheck 5m, reauth 10m. MaxLifetime is at most 2160h (90 days), or 9600h (400 days, the browser cookie cap) with Insecure.LongSessions; IdleTimeout is at most MaxLifetime; RecheckEvery is in (0, 15m] and ReauthWindow in (0, 1h]. A negative value or a value over its bound fails New.

type SessionRequirement added in v0.17.0

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

SessionRequirement is a requirement only a session can meet, so it is a RouteOption and not an APIRouteOption. The zero value is invalid and fails Build.

func AcceptMustChange added in v0.17.0

func AcceptMustChange() SessionRequirement

AcceptMustChange lets a session whose password must change through; by default such a session gets 403 on Protect and is anonymous on Optional.

func RequireFactor added in v0.17.0

func RequireFactor(f principal.Factor) SessionRequirement

RequireFactor requires a session that verified f; Build rejects the zero Factor.

func RequireFreshAuth added in v0.17.0

func RequireFreshAuth(f Freshness) SessionRequirement

RequireFreshAuth requires a session authenticated within f; with several, the strictest applies. Build rejects the zero Freshness.

func RequireMFA added in v0.17.0

func RequireMFA() SessionRequirement

RequireMFA requires a session that completed a second factor.

type SetProviderRequest added in v0.17.0

type SetProviderRequest struct {
	Tenant   principal.TenantID
	Provider federation.Provider
}

SetProviderRequest registers or replaces the OAuth or OIDC provider Provider.Name of Tenant. A generic OIDC spec is discovered now, through the tenant outbound scope that only Insecure.TenantOutboundPrivateNetwork widens. Its EmailVerification is capped at ClaimBased and becomes Never without Domains, which only a System caller may set.

type SharedCookieDomain added in v0.17.0

type SharedCookieDomain struct {
	Domain string
	Ack    *Ack
}

SharedCookieDomain scopes session cookies to Domain, which New requires to be a registrable domain and a suffix of every origin host.

type Storage added in v0.17.0

type Storage struct {
	Identity   identity.Store   `egauth:"required"`
	Ceremonies ceremony.Store   `egauth:"required"`
	Deployment deployment.Store `egauth:"required"`
	Limiter    limiter.Limiter  `egauth:"required"`
	Tokens     tokens.Store     `egauth:"module=Sessions.JWT|APIKeys"`
	Sessions   sessions.Store   `egauth:"module=Sessions.Stateful"`
	MFA        mfa.Store        `egauth:"required"`
	Passkeys   passkey.Store    `egauth:"required"`
	Federation fedstore.Store   `egauth:"module=OAuth|External"`
	Keys       keys.Store       `egauth:"module=Sessions.JWT.TenantKeys"`
}

Storage is every store an Auth reads and writes. pgxstore.New and memstore.New fill every field. MFA and Passkeys are always required: the enrollment decision reads them on every primary login, whatever the modules. Every security store must report the same Durability.

type TemporaryPassword added in v0.17.0

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

TemporaryPassword is a library-generated password, shown once to whoever hands it to the user. It renders as REDACTED under fmt, slog and JSON; only Reveal returns it.

func (TemporaryPassword) Format added in v0.17.0

func (p TemporaryPassword) Format(f fmt.State, _ rune)

func (TemporaryPassword) GoString added in v0.17.0

func (p TemporaryPassword) GoString() string

func (TemporaryPassword) IsZero added in v0.17.0

func (p TemporaryPassword) IsZero() bool

func (TemporaryPassword) LogValue added in v0.17.0

func (p TemporaryPassword) LogValue() slog.Value

func (TemporaryPassword) MarshalJSON added in v0.17.0

func (p TemporaryPassword) MarshalJSON() ([]byte, error)

func (TemporaryPassword) Reveal added in v0.17.0

func (p TemporaryPassword) Reveal() string

Reveal returns the plaintext password; never log or persist it.

func (TemporaryPassword) String added in v0.17.0

func (p TemporaryPassword) String() string

type Tenancy added in v0.17.0

type Tenancy interface {
	// contains filtered or unexported methods
}

Tenancy says how a request is mapped to a tenant. Build it with SingleTenant, TenantBySubdomain or TenantFromRequest.

func SingleTenant added in v0.17.0

func SingleTenant() Tenancy

SingleTenant serves the zero TenantID only.

func TenantBySubdomain added in v0.17.0

func TenantBySubdomain() Tenancy

TenantBySubdomain takes the tenant from the leftmost host label; PublicOrigin must then hold exactly one {tenant} label, as in https://{tenant}.example.com.

func TenantFromRequest added in v0.17.0

func TenantFromRequest(r TenantResolver) Tenancy

TenantFromRequest delegates tenant resolution to r, for example a header set by a trusted gateway. New rejects a nil r.

type TenantResolver added in v0.17.0

type TenantResolver interface {
	ResolveTenant(r *http.Request) (principal.TenantID, error)
}

TenantResolver maps a request to its tenant. An error or a zero TenantID makes the request 401, with no fallback. It must be safe for concurrent use.

type Tenants added in v0.17.0

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

Tenants administers one tenant: its erasure, its signing keys and its runtime OAuth providers. Every method needs a System caller minted for that tenant, or a live session caller of that tenant (ErrSessionEnded otherwise) allowed by Config.Admin, fresh within SessionPolicy.ReauthWindow and multi-factor when its subject enrolled a second factor; ImportKey alone needs a System caller. Any other tenant returns ErrTenantMismatch: cross-tenant work mints one System caller per tenant.

func (*Tenants) Erase added in v0.17.0

func (t *Tenants) Erase(ctx context.Context, by principal.Caller, tenant principal.TenantID) error

Erase removes every record of tenant: keys first, so the tenant is tombstoned before anything else goes, then sessions, API keys, ceremonies, factors, links and Hooks.TenantErased, and the accounts last. Every step is idempotent: on error, call it again.

func (*Tenants) ImportKey added in v0.17.0

func (t *Tenants) ImportKey(ctx context.Context, by principal.Caller, req ImportKeyRequest) error

ImportKey installs req.Material as the signer of req.Tenant, like RenewKeys; it also returns ErrInvalidRequest for material or a key id the signing package refuses. It is the only way to bring external key material in: nothing else seals a signing key. Whoever knows the material can sign any claims for the tenant, so a session caller gets ErrForbidden: only a System caller, outside any request, may import.

func (*Tenants) RemoveOAuthProvider added in v0.17.0

func (t *Tenants) RemoveOAuthProvider(ctx context.Context, by principal.Caller, req RemoveProviderRequest) error

RemoveOAuthProvider removes the runtime provider req.Name of req.Tenant; sign-ins through it fail at once. Identities already linked to it stay linked to its configuration: registering the same Issuer, JWKSURL, TokenURL and UserInfoURL again restores them, and any other configuration under the name is ErrProviderLinked. Removing an unknown provider is a no-op.

func (*Tenants) RenewKeys added in v0.17.0

func (t *Tenants) RenewKeys(ctx context.Context, by principal.Caller, req RenewKeysRequest) error

RenewKeys installs a generated signer for req.Tenant. It returns ErrFacadeUnavailable unless the session backend uses TenantKeys, ErrInvalidRequest for an algorithm, lifetime or overlap the key manager refuses, and keys.ErrTenantTombstoned for an erased tenant.

func (*Tenants) RevokeKeys added in v0.17.0

func (t *Tenants) RevokeKeys(ctx context.Context, by principal.Caller, tenant principal.TenantID) error

RevokeKeys deletes every signing key of tenant at once, for a key compromise: every token they signed stops verifying here at once and on other instances within the revocation poll bound, and the tenant cannot sign again before RenewKeys or ImportKey.

func (*Tenants) SetOAuthProvider added in v0.17.0

func (t *Tenants) SetOAuthProvider(ctx context.Context, by principal.Caller, req SetProviderRequest) error

SetOAuthProvider registers req.Provider for req.Tenant. It returns ErrFacadeUnavailable unless OAuthModule.PerTenant is set, ErrInvalidRequest for a name taken by a static provider or a spec that is invalid or incomplete after discovery, federation.ErrDomainsSystemOnly when a session caller sets Domains, keys.ErrTenantTombstoned for a tenant Erase removed, and ErrProviderLinked when identities are linked to the name under another configuration, a removed provider's included. A failed discovery is ErrInvalidRequest joined with federationsvc.ErrDiscovery alone: its network cause, which can name internal addresses, goes only to the event.OAuthProviderRejected Err; so does any store, KEK or session failure, returned as ErrStorageUnavailable alone. Returned errors are safe to show the calling tenant admin.

type TestClock added in v0.17.0

type TestClock = clock.Clock

TestClock is the library clock, named here so that memstore.NewWithClock can take the clock of an egauthtest.Clock without importing internal/clock. Its zero value reads the wall clock; only egauthtest.Clock.Library returns one that does not.

type TestResourceSeams added in v0.17.0

type TestResourceSeams struct {
	Clock   TestClock
	RootCAs *x509.CertPool
}

TestResourceSeams replaces what a journey test cannot otherwise drive in a ResourceServer: its clock and the roots its outbound client trusts. The zero value keeps the wall clock and the system roots.

type TestSeams added in v0.17.0

type TestSeams struct {
	Clock   TestClock
	RootCAs *x509.CertPool
}

TestSeams replaces what a journey test cannot otherwise drive: the clock every component of the Auth reads, and the roots its outbound client trusts. The zero value keeps the wall clock and the system roots.

type Transport added in v0.17.0

type Transport uint8

Transport selects which credential channels a deployment accepts. A login selects Bearer only through HeaderTransport, and only when the deployment allows it. Even under Bearer, an unauthenticated POST without HeaderTransport or an Authorization Bearer credential is origin-checked like a browser request, so native clients must send HeaderTransport: bearer.

const (
	Cookies Transport = iota + 1
	Bearer
	CookiesAndBearer
)

type UpgradeReport added in v0.17.0

type UpgradeReport struct {
	Upgraded   int
	Concurrent int
	Unopenable []UpgradeRow
}

UpgradeReport is the outcome of one UpgradeSecretsV016 run. Upgraded counts the rows this run re-sealed; Concurrent counts rows another instance re-sealed or replaced first; Unopenable lists every row that no candidate opens.

func UpgradeSecretsV016 added in v0.17.0

func UpgradeSecretsV016(ctx context.Context, s Storage, legacy kek.LegacyOpener, k kek.KEK) (UpgradeReport, error)

UpgradeSecretsV016 re-seals every v0.16 TOTP secret, OAuth client secret and tenant signing key under the v0.17 format, trying each row's legacy associated data (tenant and owner, then tenant alone for signing keys, then none) and writing back through the store's ReplaceSealed compare-and-swap. It is idempotent and safe to run concurrently from several instances: a row another instance changed first is counted as Concurrent and never overwritten. Stores absent from s (Federation, Keys) are skipped. A row that opens under no candidate is listed in the report and makes it return ErrUpgradeIncomplete after every other row was handled. A store failure, a cancelled ctx, a KEK failure or a LegacyOpener error other than kek.ErrOpenFailed and kek.ErrMalformed stops the run and returns it. Run it once at startup, before New.

Example
package main

import (
	"context"
	"fmt"

	"github.com/JLugagne/egauth"
	"github.com/JLugagne/egauth/kek"
)

func main() {
	ctx := context.Background()
	var storage egauth.Storage
	var oldKey, newKey []byte

	legacy, err := kek.LegacyLocalV016(oldKey)
	if err != nil {
		return
	}
	current, err := kek.NewLocal(newKey)
	if err != nil {
		return
	}
	report, err := egauth.UpgradeSecretsV016(ctx, storage, legacy, current)
	if err != nil {
		return
	}
	fmt.Println(report)
}

type UpgradeRow added in v0.17.0

type UpgradeRow struct {
	Kind   string
	Tenant principal.TenantID
	ID     string
}

UpgradeRow names a v0.16 row without any secret material. Kind is the v0.16 table; ID is the user id, the provider name or the key id, and Tenant is the zero TenantID for a single-tenant row.

type VerificationModule added in v0.17.0

type VerificationModule struct{ Email, Phone, RecoveryEmail bool }

VerificationModule enables verification and change of the enabled contact channels; at least one must be enabled.

Directories

Path Synopsis
adapters
otel module
pgx module
Package egauthtest holds the test-only helpers of egauth: the development configuration, the principal builder, the manual clock, a capturing mailbox and a fake OIDC provider.
Package egauthtest holds the test-only helpers of egauth: the development configuration, the principal builder, the manual clock, a capturing mailbox and a fake OIDC provider.
Package event defines egauth's optional security-event seam.
Package event defines egauth's optional security-event seam.
examples
fullstack command
Package main is a runnable reference application of egauth: password, magic link, passkey, TOTP MFA, self-delete and API keys on in-memory storage, composed with New and Routes.
Package main is a runnable reference application of egauth: password, magic link, passkey, TOTP MFA, self-delete and API keys on in-memory storage, composed with New and Routes.
Package federation defines the value spec of an OAuth or OIDC identity provider.
Package federation defines the value spec of an OAuth or OIDC identity provider.
providers
Package providers builds the federation.Provider specs of well-known identity providers.
Package providers builds the federation.Provider specs of well-known identity providers.
providertest
Package providertest is the contract suite of federation providers (G25).
Package providertest is the contract suite of federation providers (G25).
internal
audit
Package audit is the only library emitter of events: it validates attribute keys against the event registry before an event reaches any sink.
Package audit is the only library emitter of events: it validates attribute keys against the event registry before an event reaches any sink.
ceremonycodec
Package ceremonycodec owns the typed payload of every ceremony kind and the stateless handle sealer.
Package ceremonycodec owns the typed payload of every ceremony kind and the stateless handle sealer.
clientaddr
Package clientaddr is the only reader of http.Request.RemoteAddr and of forwarding headers.
Package clientaddr is the only reader of http.Request.RemoteAddr and of forwarding headers.
clock
Package clock is the single owner of wall-clock reads: no other package calls time.Now, time.Since or time.Until.
Package clock is the single owner of wall-clock reads: no other package calls time.Now, time.Since or time.Until.
codesvc
Package codesvc owns the passwordless primary factors: the emailed magic link (email_link) and the one-time login codes sent by email (email_code) or SMS (sms_code).
Package codesvc owns the passwordless primary factors: the emailed magic link (email_link) and the one-time login codes sent by email (email_code) or SMS (sms_code).
configcheck
Package configcheck is the single parser and validator of `egauth` struct tags (DESIGN §3.2).
Package configcheck is the single parser and validator of `egauth` struct tags (DESIGN §3.2).
cookie
Package cookie is the only writer and reader of HTTP cookies.
Package cookie is the only writer and reader of HTTP cookies.
core
Package core owns the sealed authentication vocabulary: the session attributes, the pre-session Pending, verified factors, account state, MFA decisions and every transition between them, plus the binary codec v1 that persists them opaquely.
Package core owns the sealed authentication vocabulary: the session attributes, the pre-session Pending, verified factors, account state, MFA decisions and every transition between them, plus the binary codec v1 that persists them opaquely.
csrf
Package csrf is the only cross-site request gate (DESIGN §6.4, T-10, X-07) and the only reader of the Origin, Referer and Sec-Fetch-* headers.
Package csrf is the only cross-site request gate (DESIGN §6.4, T-10, X-07) and the only reader of the Origin, Referer and Sec-Fetch-* headers.
delivery
Package delivery runs the outbound messages of the auth services (emails, texts) off the request path, on a fixed set of workers, and reports every message it could not deliver as event.DeliveryFailed.
Package delivery runs the outbound messages of the auth services (emails, texts) off the request path, on a fixed set of workers, and reports every message it could not deliver as event.DeliveryFailed.
externalsvc
Package externalsvc owns the application-verified primary factor (DESIGN §5.6): POST /external/{name}/login asks the named Verifier to check the identifier and secret, maps the ExternalID it vouches for to an account through the federation store as provider "external:<name>", creates accounts only under the registration rules and never links an existing one (D6, federationsvc.Directory), and ends in the single admission path, httpx.Issuer.Complete, with the ext factor, so the MFA decision and the account state apply.
Package externalsvc owns the application-verified primary factor (DESIGN §5.6): POST /external/{name}/login asks the named Verifier to check the identifier and secret, maps the ExternalID it vouches for to an account through the federation store as provider "external:<name>", creates accounts only under the registration rules and never links an existing one (D6, federationsvc.Directory), and ends in the single admission path, httpx.Issuer.Complete, with the ext factor, so the MFA decision and the account state apply.
factors
Package factors is the only builder of core.Verified.
Package factors is the only builder of core.Verified.
federationsvc
Package federationsvc owns federated sign-in through OAuth 2.0 and OpenID Connect providers (DESIGN §6.9).
Package federationsvc owns federated sign-in through OAuth 2.0 and OpenID Connect providers (DESIGN §6.9).
flow
Package flow serves the second step of the single MFA handshake (DESIGN §5.1 step 3) and /reauth (§5.3).
Package flow serves the second step of the single MFA handshake (DESIGN §5.1 step 3) and /reauth (§5.3).
httpx
Package httpx is the request edge of every auth endpoint (DESIGN §3.9): the preamble, the single capped parse, the responder and the dependency seam (Env) shared by the services and the composition.
Package httpx is the request edge of every auth endpoint (DESIGN §3.9): the preamble, the single capped parse, the responder and the dependency seam (Env) shared by the services and the composition.
identitysvc
Package identitysvc owns accounts: the identifier normaliser, the authoritative account state, the shared mutation path and the password endpoints (login, verified-email registration, reset).
Package identitysvc owns accounts: the identifier normaliser, the authoritative account state, the shared mutation path and the password endpoints (login, verified-email registration, reset).
issuance
Package issuance is the single admission path (DESIGN §5).
Package issuance is the single admission path (DESIGN §5).
journeytest
Package journeytest is the behavioural guard of egauth (DESIGN section 9.4): a fully enabled Auth on in-memory storage, an HTTP client with a cookie jar, an event recorder, the G22 probe battery and the entry point examples use to run the same probes against their own server.
Package journeytest is the behavioural guard of egauth (DESIGN section 9.4): a fully enabled Auth on in-memory storage, an HTTP client with a cookie jar, an event recorder, the G22 probe battery and the entry point examples use to run the same probes against their own server.
keys
Package keys is the key manager behind the sealed StaticKeys | TenantKeys choice.
Package keys is the key manager behind the sealed StaticKeys | TenantKeys choice.
lifecycle
Package lifecycle defines the account lifecycle events and the Subscriber every component implements in full, so that each component decides every event.
Package lifecycle defines the account lifecycle events and the Subscriber every component implements in full, so that each component decides every event.
mfasvc
Package mfasvc owns the TOTP factor and the recovery codes.
Package mfasvc owns the TOTP factor and the recovery codes.
outbound
Package outbound is the only builder of http.Client and http.Transport (G6).
Package outbound is the only builder of http.Client and http.Transport (G6).
passkeysvc
Package passkeysvc owns the WebAuthn passkey factor (DESIGN §8, §4.3): registration, primary login (discoverable and username-first), the step-up ceremony the MFA flow drives, and credential management.
Package passkeysvc owns the WebAuthn passkey factor (DESIGN §8, §4.3): registration, primary login (discoverable and username-first), the step-up ceremony the MFA flow drives, and credential management.
principalctx
Package principalctx owns the one context slot that carries the request principal.
Package principalctx owns the one context slot that carries the request principal.
principaltest
Package principaltest builds fully populated session state for tests.
Package principaltest builds fully populated session state for tests.
reap
Package reap owns background maintenance: it calls every store.Reaper and retries the lifecycle outbox, on a background ticker and opportunistically from the request path, so a runtime that freezes goroutines between requests (serverless) still reaps (DESIGN §3.1, T-20).
Package reap owns background maintenance: it calls every store.Reaper and retries the lifecycle outbox, on a background ticker and opportunistically from the request path, so a runtime that freezes goroutines between requests (serverless) still reaps (DESIGN §3.1, T-20).
redirect
Package redirect is the single owner of post-login redirect validation (return_to and absolute redirects).
Package redirect is the single owner of post-login redirect validation (return_to and absolute redirects).
repoguard
Package repoguard holds repository-wide source guards that outlive any one API: every exported type with secret-shaped fields must redact itself from fmt and slog, published key literals must be on the secretpolicy denylist, and release tooling installs must be pinned.
Package repoguard holds repository-wide source guards that outlive any one API: every exported type with secret-shaped fields must redact itself from fmt and slog, published key literals must be on the secretpolicy denylist, and release tooling installs must be pinned.
revoke
Package revoke holds the per-process revocation caches of DESIGN.md section 7.4: session families (sid to state), subject security epochs and tenant keysets.
Package revoke holds the per-process revocation caches of DESIGN.md section 7.4: session families (sid to state), subject security epochs and tenant keysets.
routes
Package routes holds the closed registry of endpoint paths, request field names and header names.
Package routes holds the closed registry of endpoint paths, request field names and header names.
sealing
Package sealing is the only caller of kek.KEK Seal and Open (G6) and the only place the associated data of a sealed secret is computed.
Package sealing is the only caller of kek.KEK Seal and Open (G6) and the only place the associated data of a sealed secret is computed.
session
Package session defines the session Backend that the JWT and stateful implementations satisfy, and owns renewal (core.Renew) and unsealing on the session path.
Package session defines the session Backend that the JWT and stateful implementations satisfy, and owns renewal (core.Renew) and unsealing on the session path.
session/backendtest
Package backendtest is the G21 suite of DESIGN §9.3 that every session.Backend runs at the backend level: Run(t, newBackend).
Package backendtest is the G21 suite of DESIGN §9.3 that every session.Backend runs at the backend level: Run(t, newBackend).
session/endpoints
Package endpoints serves the session endpoints every deployment has, whatever its session backend: GET /session and POST /logout, /logout-everywhere and /refresh (DESIGN §3.9).
Package endpoints serves the session endpoints every deployment has, whatever its session backend: GET /session and POST /logout, /logout-everywhere and /refresh (DESIGN §3.9).
session/jwt
Package jwt is the JWT session backend: refresh families in tokens.Store and short-lived egv 2 access tokens, plus the codec that resource servers verify those tokens with.
Package jwt is the JWT session backend: refresh families in tokens.Store and short-lived egv 2 access tokens, plus the codec that resource servers verify those tokens with.
session/stateful
Package stateful is the stateful session backend of DESIGN §3.10: a session is one sessions.Store row holding the sealed attributes and application claims, read on every request.
Package stateful is the stateful session backend of DESIGN §3.10: a session is one sessions.Store row holding the sealed attributes and application claims, read on every request.
kek
Package kek holds the key-encryption key that seals every secret egauth persists: TOTP seeds, OAuth client secrets, tenant signing keys and the deployment data key.
Package kek holds the key-encryption key that seals every secret egauth persists: TOTP seeds, OAuth client secrets, tenant signing keys and the deployment data key.
kektest
Package kektest is the contract suite every kek.KEK implementation runs (G11).
Package kektest is the contract suite every kek.KEK implementation runs (G11).
Package memstore assembles every in-memory store, and the memory limiter, into an egauth.Storage for tests, examples and single-instance development.
Package memstore assembles every in-memory store, and the memory limiter, into an egauth.Storage for tests, examples and single-instance development.
Package passwords defines egauth's password seams — Hasher (hash and constant-time compare), Policy (validate a candidate password), and BreachChecker (k-anonymity breach lookup) — plus the shared error sentinels and the MaxPasswordLength pre-hash DoS cap.
Package passwords defines egauth's password seams — Hasher (hash and constant-time compare), Policy (validate a candidate password), and BreachChecker (k-anonymity breach lookup) — plus the shared error sentinels and the MaxPasswordLength pre-hash DoS cap.
breach
Package breach describes breach-corpus lookups as value specs.
Package breach describes breach-corpus lookups as value specs.
breach/hibp
Package hibp implements passwords.BreachChecker against the Have I Been Pwned "Pwned Passwords" range API using k-anonymity: the password is hashed with SHA-1, and only the first five hex characters of that digest are ever sent to the service.
Package hibp implements passwords.BreachChecker against the Have I Been Pwned "Pwned Passwords" range API using k-anonymity: the password is hashed with SHA-1, and only the first five hex characters of that digest are ever sent to the service.
breach/offline
Package offline implements passwords.BreachChecker against an in-memory set of known- compromised password SHA-1 hashes loaded once at startup (for example from the downloadable HIBP "Pwned Passwords" offline corpus, or a custom blocklist).
Package offline implements passwords.BreachChecker against an in-memory set of known- compromised password SHA-1 hashes loaded once at startup (for example from the downloadable HIBP "Pwned Passwords" offline corpus, or a custom blocklist).
Package principal exposes the read-only authentication vocabulary shared by applications, store implementations and egauth: tenants, subjects, factors and the sealed session attributes.
Package principal exposes the read-only authentication vocabulary shared by applications, store implementations and egauth: tenants, subjects, factors and the sealed session attributes.
Package signing holds the keys egauth signs and verifies access tokens with.
Package signing holds the keys egauth signs and verifies access tokens with.
Package store holds the contracts every egauth store embeds: lifecycle, tenant erasure, expiry reaping, durability and the replication cursor.
Package store holds the contracts every egauth store embeds: lifecycle, tenant erasure, expiry reaping, durability and the replication cursor.
ceremony
Package ceremony holds the closed registry of ceremony kinds and, in later files, the ceremony store contract.
Package ceremony holds the closed registry of ceremony kinds and, in later files, the ceremony store contract.
ceremony/memory
Package memory provides an in-process ceremony.Store.
Package memory provides an in-process ceremony.Store.
ceremony/storetest
Package storetest holds the conformance suite of ceremony.Store implementations.
Package storetest holds the conformance suite of ceremony.Store implementations.
deployment
Package deployment holds the persistence contract of deployment-wide sealed values and instance liveness.
Package deployment holds the persistence contract of deployment-wide sealed values and instance liveness.
deployment/memory
Package memory provides an in-process deployment.Store.
Package memory provides an in-process deployment.Store.
deployment/storetest
Package storetest holds the conformance suite of deployment.Store implementations.
Package storetest holds the conformance suite of deployment.Store implementations.
federation
Package federation holds the persistence contract of per-tenant OAuth and OIDC provider specs and of the identities linked to them.
Package federation holds the persistence contract of per-tenant OAuth and OIDC provider specs and of the identities linked to them.
federation/memory
Package memory provides an in-process federation.Store.
Package memory provides an in-process federation.Store.
federation/storetest
Package storetest holds the conformance suite of federation.Store implementations.
Package storetest holds the conformance suite of federation.Store implementations.
identity
Package identity holds the contract of the account store: users, password credentials, federated links, the per-subject security epoch and the lifecycle outbox.
Package identity holds the contract of the account store: users, password credentials, federated links, the per-subject security epoch and the lifecycle outbox.
identity/memory
Package memory provides an in-process identity.Store.
Package memory provides an in-process identity.Store.
identity/storetest
Package storetest holds the conformance suite of identity.Store implementations.
Package storetest holds the conformance suite of identity.Store implementations.
keys
Package keys holds the persistence contract of per-tenant signing keys.
Package keys holds the persistence contract of per-tenant signing keys.
keys/memory
Package memory provides an in-process keys.Store.
Package memory provides an in-process keys.Store.
keys/storetest
Package storetest holds the conformance suite of keys.Store implementations.
Package storetest holds the conformance suite of keys.Store implementations.
limiter
Package limiter holds the rate-limiter contract.
Package limiter holds the rate-limiter contract.
limiter/memory
Package memory provides an in-process token-bucket limiter.Limiter.
Package memory provides an in-process token-bucket limiter.Limiter.
limiter/storetest
Package storetest holds the conformance suite of limiter.Limiter implementations.
Package storetest holds the conformance suite of limiter.Limiter implementations.
mfa
Package mfa holds the persistence contract of TOTP enrollments and recovery codes.
Package mfa holds the persistence contract of TOTP enrollments and recovery codes.
mfa/memory
Package memory provides an in-process mfa.Store.
Package memory provides an in-process mfa.Store.
mfa/storetest
Package storetest holds the conformance suite of mfa.Store implementations.
Package storetest holds the conformance suite of mfa.Store implementations.
passkey
Package passkey holds the persistence contract of WebAuthn credentials.
Package passkey holds the persistence contract of WebAuthn credentials.
passkey/memory
Package memory provides an in-process passkey.Store.
Package memory provides an in-process passkey.Store.
passkey/storetest
Package storetest holds the conformance suite of passkey.Store implementations.
Package storetest holds the conformance suite of passkey.Store implementations.
sessions
Package sessions holds the contract of the stateful session store.
Package sessions holds the contract of the stateful session store.
sessions/memory
Package memory provides an in-process sessions.Store.
Package memory provides an in-process sessions.Store.
sessions/storetest
Package storetest holds the conformance suite of sessions.Store implementations.
Package storetest holds the conformance suite of sessions.Store implementations.
tokens
Package tokens holds the contract of the refresh-family and API-key store.
Package tokens holds the contract of the refresh-family and API-key store.
tokens/memory
Package memory provides an in-process tokens.Store.
Package memory provides an in-process tokens.Store.
tokens/storetest
Package storetest holds the conformance suite of tokens.Store implementations.
Package storetest holds the conformance suite of tokens.Store implementations.
Package webauthntest is a virtual WebAuthn platform authenticator and the client that drives it from one origin, for tests (G24, X-13).
Package webauthntest is a virtual WebAuthn platform authenticator and the client that drives it from one origin, for tests (G24, X-13).

Jump to

Keyboard shortcuts

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