accesshttp

package
v1.0.0-dev.12 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package accesshttp serves the access HTTP routes over an account.Service. It mounts nothing itself: Routes returns each route's Descriptor and handler for the app's own mux, and every refusal goes through the app's access.ErrorWriter.

Index

Constants

View Source
const (
	ReasonSSOGoverned              = "sso_governed"
	ReasonTTLTooLong               = "ttl_too_long"
	ReasonTTLNegative              = "ttl_negative"
	ReasonNoChange                 = "no_change"
	ReasonExpiryInvalid            = "expiry_invalid"
	ReasonRedirectTooLong          = "redirect_too_long"
	ReasonCurrentPasswordRequired  = "current_password_required"
	ReasonSessionGone              = "session_gone"
	ReasonPendingTooLarge          = "pending_too_large"
	ReasonStaleAuthentication      = "stale_authentication"
	ReasonFlowInvalid              = "flow_invalid"
	ReasonDiscoveryFailed          = "discovery_failed"
	ReasonExchangeFailed           = "exchange_failed"
	ReasonTokenInvalid             = "token_invalid"
	ReasonNonceMismatch            = "nonce_mismatch"
	ReasonNoUsername               = "no_username"
	ReasonProvisioningDisabled     = "provisioning_disabled"
	ReasonNotAdmitted              = "not_admitted"
	ReasonUsernameInvalid          = "username_invalid"
	ReasonRecovery                 = "recovery" // auth_session_required on a recovery route
	ReasonReenableNeedsOtherMethod = failreason.ReenableNeedsOtherMethod
	ReasonTrailingData             = "trailing_data"  // auth_bad_request: data after the JSON value
	ReasonMalformedJSON            = "malformed_json" // auth_bad_request: the body is not one JSON value
	ReasonContentType              = "content_type"   // auth_bad_request: the body is not application/json
	ReasonBody                     = "body"           // auth_bad_request: the body is unreadable or not an object
	ReasonUnknownField             = "unknown_field"  // auth_bad_request: a key the request type lacks
	ReasonTokenInQuery             = "token_in_query" // auth_bad_request: a token route got a token in its URL
)

The access.Error Reason values accesshttp assigns itself, in Reasons order.

Variables

This section is empty.

Functions

func Reasons

func Reasons() []string

Reasons returns every fixed access.Error Reason, each once, in a stable order: accesshttp's own, then access's PasswordRejections, account's PolicyReasons, UsernameReasons, TextErrors and LogFilterReasons, and webauthn's OriginRejections. Two families stay open and are not listed: "provider_error:" followed by an IdP's error code on auth_oidc_failed, and on auth_bad_request the name of the body field, path value or query key that was refused; the refusals of the body or URL as a whole are listed.

Types

type AdminSecurityLogQuery

type AdminSecurityLogQuery struct {
	Kinds       string `json:"kinds,omitempty"`        // LogFilter.Kinds, split on ","
	User        int64  `json:"user,omitempty"`         // LogFilter.UserID
	Actor       int64  `json:"actor,omitempty"`        // LogFilter.ActorUserID
	ActorKey    int64  `json:"actor_key,omitempty"`    // LogFilter.ActorKeyID
	After       int64  `json:"after,omitempty"`        // LogFilter.AfterSeq
	Before      int64  `json:"before,omitempty"`       // LogFilter.BeforeSeq
	Limit       int64  `json:"limit,omitempty"`        // LogFilter.Limit
	OldestFirst bool   `json:"oldest_first,omitempty"` // LogFilter.OldestFirst
}

AdminSecurityLogQuery is authAdminSecurityLog's query. Kinds is a comma-separated list of kinds, OldestFirst is "true" or absent, and every other key is a positive decimal.

type AdminUsersQuery

type AdminUsersQuery struct {
	Key int64 `json:"key,omitempty"` // a positive decimal key ID, or absent
}

AdminUsersQuery is authAdminUsers' query.

type CeremonyResponse

type CeremonyResponse struct {
	Ceremony string `json:"ceremony"` // echoed in X-Auth-Ceremony on finish
	// PublicKey is webauthn.CredentialCreation or webauthn.CredentialAssertion
	// in the browser's JSON shape ({"publicKey": …, "mediation"?}).
	PublicKey json.RawMessage `json:"public_key"`
}

CeremonyResponse is a begun WebAuthn ceremony.

type Class

type Class string

Class is who a route admits; its guard enforces it.

const (
	ClassPublic     Class = "public"
	ClassSession    Class = "session"
	ClassRecentAuth Class = "recent_auth"
	ClassKeyScope   Class = "key_scope" // Scope names the required key scope; a session also passes
	// ClassKeyPermission: a key carrying Scope, or a full session under
	// recent auth (account.Service.RequireKeyPermission).
	ClassKeyPermission Class = "key_permission"
	ClassRecovery      Class = "recovery" // the restricted recovery session only
)

The classes.

type Config

type Config struct {
	// Account supplies the Authenticator, and through it the session cookie
	// and timeouts; accesshttp holds no copy of either. Required.
	Account *account.Service
	// Errors renders every refusal. Required.
	Errors access.ErrorWriter
	// Audit receives the request-level outcomes that change no state. Optional.
	Audit         func(r *http.Request, e access.AuditEvent)
	PendingSealer *access.Sealer // seals the pending-link cookie; nil: an ephemeral sealer
	Logger        *slog.Logger   // nil: slog.Default() at each log call
	Prefix        string         // e.g. "/api/auth"; every path not under OIDCPrefix starts with it
	OIDCPrefix    string         // the OIDC start and callback routes' prefix
	// SignInPath is where the OIDC callback sends a browser on a non-success
	// outcome. A value access.ValidateRedirectURI refuses, empty included, is "/".
	SignInPath string
}

Config configures the handlers.

type CurrentSessionView

type CurrentSessionView struct {
	AuthTime         time.Time     `json:"auth_time"`
	IdleDeadline     time.Time     `json:"idle_deadline"`
	AbsoluteDeadline time.Time     `json:"absolute_deadline"`
	ID               string        `json:"id"`
	Method           access.Method `json:"method"`
}

CurrentSessionView is the caller's own session.

type Descriptor

type Descriptor struct {
	Request  reflect.Type // nil when there is no JSON body
	Query    reflect.Type // the accepted query arguments; nil when none
	Response reflect.Type // nil when the 2xx body is not decoded
	Name     string       // stable, a valid TS identifier, e.g. "authLoginPassword"
	Method   string
	Path     string // full path including the configured prefix
	Class    Class
	Scope    string // ClassKeyScope and ClassKeyPermission only
	Kind     Kind
	Doc      string
	// Codes is every code this route can answer, in [access.Codes] order: its
	// class guard's, its transport's and its account operation's.
	Codes   []access.Code
	Passive bool // verification does not count as activity
	Array   bool // Response is a JSON array of Response
}

Descriptor states one route for an app's mux, gate, census and code generator.

func Descriptors

func Descriptors(cfg DescriptorConfig) []Descriptor

Descriptors returns every route's Descriptor, in Routes order, with no Account: for the same values it equals the Descriptors of New's Routes.

type DescriptorConfig

type DescriptorConfig struct {
	Prefix           string
	OIDCPrefix       string
	AdminScope       string
	ManageUsersScope string
	CreateKeysScope  string
}

DescriptorConfig is what a route's Path and access level read: Config's two prefixes and account.Config's three key scopes.

type Handler

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

Handler serves the access routes. Build it with New.

func New

func New(cfg Config) (*Handler, error)

New refuses a nil Account or Errors.

func (*Handler) Routes

func (h *Handler) Routes() []Route

Routes returns a copy of the routes; the app mounts any subset on its own mux.

type InviteAcceptRequest

type InviteAcceptRequest struct {
	Token    string `json:"token"`
	Username string `json:"username"`
	Password string `json:"password"`
}

InviteAcceptRequest is authInviteAcceptPassword's body.

type InviteRequest

type InviteRequest struct {
	Role  access.Role `json:"role"`
	Hours int         `json:"hours,omitempty"`
}

InviteRequest is authAdminInvite's body.

type KeyCreatedResponse

type KeyCreatedResponse struct {
	Key     string  `json:"key"` // the plaintext, shown once
	Details KeyView `json:"details"`
}

KeyCreatedResponse is a minted key. Only writeShownOnce fills Key.

type KeyView

type KeyView struct {
	CreatedAt  time.Time `json:"created_at"`
	ExpiresAt  time.Time `json:"expires_at,omitzero"`
	LastUsedAt time.Time `json:"last_used_at,omitzero"`
	// PreviousUntil is the overlap's bound, set only while the superseded
	// secret still verifies at the response's now.
	PreviousUntil time.Time `json:"previous_until,omitzero"`
	Owner         string    `json:"owner,omitempty"` // username; set on the admin list only
	Label         string    `json:"label"`
	Prefix        string    `json:"prefix"`
	Suffix        string    `json:"suffix"`
	Scopes        []string  `json:"scopes"`
	ID            int64     `json:"id"`
	UserID        int64     `json:"user_id"`
	ParentKeyID   int64     `json:"parent_key_id,omitempty"` // Key.ParentKeyID()
}

KeyView is one API key, never its secret or hash.

type Kind

type Kind string

Kind is how a route answers: JSON bodies, or a redirect.

const (
	KindJSON     Kind = "json"
	KindRedirect Kind = "redirect"
)

The kinds.

type LogActorView

type LogActorView struct {
	SessionID string `json:"session_id,omitempty"`
	OutOfBand string `json:"out_of_band,omitempty"`
	Label     string `json:"label,omitempty"`
	UserAgent string `json:"user_agent,omitempty"`
	KeySuffix string `json:"key_suffix,omitempty"`
	UserID    int64  `json:"user_id,omitempty"`
	KeyID     int64  `json:"key_id,omitempty"`
}

LogActorView is who made a logged change, with the display data the change's Update snapshotted.

type LogClassView

type LogClassView struct {
	Class   account.LogClass `json:"class"`
	Count   int64            `json:"count"`
	Evicted int64            `json:"evicted"` // removed by the size limit, ever
}

LogClassView is one log class's entry count and cap evictions.

type LogEntryView

type LogEntryView struct {
	At         time.Time        `json:"at"`
	OccurredAt time.Time        `json:"occurred_at"` // Event.At
	Class      account.LogClass `json:"class"`
	Kind       string           `json:"kind"`
	IP         string           `json:"ip,omitempty"`
	Method     access.Method    `json:"method,omitempty"`
	Role       access.Role      `json:"role,omitempty"`
	Detail     string           `json:"detail,omitempty"`
	SessionIDs []string         `json:"session_ids,omitempty"`
	Actor      LogActorView     `json:"actor"`
	Seq        int64            `json:"seq"`
	UserID     int64            `json:"user_id,omitempty"`
	KeyID      int64            `json:"key_id,omitempty"`
	PasskeyID  int64            `json:"passkey_id,omitempty"`
	Trusted    bool             `json:"trusted,omitempty"`
}

LogEntryView is one security-log entry.

type LoginRequest

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

LoginRequest is authLoginPassword's body.

type MeResponse

type MeResponse struct {
	Session     CurrentSessionView `json:"session"`
	Methods     MethodsView        `json:"methods"`
	User        UserView           `json:"user"`
	CanLinkOIDC bool               `json:"can_link_oidc"`
	SSOGoverned bool               `json:"sso_governed"`
}

MeResponse is the signed-in user's own view.

type MethodLockView

type MethodLockView struct {
	Method    access.Method `json:"method"`
	Untrusted bool          `json:"untrusted"`
	Trusted   bool          `json:"trusted"`
}

MethodLockView is one locked method, per trust context.

type MethodsView

type MethodsView struct {
	Locks             []MethodLockView `json:"locks"` // [] when none
	PasskeyCount      int              `json:"passkey_count"`
	Password          bool             `json:"password"`
	OIDCLinked        bool             `json:"oidc_linked"`
	OIDCAvailable     bool             `json:"oidc_available"`
	PasskeysAvailable bool             `json:"passkeys_available"`
	PasswordLogin     bool             `json:"password_login"`
}

MethodsView is what a user can sign in with.

type NameRequest

type NameRequest struct {
	Name string `json:"name"`
}

NameRequest renames a passkey, a session or an API key.

type NewKeyRequest

type NewKeyRequest struct {
	Label         string   `json:"label"`
	Scopes        []string `json:"scopes"`
	ExpiresInDays int      `json:"expires_in_days,omitempty"` // 0 = never
}

NewKeyRequest is authKeyCreate's body.

type NewUserRequest

type NewUserRequest struct {
	Username string      `json:"username"`
	Password string      `json:"password,omitempty"` // empty: no sign-in method until a recovery link
	Role     access.Role `json:"role"`
}

NewUserRequest is authAdminUserCreate's body.

type OIDCCallbackQuery

type OIDCCallbackQuery struct {
	State string `json:"state"`
	Code  string `json:"code,omitempty"`
	Error string `json:"error,omitempty"`
}

OIDCCallbackQuery is what the IdP sends on its redirect (RFC 6749 sections 4.1.2 and 4.1.2.1). It converts to oidc.Callback, which compiles only while the two types have the same fields.

type OIDCSignInQuery

type OIDCSignInQuery struct {
	Redirect string `json:"redirect,omitempty"`
}

OIDCSignInQuery is authOIDCStartSignIn's query.

type OIDCStartResponse

type OIDCStartResponse struct {
	URL string `json:"url"`
}

OIDCStartResponse is the link and step-up starts' answer.

type PasskeyBeginQuery

type PasskeyBeginQuery struct {
	Mediation string `json:"mediation,omitempty"` // "conditional" or absent
}

PasskeyBeginQuery is authLoginPasskeyBegin's query.

type PasskeyView

type PasskeyView struct {
	CreatedAt  time.Time `json:"created_at"`
	LastUsedAt time.Time `json:"last_used_at,omitzero"`
	Name       string    `json:"name"`
	// RPID is the relying-party ID the passkey was registered against; one
	// that differs from the current RP's ID cannot sign in.
	RPID           string `json:"rp_id"`
	ID             int64  `json:"id"`
	BackupEligible bool   `json:"backup_eligible"`
	BackedUp       bool   `json:"backed_up"`
	CloneWarning   bool   `json:"clone_warning,omitempty"`
}

PasskeyView is one passkey.

type PasswordChangeRequest

type PasswordChangeRequest struct {
	CurrentPassword string `json:"current_password,omitempty"`
	Password        string `json:"password"`
}

PasswordChangeRequest is authPasswordSet's body. CurrentPassword is required when the user holds a password.

type PasswordRemoveRequest

type PasswordRemoveRequest struct {
	CurrentPassword string `json:"current_password"`
}

PasswordRemoveRequest is authPasswordRemove's body: the password being removed; empty is current_password_required.

type PasswordRequest

type PasswordRequest struct {
	Password string `json:"password"`
}

PasswordRequest is authStepUpPassword's body.

type PendingLinkResponse

type PendingLinkResponse struct {
	Issuer       string `json:"issuer"`
	UsernameHint string `json:"username_hint,omitempty"`
	Email        string `json:"email,omitempty"`
}

PendingLinkResponse is the identity a pending link would attach.

type ProfileRequest

type ProfileRequest struct {
	DisplayName string `json:"display_name"`
}

ProfileRequest is authProfile's body.

type RecoverPasswordRequest

type RecoverPasswordRequest struct {
	Password     string `json:"password"`
	KeepSessions bool   `json:"keep_sessions,omitempty"`
	KeepKeys     bool   `json:"keep_keys,omitempty"`
}

RecoverPasswordRequest is authRecoveryPassword's body.

type RecoveryPasskeyFinishQuery

type RecoveryPasskeyFinishQuery struct {
	KeepSessions bool `json:"keep_sessions,omitempty"` // "true" or absent
	KeepKeys     bool `json:"keep_keys,omitempty"`     // "true" or absent
}

RecoveryPasskeyFinishQuery is authRecoveryPasskeyFinish's query.

type RecoveryResponse

type RecoveryResponse struct {
	Username string      `json:"username"`
	Methods  MethodsView `json:"methods"`
}

RecoveryResponse is a started recovery.

type RedirectRequest

type RedirectRequest struct {
	Redirect string `json:"redirect,omitempty"` // the app's return path, at most oidc.MaxRedirectBytes
}

RedirectRequest is the OIDC link and step-up starts' body.

type Route

type Route struct {
	Handler http.Handler
	Descriptor
}

Route is one descriptor and its handler, which the app mounts on its own mux at Method and Path.

type SecurityLogView

type SecurityLogView struct {
	Entries []LogEntryView `json:"entries"` // never null: an empty page is []
	Classes []LogClassView `json:"classes"` // one per account.LogClasses() value, in order
}

SecurityLogView is one authAdminSecurityLog page.

type SessionView

type SessionView struct {
	CreatedAt    time.Time `json:"created_at"`
	LastActivity time.Time `json:"last_activity"`
	AuthTime     time.Time `json:"auth_time"`
	// IdleDeadline and AbsoluteDeadline are access.SessionDeadlines of the
	// session under the Authenticator's timeouts.
	IdleDeadline     time.Time     `json:"idle_deadline"`
	AbsoluteDeadline time.Time     `json:"absolute_deadline"`
	ID               string        `json:"id"`
	Label            string        `json:"label,omitempty"`
	UserAgent        string        `json:"user_agent,omitempty"`
	LastIP           string        `json:"last_ip,omitempty"`
	Method           access.Method `json:"method"`
	Current          bool          `json:"current"`
}

SessionView is one session.

type SetupPasskeyBeginRequest

type SetupPasskeyBeginRequest struct {
	Token    string `json:"token,omitempty"`
	Username string `json:"username"`
}

SetupPasskeyBeginRequest is authSetupPasskeyBegin's body.

type SetupPasswordRequest

type SetupPasswordRequest struct {
	Token    string `json:"token,omitempty"` // required when the setup rule asks for one
	Username string `json:"username"`
	Password string `json:"password"`
}

SetupPasswordRequest is authSetupPassword's body.

type SignedInResponse

type SignedInResponse struct {
	SessionID    string   `json:"session_id"`
	User         UserView `json:"user"`
	CloneWarning bool     `json:"clone_warning,omitempty"`
}

SignedInResponse is the answer of every route that signs a user in.

type StateResponse

type StateResponse struct {
	SetupRequired bool `json:"setup_required"`
	PasswordLogin bool `json:"password_login"`
	Passkeys      bool `json:"passkeys"`
	OIDC          bool `json:"oidc"`
}

StateResponse is authState's answer.

type TTLRequest

type TTLRequest struct {
	Hours int `json:"hours,omitempty"` // 0 = the default lifetime
}

TTLRequest is authAdminRecovery's body.

type TokenRequest

type TokenRequest struct {
	Token string `json:"token"`
}

TokenRequest is authRecoveryStart's body.

type TokenResponse

type TokenResponse struct {
	ExpiresAt time.Time `json:"expires_at"`
	Token     string    `json:"token"` // the plaintext, shown once
}

TokenResponse is a minted invite or recovery token. Only writeShownOnce fills Token.

type TokenView

type TokenView struct {
	CreatedAt time.Time           `json:"created_at"`
	ExpiresAt time.Time           `json:"expires_at"`
	Purpose   access.TokenPurpose `json:"purpose"`        // "invite" or "recovery"
	Role      access.Role         `json:"role,omitempty"` // invite only
	// IssuerLineage is the issuing key's LineageIDs, root first; omitted for
	// a token no key issued.
	IssuerLineage []int64 `json:"issuer_lineage,omitempty"`
	Subject       int64   `json:"subject,omitempty"` // recovery only: the user it acts on
	IssuedByKey   int64   `json:"issued_by_key,omitempty"`
}

TokenView is one live invite or recovery token on authAdminTokens. It carries neither the token nor its hash.

type UserMethodsView

type UserMethodsView struct {
	PasskeyCount int  `json:"passkey_count"`
	Password     bool `json:"password"`
}

UserMethodsView is a listed user's password and passkey count.

type UserUpdateRequest

type UserUpdateRequest struct {
	Role    *access.Role `json:"role,omitempty"`
	Enabled *bool        `json:"enabled,omitempty"`
}

UserUpdateRequest is authAdminUserUpdate's body.

type UserView

type UserView struct {
	CreatedAt time.Time `json:"created_at"`
	// Methods is the user's sign-in methods; set on the admin list only.
	Methods     *UserMethodsView `json:"methods,omitempty"`
	Username    string           `json:"username"`
	DisplayName string           `json:"display_name,omitempty"`
	Role        access.Role      `json:"role"`
	// KeyLineage is account.ListedUser.KeyLineage; set on the admin list only.
	KeyLineage []int64 `json:"key_lineage,omitempty"`
	ID         int64   `json:"id"`
	Enabled    bool    `json:"enabled"`
	OIDCLinked bool    `json:"oidc_linked"`
}

UserView is one user.

Jump to

Keyboard shortcuts

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