models

package
v2.14.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: MIT Imports: 7 Imported by: 0 modules, 0 packages

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.

Documentation

Overview

Package models is the internal home for the persisted entities (User, Session, OAuthClient, Agent and others), the Permission catalog, and the sentinel errors shared by storage adapters and services. The root package re-exports every symbol here through aliases, which keeps the public API identical.

Index

Constants

View Source
const (
	EmailChangeKindConfirm = "confirm"
	EmailChangeKindUndo    = "undo"
)

Email change record kinds.

View Source
const (
	CodeWeakPassword         = "weak_password"
	CodeEmailTaken           = "email_taken"
	CodeInvalidCredentials   = "invalid_credentials"
	CodeRateLimited          = "rate_limited"
	CodePasswordResetExpired = "password_reset_expired"
	CodePasswordResetInvalid = "password_reset_invalid"

	// v0.5 codes.
	CodeTOTPRequired    = "totp_required"
	CodeInvalidTOTP     = "invalid_totp"
	CodeAlreadyEnrolled = "already_enrolled"
	CodeWebAuthn        = "webauthn_error"

	// v2.3 identity-linking codes.
	CodeIdentityConflict = "identity.conflict"
	CodeStepUpRequired   = "identity.step_up_required"
	CodeLastAuthMethod   = "identity.last_auth_method"
	CodeIdentityLinked   = "identity.linked"
	CodeIdentityUnlinked = "identity.unlinked"
	CodeAccountMerged    = "account.merged"
)

Stable error codes that callers can switch on. New endpoints return TheAuthError; old endpoints keep returning the sentinels above. They live in internal/models so internal packages can build TheAuthError without an import cycle. Re-exported from root errors.go as untyped string constants.

View Source
const (
	CodeAccountLocked     = "account_locked"
	CodeSignupClosed      = "signup_closed"
	CodeSetupTokenInvalid = "setup_token_invalid"
	CodeBadRequest        = "bad_request"
	CodeUnauthorized      = "unauthorized"
	CodeForbidden         = "forbidden"
	CodeNotFound          = "not_found"
	CodeConflict          = "conflict"
	CodeInternal          = "internal_error"
)

Codes added with the auth hardening work. Additive: no existing code changed.

View Source
const (
	// CodePasswordChangeRequired is returned at sign-in when the account is
	// flagged MustChangePassword. The credential was correct; the caller must
	// complete a password reset before a session is issued.
	CodePasswordChangeRequired = "password_change_required"
	// CodeAccountDisabled is returned at sign-in when the account is disabled.
	CodeAccountDisabled = "account_disabled"
	// CodeReauthRequired is returned by self-service destructive actions when
	// the session was not recently authenticated.
	CodeReauthRequired = "reauth_required"
	// CodeSessionLimit is returned when SessionPolicy.MaxConcurrentSessions is
	// reached and the policy is reject.
	CodeSessionLimit = "session_limit_reached"
	// CodeProviderGrantRevoked is returned when the upstream provider no
	// longer honors the stored refresh token.
	CodeProviderGrantRevoked = "provider_grant_revoked"
	// CodeProviderNoRefresh is returned when the provider or the stored grant
	// cannot be refreshed.
	CodeProviderNoRefresh = "provider_refresh_unsupported"
)

Codes added with the account lifecycle work. Additive: no existing code changed.

View Source
const (
	AuthLevelFull       = "full"
	AuthLevelPending2FA = "pending_2fa"
)

Session auth levels (v0.5). AuthLevelFull is the post-MFA, full-access state. AuthLevelPending2FA is the short-lived state after a successful password verify on an account that also has TOTP enrolled: the user has proven the first factor and may only call /auth/totp/verify or /auth/totp/recovery. RequireAuth rejects pending sessions everywhere else.

View Source
const (
	// AMRPassword is a password sign-in or password step-up.
	AMRPassword = "pwd"
	// AMROTP is a one-time code: TOTP or a recovery code.
	AMROTP = "otp"
	// AMRHardwareKey is a passkey bound to one authenticator (hwk): the
	// credential is not backup eligible.
	AMRHardwareKey = "hwk"
	// AMRSoftwareKey is a synced, backup eligible passkey (swk): its key lives
	// in a credential manager, not in a single device.
	AMRSoftwareKey = "swk"
	// AMRUserVerified marks that the authenticator reported user verification
	// (PIN or biometric) for a passkey assertion ("user", RFC 8176 section 2).
	AMRUserVerified = "user"
	// AMRMFA marks that two or more distinct factors were proved.
	AMRMFA = "mfa"
	// AMREmail is a magic link or emailed code sign-in (not RFC 8176).
	AMREmail = "email"
	// AMRFederated is a social OAuth sign-in (not RFC 8176).
	AMRFederated = "fed"
	// AMRSSO is an enterprise SAML sign-in (not RFC 8176).
	AMRSSO = "sso"
)

RFC 8176 authentication method references recorded on a session. The registered values are pwd, otp, hwk, swk and mfa. AMREmail, AMRFederated and AMRSSO are theauth specific values for flows RFC 8176 has no name for; they are never confused with the registered ones.

View Source
const (
	OrgRoleOwner  = "owner"
	OrgRoleAdmin  = "admin"
	OrgRoleMember = "member"
)

Organization role constants. Scoped to one organization each.

View Source
const (
	AuditOrderAsc  = "asc"
	AuditOrderDesc = "desc"
)

Audit read orders for AuditQuery.Order. The empty value means AuditOrderDesc.

View Source
const (
	AgentMintClientCredentials = "client_credentials"
	AgentMintTokenExchange     = "token_exchange"
	AgentMintJWTBearer         = "jwt_bearer"
)

Mint grants named in AgentMintRequest.Grant.

View Source
const (
	BackchannelStatusPending  = "pending"
	BackchannelStatusApproved = "approved"
	BackchannelStatusDenied   = "denied"
)

BackchannelStatus values persisted in backchannel_requests.status.

View Source
const (
	CIBADeliveryModePoll = "poll"
	CIBADeliveryModePing = "ping"
)

CIBA token delivery mode constants.

View Source
const (
	ConnectedAppSourceRegistered = "registered"
	ConnectedAppSourceDCR        = "dcr"
	ConnectedAppSourceCIMD       = "cimd"
	// ConnectedAppSourceUnknown marks a client that no longer resolves.
	ConnectedAppSourceUnknown = "unknown"
)

Values of ConnectedApp.Source.

View Source
const (
	// ConnectedAppAccessRevoked means issued access tokens were put on the denylist.
	ConnectedAppAccessRevoked = "revoked"
	// ConnectedAppAccessExpireNaturally means offline verifiers accept issued JWTs until exp.
	ConnectedAppAccessExpireNaturally = "expire_naturally"
)

Values of ConnectedAppRevokeResult.AccessTokens.

View Source
const (
	DeviceAuthPending  = "pending"
	DeviceAuthApproved = "approved"
	DeviceAuthDenied   = "denied"
	// DeviceAuthConsumed marks an approved authorization whose tokens were
	// already issued. The transition approved to consumed is atomic, which
	// makes a device_code single use.
	DeviceAuthConsumed = "consumed"
)

DeviceAuthorization status values.

View Source
const (
	DeviceStatusActive = "active"
	// DeviceStatusSuspended is a reversible hold: the device gets no tokens until it is resumed.
	DeviceStatusSuspended = "suspended"
	DeviceStatusRevoked   = "revoked"
)

Device statuses.

View Source
const (
	JWKSStateNext     = "next"
	JWKSStateCurrent  = "current"
	JWKSStatePrevious = "previous"
	JWKSStateRetired  = "retired"
)

JWKS key state constants.

View Source
const (
	ClientOwnerKindUser         = "user"
	ClientOwnerKindOrganization = "organization"
	ClientOwnerKindAgent        = "agent"
	ClientOwnerKindAnonymous    = "anonymous"
)

Client owner kind constants persisted in oauth_clients.owner_kind.

View Source
const (
	ClientAuthSecretBasic = "client_secret_basic"
	ClientAuthSecretPost  = "client_secret_post"
	ClientAuthNone        = "none"
	// ClientAuthPrivateKeyJWT is the RFC 7523 section 2.2 method where the
	// client authenticates by presenting a signed JWT (client_assertion)
	// rather than a shared secret. The signing key is registered via
	// jwks_uri or inline jwks on the OAuthClient row.
	ClientAuthPrivateKeyJWT = "private_key_jwt"
	// ClientAuthClientSecretJWT is the legacy HMAC variant where the
	// client_secret is used as the signing key (HS256). Weaker than
	// private_key_jwt; kept for backward compatibility with RFC 7523
	// compliant stacks that do not have asymmetric keys available.
	ClientAuthClientSecretJWT = "client_secret_jwt"
)

Client authentication method constants advertised in AS metadata and used on /oauth/token client authentication.

View Source
const (
	GrantTypeAuthorizationCode = "authorization_code"
	GrantTypeRefreshToken      = "refresh_token"
	GrantTypeClientCredentials = "client_credentials"
	GrantTypeTokenExchange     = "urn:ietf:params:oauth:grant-type:token-exchange"
	// GrantTypeJWTBearer is the RFC 7523 section 2.1 grant type: an
	// externally-issued JWT is presented directly in exchange for an AS-
	// issued access token. Used for workload identity flows (GCP SA tokens,
	// k8s ServiceAccount tokens, AWS IAM Roles Anywhere).
	GrantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer"
)

Grant type constants. Phase 1 + 2 ships authorization_code and refresh_token; phase 3 adds client_credentials, phase 4 adds the RFC 8693 token-exchange grant URN, and RFC 7523 adds the jwt-bearer grant.

View Source
const (
	TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token"
	// TokenTypeIDJAG identifies an Identity Assertion JWT Authorization
	// Grant (draft-ietf-oauth-identity-assertion-authz-grant).
	TokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag"
)

Token type URNs used by the RFC 8693 token-exchange grant.

View Source
const (
	AccessTokenFormatJWT    = "jwt"
	AccessTokenFormatOpaque = "opaque"
)

Access token formats selectable per client.

View Source
const (
	SubjectTypePublic   = "public"
	SubjectTypePairwise = "pairwise"
)

Subject identifier types (OIDC Core section 8).

View Source
const (
	AgentStatusActive    = "active"
	AgentStatusSuspended = "suspended"
	AgentStatusRevoked   = "revoked"
)

Agent lifecycle status values persisted in agents.status.

View Source
const (
	AgentCredentialKindSecret = "secret"
	AgentCredentialKindX509   = "x509"
	AgentCredentialKindJWK    = "jwk"
)

Agent credential kind constants persisted in agent_credentials.kind.

View Source
const (
	CodePasskeyUnknown              = "passkey_unknown"
	CodeConditionalCreateDisabled   = "conditional_create_disabled"
	CodeConditionalCreateNotAllowed = "conditional_create_not_allowed"
)

Passkey lifecycle error codes.

View Source
const (
	PermissionBillingRead    = "billing:read"
	PermissionBillingWrite   = "billing:write"
	PermissionBillingAdmin   = "billing:admin"
	PermissionUsersRead      = "users:read"
	PermissionUsersInvite    = "users:invite"
	PermissionUsersAdmin     = "users:admin"
	PermissionRolesRead      = "roles:read"
	PermissionRolesAdmin     = "roles:admin"
	PermissionAuditRead      = "audit:read"
	PermissionSAMLAdmin      = "saml:admin"
	PermissionSCIMAdmin      = "scim:admin"
	PermissionSessionsRevoke = "sessions:revoke"

	// v2.0 phase 6 additions. agents:admin grants organization-scoped
	// agent CRUD via /admin/v1/.../agents; delegations:admin grants
	// delegation CRUD via /admin/v1/.../delegations. Seeded into every
	// organization's "owner" and "admin" default roles.
	PermissionAgentsAdmin      = "agents:admin"
	PermissionDelegationsAdmin = "delegations:admin"

	// v2.3 identity linking additions.
	// account:link allows the caller to link or unlink OAuth providers
	// and password credentials to their own account.
	PermissionAccountLink = "account:link"
	// account:merge allows the caller to initiate a destructive merge of
	// a secondary user record into their own (primary) account.
	PermissionAccountMerge = "account:merge"
)

Seeded permission catalog. Every consumer's permission set extends (never shrinks) this list; New returns an error if a custom Permission name duplicates a seeded one with a different description (defensive against silent overrides).

The list is intentionally finite and small. Wildcards and ABAC are deferred to v1.x per the v1.0 design document.

View Source
const AccountabilityMetadataKey = "_accountability"

AccountabilityMetadataKey is the reserved metadata key under which stores without native accountability columns keep these fields.

View Source
const AgentSubjectPrefix = "agent:"

AgentSubjectPrefix is prepended to an agent ID inside JWT sub and act.sub claims so resource servers can distinguish a user subject from an agent subject without consulting storage.

View Source
const ClientAssertionTypeJWTBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"

ClientAssertionTypeJWTBearer is the client_assertion_type value for RFC 7523 section 2.2 client authentication via signed JWT.

View Source
const DeviceAttestationJoinToken = "join_token"

DeviceAttestationJoinToken is the attestation kind of a device enrolled with a single-use join token.

View Source
const DeviceSubjectPrefix = "device:"

DeviceSubjectPrefix is prepended to a device ID for the access token sub when the device has no SPIFFE ID.

View Source
const GrantTypeCIBA = "urn:openid:params:grant-type:ciba"

CIBA grant type URN per RFC 9509 section 4.

View Source
const GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code"

GrantTypeDeviceCode is the RFC 8628 section 3.4 grant type URN.

View Source
const MaxAgentLifetime = 10 * 365 * 24 * time.Hour

MaxAgentLifetime is the farthest an agent expiry may be set from now.

View Source
const (
	ResponseTypeCode = "code"
)

Response type constants. OAuth 2.1 supports only "code".

View Source
const SystemRoleSuperAdmin = "super_admin"

SystemRoleSuperAdmin is the global role whose presence on a user bypasses every permission check. It is created at seed time with a NULL organization_id and is granted via direct DB insert or a CLI; the admin API never exposes a path to grant it.

Variables

View Source
var (
	// ErrInvalidToken is returned by any service that fails to authenticate
	// or validate a presented opaque token.
	ErrInvalidToken = errors.New("theauth: invalid token")

	// ErrSessionExpired is returned by session lookups whose row exists but
	// is past its ExpiresAt or has a non-nil RevokedAt.
	ErrSessionExpired = errors.New("theauth: session expired")

	// ErrMagicLinkExpired is returned by magic link consumption when the
	// row is past ExpiresAt or already used.
	ErrMagicLinkExpired = errors.New("theauth: magic link expired")

	// ErrStorageNotFound is the canonical row-missing sentinel. Storage adapters return it on lookup
	// misses, and services can check it without importing storage.
	ErrStorageNotFound = errors.New("theauth: storage row not found")

	// ErrBadCursor is returned by storage adapters when a keyset pagination cursor fails to decode.
	// Handlers match it with errors.Is.
	ErrBadCursor = errors.New("theauth: invalid pagination cursor")

	// ErrBadAuditOrder is returned when AuditQuery.Order is neither "", "asc" nor "desc".
	ErrBadAuditOrder = errors.New("theauth: invalid audit order")

	// ErrAuditOrderUnsupported is returned when an audit query asks for ascending order, an event
	// filter or a write-order cursor and the storage backend does not declare write order support
	// (AuditOrderSupported() bool). The query is refused instead of silently ignoring the filter.
	ErrAuditOrderUnsupported = errors.New("theauth: audit storage backend does not support write order, event filters or c1 cursors")

	// ErrAuditProvenanceUnsupported is returned when an audit query has a Provenance filter and the
	// storage backend does not declare AuditProvenanceSupported() true. The query is refused
	// instead of silently ignoring the filter.
	ErrAuditProvenanceUnsupported = errors.New("theauth: audit storage backend does not support the provenance filter")

	// ErrBadProvenanceFilter is returned for a provenance filter with an unknown kind or a hash that
	// is not 64 lowercase hex characters.
	ErrBadProvenanceFilter = errors.New("theauth: invalid audit provenance filter")

	// ErrLastOwner is returned when an org member removal would leave the
	// organization with zero owners.
	ErrLastOwner = errors.New("theauth: cannot remove the last owner")

	// ErrSlugTaken is returned when the supplied organization slug already
	// exists. It lives in internal/models so internal packages can match it.
	ErrSlugTaken = errors.New("theauth: organization slug already taken")

	// ErrForbidden indicates the caller lacks a required permission for
	// the requested operation. Handlers map this to 403 with code
	// "rbac.forbidden" in the RFC 7807 problem body.
	ErrForbidden = errors.New("theauth: forbidden")

	// ErrUnknownPermission indicates a permission name not present in the
	// seeded or extended catalog. Mapped to 400 "rbac.unknown_permission".
	ErrUnknownPermission = errors.New("theauth: unknown permission")

	// ErrRoleInUse indicates a DELETE role would leave the organization
	// without any user holding the "users:admin" permission. Mapped to
	// 409 "rbac.role_in_use".
	ErrRoleInUse = errors.New("theauth: role in use")

	// ErrRBACDisabled is returned by RBAC service methods invoked when
	// Config.RBAC is nil. The RequirePermission middleware short-circuits
	// to 500 rather than returning this error directly.
	ErrRBACDisabled = errors.New("theauth: RBAC disabled (Config.RBAC is nil)")

	// ErrASRequiresEncryptionKey is returned by New when
	// Config.AuthorizationServer is non-nil but Config.EncryptionKey is not a
	// 32-byte AES-256 key.
	ErrASRequiresEncryptionKey = errors.New("theauth: AuthorizationServer requires Config.EncryptionKey (32 bytes)")

	// ErrASIssuerRequired is returned by New when Config.AuthorizationServer
	// is non-nil but Issuer is empty.
	ErrASIssuerRequired = errors.New("theauth: AuthorizationServer.Issuer is required")

	// ErrASUnsupportedAlg is returned by New for any signing algorithm other
	// than EdDSA, ES256 and RS256.
	ErrASUnsupportedAlg = errors.New("theauth: AuthorizationServer.SigningAlg must be EdDSA, ES256 or RS256")

	// ErrOAuthInvalidRequest maps to the OAuth 2.1 "invalid_request" error.
	ErrOAuthInvalidRequest = errors.New("theauth: invalid_request")

	// ErrOAuthInvalidClient maps to the OAuth 2.1 "invalid_client" error.
	ErrOAuthInvalidClient = errors.New("theauth: invalid_client")

	// ErrOAuthInvalidGrant maps to the OAuth 2.1 "invalid_grant" error.
	ErrOAuthInvalidGrant = errors.New("theauth: invalid_grant")

	// ErrOAuthInvalidScope maps to the OAuth 2.1 "invalid_scope" error.
	ErrOAuthInvalidScope = errors.New("theauth: invalid_scope")

	// ErrOAuthUnsupportedGrantType maps to "unsupported_grant_type".
	ErrOAuthUnsupportedGrantType = errors.New("theauth: unsupported_grant_type")

	// ErrOAuthUnsupportedResponseType maps to "unsupported_response_type".
	ErrOAuthUnsupportedResponseType = errors.New("theauth: unsupported_response_type")

	// ErrOAuthInvalidAuthorizationDetails maps to the RFC 9396 section 5 error
	// "invalid_authorization_details".
	ErrOAuthInvalidAuthorizationDetails = errors.New("theauth: invalid_authorization_details")

	// ErrOAuthInvalidResource maps to RFC 8707 "invalid_target".
	ErrOAuthInvalidResource = errors.New("theauth: invalid_target")

	// ErrOAuthRegistrationDenied is returned when DCR is attempted without a
	// valid initial access token and AllowAnonymousRegistration is false.
	ErrOAuthRegistrationDenied = errors.New("theauth: registration not permitted")

	// ErrOAuthRedirectURIMismatch is returned when the token request's
	// redirect_uri does not equal the value bound to the authorization code.
	ErrOAuthRedirectURIMismatch = errors.New("theauth: redirect_uri mismatch")

	// ErrOAuthPKCEMismatch is returned when the supplied code_verifier does
	// not match the stored code_challenge under S256.
	ErrOAuthPKCEMismatch = errors.New("theauth: pkce verification failed")

	// ErrOAuthAudienceMismatch is returned at introspection when a token's
	// aud claim does not match the caller's expected resource identifier.
	ErrOAuthAudienceMismatch = errors.New("theauth: token audience mismatch")

	// ErrNotImplemented is returned by service paths that exist for forward
	// compatibility but whose body lands in a later phase.
	ErrNotImplemented = errors.New("theauth: not implemented")

	// ErrAgentNotFound is returned by lookups whose target agent is absent.
	ErrAgentNotFound = errors.New("theauth: agent not found")

	// ErrAgentInactive is returned when an operation depends on an agent
	// whose status is suspended or revoked.
	ErrAgentInactive = errors.New("theauth: agent inactive")

	// ErrAgentExpired is returned when an operation depends on an agent whose ExpiresAt has passed.
	// It wraps ErrAgentInactive so existing inactive checks keep matching; the code is agent_expired.
	ErrAgentExpired = fmt.Errorf("%w: agent_expired", ErrAgentInactive)

	// ErrAgentExpiryInvalid is returned when a requested agent expiry is in the past or too far ahead.
	ErrAgentExpiryInvalid = errors.New("theauth: agent expiry must be in the future and within the maximum agent lifetime")

	// ErrDelegationNotFound is returned when no delegation_grants row
	// matches the (user, agent, resource) tuple.
	ErrDelegationNotFound = errors.New("theauth: delegation grant not found")

	// ErrDelegationRevoked is returned when a delegation grant exists but
	// its revoked_at is set.
	ErrDelegationRevoked = errors.New("theauth: delegation grant revoked")

	// ErrChainDepthExceeded is returned by the token exchange path when
	// adding the requesting agent to the actor chain would exceed the
	// AgentConfig.MaxChainDepth (default 3).
	ErrChainDepthExceeded = errors.New("theauth: actor chain depth exceeded")

	// ErrSubjectTokenInvalid is returned when the supplied subject_token
	// fails signature, issuer, expiry, or audience checks.
	ErrSubjectTokenInvalid = errors.New("theauth: subject_token invalid")

	// ErrActorTokenInvalid is returned when the supplied actor_token fails
	// signature, issuer, expiry, or audience checks, or when it does not
	// resolve to the authenticated agent client.
	ErrActorTokenInvalid = errors.New("theauth: actor_token invalid")

	// ErrAgentRequiresAS is returned by New when Config.AgentIdentity is
	// non-nil but Config.AuthorizationServer is nil.
	ErrAgentRequiresAS = errors.New("theauth: AgentIdentity requires AuthorizationServer to be configured")

	// ErrAgentChainDepthTooHigh is returned by New when
	// AgentConfig.MaxChainDepth exceeds the v2.0 hard ceiling of 3.
	ErrAgentChainDepthTooHigh = errors.New("theauth: AgentConfig.MaxChainDepth must not exceed 3 in v2.0")

	// ErrAccountUXRequiresAgents is returned by New when Config.AccountUX is
	// true but Config.AgentIdentity is nil.
	ErrAccountUXRequiresAgents = errors.New("theauth: AccountUX requires AgentIdentity to be configured")

	// ErrStorageMissingOAuthMethods is returned by New when
	// Config.AuthorizationServer is non-nil but the supplied Storage does
	// not satisfy the OAuthServerStorage extension. Catches in-memory
	// adapters that pre-date the v2.0 storage surface.
	ErrStorageMissingOAuthMethods = errors.New("theauth: Storage does not implement OAuthServerStorage")

	// ErrIdentityConflict is returned by LinkOAuthToCurrentUser when the
	// OAuth account being linked is already bound to a different user. The
	// conflicting user ID is surfaced via ConflictingUserID on the wrapped
	// IdentityConflictError so consumer UIs can present a merge confirmation.
	ErrIdentityConflict = errors.New("theauth: oauth account already linked to another user")

	// ErrStepUpRequired is returned when a link or merge operation is
	// called with a session that is not fully authenticated (AuthLevel is
	// pending_2fa or the session is otherwise incomplete). Consumer
	// middleware should map this to the pending_2fa response shape.
	ErrStepUpRequired = errors.New("theauth: step-up authentication required")

	// ErrLastAuthMethod is returned when an unlink or DELETE would remove
	// the only remaining authentication method from the account, which
	// would lock the user out permanently.
	ErrLastAuthMethod = errors.New("theauth: cannot remove the last authentication method")
)

Sentinel errors shared by the storage layer and services. The root re-exports them through var aliases for v0.1 callers that errors.Is-check them. Only model-layer sentinels live here; wire-protocol and service-flow sentinels stay in root.

View Source
var (
	// ErrStorageMissingCapability is returned by New when an enabled feature needs a capability the
	// storage lacks.
	ErrStorageMissingCapability = errors.New("theauth: storage does not implement a required capability")
	// ErrImportDuplicate is returned by the import helpers when the record already exists.
	ErrImportDuplicate = errors.New("theauth: import: record already exists")
)

Sentinels shared by the import helpers and the capability checks.

View Source
var (
	// ErrCIBAAuthorizationPending is returned by the token endpoint poll
	// when the user has not yet approved or denied the request.
	ErrCIBAAuthorizationPending = errors.New("theauth: authorization_pending")

	// ErrCIBASlowDown is returned when the client polls faster than
	// MinPollInterval. The client should double its polling interval.
	ErrCIBASlowDown = errors.New("theauth: slow_down")

	// ErrCIBAAccessDenied is returned when the user denied the request.
	ErrCIBAAccessDenied = errors.New("theauth: access_denied (ciba)")

	// ErrCIBAExpiredToken is returned when the auth_req_id has passed its
	// ExpiresAt deadline.
	ErrCIBAExpiredToken = errors.New("theauth: expired_token")

	// ErrCIBAInvalidRequest is returned when required hint parameters are
	// missing or mutually exclusive constraints are violated.
	ErrCIBAInvalidRequest = errors.New("theauth: invalid_request (ciba)")

	// ErrCIBADisabled is returned when a CIBA endpoint is called but
	// Config.CIBA is nil, or the storage does not implement CIBAStorage.
	ErrCIBADisabled = errors.New("theauth: CIBA not enabled")

	// ErrCIBAUserMismatch is returned by ApproveBackchannelAuth /
	// DenyBackchannelAuth when the supplied userID does not match the
	// resolved subject on the pending request.
	ErrCIBAUserMismatch = errors.New("theauth: ciba user mismatch")
)

CIBA sentinel errors. Re-exported from the root package in errors_ciba.go via var aliases for backward compatibility.

View Source
var (
	// ErrProviderGrantRevoked means the provider no longer honors the stored
	// refresh token (user revoked access, token expired or rotated away). The
	// stored tokens are cleared; the user must sign in with the provider again.
	ErrProviderGrantRevoked = errors.New("theauth: provider grant revoked")
	// ErrProviderRefreshUnsupported means the provider cannot refresh tokens,
	// or no refresh token is stored for the account.
	ErrProviderRefreshUnsupported = errors.New("theauth: provider token refresh unsupported")
	// ErrProviderNotLinked means the user has no linked account for the provider.
	ErrProviderNotLinked = errors.New("theauth: provider account not linked")
)

Upstream provider token sentinels. They are wrapped in a TheAuthError with the matching Code, so both errors.Is on the sentinel and on a code-only TheAuthError work.

View Source
var (
	// ErrDeviceAuthorizationPending maps to authorization_pending.
	ErrDeviceAuthorizationPending = errors.New("theauth: authorization_pending (device)")
	// ErrDeviceSlowDown maps to slow_down.
	ErrDeviceSlowDown = errors.New("theauth: slow_down (device)")
	// ErrDeviceAccessDenied maps to access_denied.
	ErrDeviceAccessDenied = errors.New("theauth: access_denied (device)")
	// ErrDeviceExpiredToken maps to expired_token.
	ErrDeviceExpiredToken = errors.New("theauth: expired_token (device)")
	// ErrDeviceAuthDisabled is returned when the device grant is not configured
	// or the storage does not implement DeviceAuthorizationStorage.
	ErrDeviceAuthDisabled = errors.New("theauth: device authorization not enabled")
	// ErrDeviceAuthUserCodeTaken is returned by InsertDeviceAuthorization when
	// the user code hash collides with a live record. The service retries
	// with a fresh code.
	ErrDeviceAuthUserCodeTaken = errors.New("theauth: device authorization user code already in use")
	// ErrDeviceUserCodeInvalid is returned for an unknown, expired or
	// already decided user code. One error covers all three so the
	// verification page cannot be used to probe which codes exist.
	ErrDeviceUserCodeInvalid = errors.New("theauth: invalid or expired user code")
	// ErrDeviceTooManyAttempts is returned when a subject exceeded the
	// user-code attempt budget.
	ErrDeviceTooManyAttempts = errors.New("theauth: too many user code attempts")
)

RFC 8628 section 3.5 error sentinels.

View Source
var (
	// ErrDeviceEnrollmentInvalid covers unknown, revoked and mismatched devices and
	// join tokens so callers cannot tell which.
	ErrDeviceEnrollmentInvalid = errors.New("theauth: invalid device or join token")
	// ErrDeviceAttestationRequired is returned when DeviceTokensConfig.Attestation.Required is set
	// and the device sent no evidence. The TypeScript code for it is attestation_required.
	ErrDeviceAttestationRequired = errors.New("theauth: device attestation evidence is required")
	// ErrDeviceAttestationFailed is returned when the attestation verifier refused the evidence or
	// failed. It is wrapped in a *DeviceAttestationError that carries the refusal reason. The
	// TypeScript code for it is attestation_failed.
	ErrDeviceAttestationFailed = errors.New("theauth: device attestation failed")
	// ErrDeviceConflict is returned when a SPIFFE ID is already registered.
	ErrDeviceConflict = errors.New("theauth: device SPIFFE ID already registered")
	// ErrDeviceRevoked is returned when suspending or resuming a revoked device. Revocation is
	// permanent.
	ErrDeviceRevoked = errors.New("theauth: device is revoked")
	// ErrDevicesDisabled is returned when device tokens are not configured or
	// the storage cannot hold devices.
	ErrDevicesDisabled = errors.New("theauth: device tokens not enabled")
	// ErrOIDCDisabled is returned when the OpenID Provider is not configured.
	ErrOIDCDisabled = errors.New("theauth: OpenID Provider not enabled")
)

Device identity sentinels.

View Source
var (
	// ErrRegistrationTokenInvalid covers unknown, expired, revoked and
	// exhausted tokens so callers cannot tell which.
	ErrRegistrationTokenInvalid = errors.New("theauth: invalid registration token")
	// ErrRegistrationTokenScope is returned when the registration request asks
	// for more than the token allows.
	ErrRegistrationTokenScope = errors.New("theauth: registration request exceeds token scope")
	// ErrRegistrationTokensDisabled is returned when the storage does not
	// implement RegistrationTokenStorage.
	ErrRegistrationTokensDisabled = errors.New("theauth: registration tokens not supported by storage")
)

Registration token sentinels.

View Source
var (
	ErrPasskeyUnknown              = errors.New("theauth: passkey is not known to this server")
	ErrConditionalCreateDisabled   = errors.New("theauth: conditional passkey creation is not enabled")
	ErrConditionalCreateNotAllowed = errors.New("theauth: conditional passkey creation is not allowed for this session")
)

Passkey lifecycle errors.

View Source
var (
	// ErrCredentialRevoked is returned by a CredentialChecker when the
	// upstream credential a session is tied to is revoked, expired or gone.
	ErrCredentialRevoked = errors.New("theauth: upstream credential revoked")

	// ErrSessionLinkInvalid covers every way a session link fails to
	// exchange: unknown, expired, already used, or credential revoked.
	ErrSessionLinkInvalid = errors.New("theauth: invalid or expired session link")
)
View Source
var (
	// ErrSSODomainExists is returned by storage when the connection already lists the domain.
	ErrSSODomainExists = errors.New("theauth: domain is already listed on this connection")
	// ErrSSODomainTaken means another connection holds the verified claim on the domain.
	ErrSSODomainTaken = errors.New("theauth: domain is verified by another connection")
	// ErrSSODomainUnverified refuses a SAML sign-in outside the connection's verified domains.
	ErrSSODomainUnverified = errors.New("theauth: email domain is not verified for this connection")
)

SSO domain errors shared by the stores, the SAML service provider and the root package.

View Source
var ErrAccountStateDisabled = errors.New("theauth: Config.AccountState is not enabled")

ErrAccountStateDisabled is returned by the forced-password-change and disable APIs when Config.AccountState is false.

View Source
var ErrAgentPolicyDenied = errors.New("theauth: access_denied")

ErrAgentPolicyDenied is wrapped by every mint refusal caused by agent policy (an explicit deny, a scope no allow statement covers, or an escalation). It maps to the OAuth error access_denied. The wrapping message names the action but never the policy text.

View Source
var ErrAuditChainUnsupported = errors.New("audit chain verification is not supported by this storage backend")

ErrAuditChainUnsupported is returned alongside an unsupported AuditChainResult when verification is requested on a backend without a chain.

View Source
var ErrConnectedAppNotFound = errors.New("theauth: connected app not found")

ErrConnectedAppNotFound is returned when the user has no grant for the client.

View Source
var ErrEmailChangeAddressTaken = errors.New("theauth: email address is already in use")

ErrEmailChangeAddressTaken is returned by storage when the unique email constraint refuses the target address.

View Source
var ErrOAuthServerBusy = errors.New("theauth: temporarily_unavailable")

ErrOAuthServerBusy is returned when the authorization server sheds load because too many client-secret verifications are already running. Handlers map it to HTTP 503 with error=temporarily_unavailable.

Functions

func MergeAuthMethods added in v2.11.0

func MergeAuthMethods(existing []string, add ...string) []string

MergeAuthMethods returns existing followed by the entries of add that are not yet present, normalized to lower case with blanks dropped. It never reorders existing entries.

func WithAuthMethods added in v2.11.0

func WithAuthMethods(ctx context.Context, methods ...string) context.Context

WithAuthMethods returns a context that records the RFC 8176 methods and an AuthTime of now on the session it creates. Contexts without it create sessions with no record.

func WithAuthRecord added in v2.11.0

func WithAuthRecord(ctx context.Context, at time.Time, methods ...string) context.Context

WithAuthRecord is WithAuthMethods with an explicit AuthTime, used when a session is replaced and must keep the original authentication time.

func WithSelfActor added in v2.14.0

func WithSelfActor(ctx context.Context, userID ULID) context.Context

WithSelfActor records that the library verified the request is the user's own although it holds no session, for example by a mailed reset token. Security notices then include its facts.

Types

type AccountState added in v2.10.0

type AccountState struct {
	// MustChangePassword blocks sign-in until the password is changed or reset.
	MustChangePassword bool
	// DisabledAt, when set, blocks sign-in and has revoked every session.
	DisabledAt *time.Time
}

AccountState holds per-user lifecycle flags kept outside the user row so adding them never touches the user queries of an adapter.

type ActorClaim

type ActorClaim struct {
	Sub string      `json:"sub"`
	Act *ActorClaim `json:"act,omitempty"`
}

ActorClaim mirrors the RFC 8693 section 4.1 actor structure. The sub field names the immediate actor; act recurses outward through the chain so the outermost subject (the user who originally granted authority) is implicit in the surrounding JWT's sub.

type Agent

type Agent struct {
	ID             ULID       `json:"id"`
	OwnerUserID    *ULID      `json:"ownerUserId,omitempty"`
	OrganizationID *ULID      `json:"organizationId,omitempty"`
	Name           string     `json:"name"`
	Description    string     `json:"description,omitempty"`
	Status         string     `json:"status"`
	ClientID       string     `json:"clientId"`
	Scope          []string   `json:"scope,omitempty"`
	CreatedAt      time.Time  `json:"createdAt"`
	LastActiveAt   *time.Time `json:"lastActiveAt,omitempty"`
	// ExpiresAt is the optional moment after which the agent is treated as inactive. Nil means the
	// agent never expires. An expired agent cannot authenticate, mint tokens, lend permissions in a
	// delegation chain, or introspect as active.
	ExpiresAt *time.Time `json:"expiresAt,omitempty"`
}

Agent is the persistent record for an agent identity.

func (Agent) AgentExpired added in v2.12.0

func (a Agent) AgentExpired(now time.Time) bool

AgentExpired reports whether the agent has an expiry that is at or before now.

type AgentCredential

type AgentCredential struct {
	ID         ULID       `json:"id"`
	AgentID    ULID       `json:"agentId"`
	Kind       string     `json:"kind"`
	ValueEnc   []byte     `json:"-"`
	CreatedAt  time.Time  `json:"createdAt"`
	ExpiresAt  *time.Time `json:"expiresAt,omitempty"`
	LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
	RevokedAt  *time.Time `json:"revokedAt,omitempty"`
}

AgentCredential is one stored secret material row for an agent. For kind = "secret" the ValueEnc field carries the Argon2id PHC hash of the shared secret (cast to bytes); kinds "x509" and "jwk" are reserved for future phases.

type AgentMintRequest added in v2.11.0

type AgentMintRequest struct {
	// Grant is one of the AgentMint* constants.
	Grant string
	// Resource is the audience the token is minted for.
	Resource string
	// Scopes are the scopes the mint is about to grant, already narrowed by
	// the registered scope set, resource catalog and delegation.
	Scopes []string
	// Explicit is true when the caller asked for these scopes by name. An
	// explicit scope that policy denies fails the mint. A defaulted scope that
	// policy denies is dropped instead.
	Explicit bool
	// Ceiling, when non-nil, is the most the credential may ever carry (the
	// agent's registered scopes). The gate never lets policy widen past it:
	// explicit scopes outside it are invalid_scope, defaulted ones are cut.
	// Set only where the grant has no ceiling of its own (jwt-bearer).
	Ceiling []string
}

AgentMintRequest asks the agent gate to vet one token mint.

type AgentMintResult added in v2.11.0

type AgentMintResult struct {
	Scopes []string
	// Dropped lists defaulted scopes that policy removed.
	Dropped []string
	// PolicyIDs lists the ids of the attached policies, sorted. Empty when no
	// policy applied.
	PolicyIDs []string
	// PolicyHash is a hex SHA-256 over the canonical policy documents, so a
	// decision can be tied to the exact text in force. Empty when no policy
	// applied.
	PolicyHash string
}

AgentMintResult is the gate's verdict: the scopes that survive and the identifiers of the policies that were consulted.

type AgentOwner

type AgentOwner struct {
	UserID         *ULID
	OrganizationID *ULID
}

AgentOwner identifies who owns an agent. Exactly one of the pointer fields MUST be non-nil. A UserID-owned agent is a personal agent; an OrganizationID-owned agent is a service account.

type AgentPolicyDeniedError added in v2.11.0

type AgentPolicyDeniedError struct {
	Action   string
	Resource string
	// PolicyID and StatementID identify the matching deny for audit only.
	PolicyID    string
	StatementID string
	Reason      string
}

AgentPolicyDeniedError carries the denied action for audit. Its Error text is safe for a client: it names the action, not the policy.

func (*AgentPolicyDeniedError) Error added in v2.11.0

func (e *AgentPolicyDeniedError) Error() string

func (*AgentPolicyDeniedError) Is added in v2.11.0

func (e *AgentPolicyDeniedError) Is(target error) bool

Is makes errors.Is(err, ErrAgentPolicyDenied) true.

type AgentRateLimitedError added in v2.11.0

type AgentRateLimitedError struct {
	RetryAfter time.Duration
}

AgentRateLimitedError is returned when an agent has used up its mint budget.

func (*AgentRateLimitedError) Error added in v2.11.0

func (e *AgentRateLimitedError) Error() string

type AgentSecret

type AgentSecret struct {
	AgentID      ULID       `json:"agentId"`
	CredentialID ULID       `json:"credentialId"`
	ClientID     string     `json:"clientId"`
	Secret       string     `json:"secret"`
	ExpiresAt    *time.Time `json:"expiresAt,omitempty"`
}

AgentSecret is the one-time return value from CreateAgent or RotateAgentSecret. The plaintext Secret is shown to the caller exactly once; only the Argon2id hash is persisted.

type AuditChainBreak added in v2.11.0

type AuditChainBreak struct {
	ChainKey string `json:"chainKey"`
	RowID    string `json:"rowId"`
	Seq      int64  `json:"seq"`
	// Reason is one of hash_mismatch, prev_hash_mismatch, seq_gap,
	// pseudonym_mismatch (a raw id column was edited after the row was written).
	// On postgres and mysql, hash_mismatch also covers a native jsonb/inet or
	// foreign key column that disagrees with the hashed text.
	Reason string `json:"reason"`
}

AuditChainBreak describes the first row at which an audit chain fails to verify.

type AuditChainResult added in v2.11.0

type AuditChainResult struct {
	Supported bool `json:"supported"`
	OK        bool `json:"ok"`
	// Checked is the number of chained rows examined.
	Checked int `json:"checked"`
	// Unchained is the number of rows written before the chain existed.
	Unchained int `json:"unchained"`
	// Erased is the number of checked rows whose raw actor ids were erased
	// (GDPR). They still verify through their stored pseudonym.
	Erased int `json:"erased"`
	// FirstBreak is set when a supported chain fails to verify.
	FirstBreak *AuditChainBreak `json:"firstBreak,omitempty"`
}

AuditChainResult is the outcome of verifying an audit store's hash chain.

Supported is false for backends that keep no chain (memory, postgres, mysql). In that case OK is also false and nothing was checked: callers must treat the result as "not tamper-evident", never as a pass.

type AuditEvent

type AuditEvent struct {
	ID             ULID           `json:"id"`
	OrganizationID *ULID          `json:"organizationId,omitempty"`
	ActorUserID    *ULID          `json:"actorUserId,omitempty"`
	ActorSessionID *ULID          `json:"actorSessionId,omitempty"`
	Action         string         `json:"action"`
	TargetType     string         `json:"targetType,omitempty"`
	TargetID       string         `json:"targetId,omitempty"`
	Metadata       map[string]any `json:"metadata,omitempty"`
	IP             string         `json:"ip,omitempty"`
	UserAgent      string         `json:"userAgent,omitempty"`
	CreatedAt      time.Time      `json:"createdAt"`

	// Event is the shared event name (see internal/audit events and the audit package), empty when
	// the writer did not set one or the action has no shared name (stored as NULL). RecordedAtUs is
	// the microsecond write-order stamp assigned by the store inside the append, strictly increasing
	// per chain key, zero on rows from stores or schemas that predate it. Neither field is part of
	// the audit chain hash, and a value passed to InsertAuditEvents for RecordedAtUs is ignored.
	Event        string `json:"event,omitempty"`
	RecordedAtUs int64  `json:"recordedAtUs,omitempty"`

	// Accountability fields. SubjectID is the principal the action was taken
	// on behalf of; ActorID is the agent or service that performed it. Token
	// `sub` semantics are unchanged: these are recorded explicitly instead.
	SubjectID       string         `json:"subjectId,omitempty"`
	ActorID         string         `json:"actorId,omitempty"`
	PolicyVersion   string         `json:"policyVersion,omitempty"`
	ApproverID      string         `json:"approverId,omitempty"`
	DelegationChain []string       `json:"delegationChain,omitempty"`
	InputProvenance map[string]any `json:"inputProvenance,omitempty"`

	// Hash chain output, set by stores that chain (sqlite, postgres, mysql). ChainSeq counts
	// up from 1 per chain key (the organization id, or empty). Zero Hash
	// means the row is not chained.
	ChainSeq uint64 `json:"chainSeq,omitempty"`
	PrevHash string `json:"prevHash,omitempty"`
	Hash     string `json:"hash,omitempty"`
}

AuditEvent is one append-only row in audit_events. Metadata is arbitrary jsonb; the default redactor masks secret-flavored keys at any depth before the value reaches storage.

func (AuditEvent) HasAccountability added in v2.11.0

func (e AuditEvent) HasAccountability() bool

HasAccountability reports whether any accountability field is set.

func (AuditEvent) MetadataWithAccountability added in v2.11.0

func (e AuditEvent) MetadataWithAccountability() map[string]any

MetadataWithAccountability returns Metadata with the accountability fields folded in under AccountabilityMetadataKey. The input map is not modified. Stores without native columns persist this value so the fields are not lost.

type AuditQuery

type AuditQuery struct {
	OrganizationID *ULID
	ActorUserID    *ULID
	Action         string
	TargetType     string
	TargetID       string
	Since          *time.Time
	Until          *time.Time
	Event          string
	// Provenance keeps rows that recorded a given input source. Needs a backend that declares
	// AuditProvenanceSupported() true, otherwise the query fails with ErrAuditProvenanceUnsupported.
	Provenance *ProvenanceFilter
	Order      string
	Limit      int
	After      string
}

AuditQuery filters and paginates audit_events reads. Zero-valued fields are ignored. Limit is capped at 200 and defaults to 50; After is the opaque cursor returned by the previous page.

Event keeps only rows whose event equals it. Order is AuditOrderDesc (the default, newest write first) or AuditOrderAsc, and applies to stores that declare write order support. A cursor is only valid for the order that produced it. Cursors from before write order existed (no "c1." prefix) keep working for descending reads.

type AuthRecord added in v2.11.0

type AuthRecord struct {
	Methods []string
	// At is the AuthTime to record; zero means the moment of issue.
	At time.Time
}

AuthRecord is the authentication record a sign-in flow asks the session service to store on the session it is about to mint.

func AuthRecordFrom added in v2.11.0

func AuthRecordFrom(ctx context.Context) AuthRecord

AuthRecordFrom returns the record attached by WithAuthRecord.

type AuthorizationCode

type AuthorizationCode struct {
	Code                string
	ClientID            string
	UserID              ULID
	OrganizationID      *ULID
	RedirectURI         string
	Scope               []string
	Resource            string
	CodeChallenge       string
	CodeChallengeMethod string
	Nonce               string
	// AuthorizationDetails is the RFC 9396 authorization_details array the
	// user approved, as JSON. Nil when the request carried none.
	AuthorizationDetails []byte
	// AuthTime, ACR and AMR describe how and when the user authenticated
	// for this grant (OIDC Core auth_time, acr, amr). AuthTime is the zero
	// time and ACR and AMR are empty when the session carried no such data.
	AuthTime  time.Time
	ACR       string
	AMR       []string
	ExpiresAt time.Time
	CreatedAt time.Time
}

AuthorizationCode is a single-use 60-second TTL record bound to a client, user, redirect URI, scope, resource (RFC 8707), and PKCE challenge.

type BackchannelRequest

type BackchannelRequest struct {
	// AuthReqID is the opaque handle returned to the client on
	// POST /oauth/bc-authorize. 256-bit, base64url-encoded.
	AuthReqID string

	// ClientID is the registered OAuth client that initiated the request.
	ClientID string

	// UserID is the resolved subject (operator sets this via
	// ApproveBackchannelAuth; nil until approved or when derived from
	// login_hint resolution at request time). Stored so the approve path
	// can verify that the correct user acts.
	UserID *ULID

	// LoginHint, LoginHintToken, IDTokenHint carry the raw hint values
	// submitted by the client. Operators use these in their AD notification
	// to locate the correct user.
	LoginHint      string
	LoginHintToken string
	IDTokenHint    string

	// Scope is the requested scope list.
	Scope []string

	// BindingMessage is the optional short human-readable string shown on
	// the Authentication Device.
	BindingMessage string

	// ClientNotificationToken is the bearer token the AS uses when calling
	// the client's notification endpoint (Ping mode only). Stored opaque
	// (the AS never inspects it); empty for Poll mode requests.
	ClientNotificationToken string

	// Status is the current lifecycle state: pending / approved / denied.
	Status string

	// AccessToken, RefreshToken, IDToken are provisioned by
	// ApproveBackchannelAuth and returned on the next successful poll.
	// Stored encrypted at rest (opaque bytes).
	AccessToken  string
	RefreshToken string
	IDToken      string

	// PollInterval is the minimum seconds between token polls. The AS
	// doubles this on slow_down responses.
	PollInterval int

	// LastPollAt tracks the timestamp of the most recent token poll so
	// the slow_down check can be enforced.
	LastPollAt *time.Time

	// ExpiresAt is the hard deadline for the auth_req_id. Polling after
	// this returns expired_token.
	ExpiresAt time.Time

	CreatedAt time.Time
}

BackchannelRequest is the persistent record for one CIBA flow.

type ClientOwner

type ClientOwner struct {
	UserID         *ULID
	OrganizationID *ULID
	AgentID        *ULID
}

ClientOwner identifies who owns an OAuth client registration. Exactly one pointer field is non-nil. AgentID is reserved for phase 3; phase 1 + 2 clients are always owned by a user, an organization, or are anonymous DCR registrations (Owner is the zero value and AnonymousRegistered is true on the OAuthClient row).

type ConnectedApp added in v2.14.0

type ConnectedApp struct {
	ClientID   string `json:"clientId"`
	ClientName string `json:"clientName"`
	// ClientURI and LogoURI are client supplied. Only http and https values are passed through.
	ClientURI string `json:"clientUri,omitempty"`
	LogoURI   string `json:"logoUri,omitempty"`
	Source    string `json:"source"`
	// Verified is true for a CIMD client whose metadata document was resolved.
	Verified          bool      `json:"verified"`
	Scopes            []string  `json:"scopes"`
	Resources         []string  `json:"resources"`
	FirstAuthorizedAt time.Time `json:"firstAuthorizedAt"`
	LastIssuedAt      time.Time `json:"lastIssuedAt"`
	ExpiresAt         time.Time `json:"expiresAt"`
}

ConnectedApp is one OAuth client holding a live refresh token for a user.

type ConnectedAppList added in v2.14.0

type ConnectedAppList struct {
	Apps []ConnectedApp `json:"apps"`
	// Truncated is true when the user has more apps than the configured cap.
	Truncated bool `json:"truncated"`
}

ConnectedAppList is a user's connected apps, most recently used first.

type ConnectedAppRevokeResult added in v2.14.0

type ConnectedAppRevokeResult struct {
	ClientID             string    `json:"clientId"`
	RevokedAt            time.Time `json:"revokedAt"`
	AccessTokens         string    `json:"accessTokens"`
	RefreshTokensRevoked int       `json:"refreshTokensRevoked"`
	CodesDeleted         int       `json:"codesDeleted"`
}

ConnectedAppRevokeResult reports what revoking a connected app removed.

type CreateAgentInput

type CreateAgentInput struct {
	Owner       AgentOwner
	Name        string
	Description string
	// Scope is the set of scopes the agent may request via client credentials
	// or token exchange. Must be a subset of the resource's supported scopes
	// at mint time; the AS enforces this at every grant.
	Scope []string
	// ExpiresAt optionally bounds the agent's lifetime. It must be in the future and no more than
	// MaxAgentLifetime ahead. Nil means the agent does not expire.
	ExpiresAt *time.Time
}

CreateAgentInput is the input bundle for CreateAgent.

type DelegationGrant

type DelegationGrant struct {
	ID                 ULID       `json:"id"`
	UserID             ULID       `json:"userId"`
	AgentID            ULID       `json:"agentId"`
	OrganizationID     *ULID      `json:"organizationId,omitempty"`
	Scope              []string   `json:"scope"`
	Resource           string     `json:"resource"`
	MaxDurationSeconds int        `json:"maxDurationSeconds"`
	CreatedAt          time.Time  `json:"createdAt"`
	ExpiresAt          *time.Time `json:"expiresAt,omitempty"`
	RevokedAt          *time.Time `json:"revokedAt,omitempty"`
	RevocationNote     string     `json:"revocationNote,omitempty"`
}

DelegationGrant records "user U delegates scope S on resource R to agent A for at most max_duration_seconds, optionally bounded by expires_at". Token exchange consults this row at every mint; revocation flips RevokedAt and introspection on every resource request makes the change visible inside IntrospectionCacheTTL.

type Device added in v2.10.0

type Device struct {
	ID ULID
	// OrganizationID scopes the device to one organization. Nil when it was
	// enrolled through the programmatic API without one.
	OrganizationID *ULID
	Name           string
	// SPIFFEID is the workload identity used as the access token subject.
	// Empty when the operator did not assign one.
	SPIFFEID string
	// PublicKeyJWK is the device's public key as a JWK document.
	PublicKeyJWK []byte
	// KeyThumbprint is the RFC 7638 SHA-256 thumbprint of PublicKeyJWK.
	KeyThumbprint string
	// Attestation records how the device proved its identity at enrollment.
	Attestation string
	// AttestationClaims are the facts a hardware attestation verifier proved at enrollment
	// (Android Key Attestation, Apple App Attest, TPM 2.0 quote), such as securityLevel,
	// verifiedBootState or appId. Nil when the device enrolled without hardware evidence.
	// Policy reads them through iot/attest.FactsFromClaims. They are written once at enrollment.
	AttestationClaims map[string]any
	// AppAttestCounter is the highest Apple App Attest assertion counter accepted for the device key.
	// It only grows, through DeviceAppAttestStorage.AdvanceAppAttestCounter (one conditional update).
	AppAttestCounter uint32
	// Scopes caps what the device's tokens may carry.
	Scopes     []string
	Status     string
	CreatedAt  time.Time
	LastSeenAt *time.Time
	RevokedAt  *time.Time
}

Device is a registered constrained device. It authenticates to the token endpoint with an RFC 7523 assertion signed by the key in PublicKeyJWK.

func (Device) Active added in v2.10.0

func (d Device) Active() bool

Active reports whether the device may still obtain tokens.

func (Device) Subject added in v2.10.0

func (d Device) Subject() string

Subject is the access token sub for the device: the SPIFFE ID when set, otherwise device:<id>.

type DeviceAuthorization added in v2.8.0

type DeviceAuthorization struct {
	ID             ULID
	DeviceCodeHash []byte
	UserCodeHash   []byte
	ClientID       string
	Scope          []string
	// Resource is the RFC 8707 audience the tokens will be minted for. May
	// be empty, in which case the AS default applies at redemption.
	Resource string
	Status   string
	// UserID is set when the user approves or denies.
	UserID *ULID
	// IntervalSeconds is the current minimum polling interval. It grows by
	// five seconds each time the client is told slow_down (RFC 8628 3.5).
	IntervalSeconds int
	LastPollAt      *time.Time
	CreatedAt       time.Time
	ExpiresAt       time.Time
	DecidedAt       *time.Time
}

DeviceAuthorization is the persistent record of one device flow. Neither code is stored in clear: DeviceCodeHash and UserCodeHash are keyed hashes (HMAC-SHA256 under a server secret), so a database leak does not reveal codes that are still live.

type DeviceJoinToken added in v2.10.0

type DeviceJoinToken struct {
	ID             ULID
	TokenHash      []byte
	Prefix         string
	OrganizationID *ULID
	Name           string
	SPIFFEID       string
	Scopes         []string
	CreatedBy      *ULID
	CreatedAt      time.Time
	ExpiresAt      time.Time
	// MaxUses is how many devices the token may enroll. Zero means one (rows written before
	// bulk tokens existed).
	MaxUses int
	// Uses is how many devices the token has enrolled so far.
	Uses int
	// RedeemedAt is set when the last use was spent. DeviceID is set only on a single use token,
	// to the device it enrolled.
	RedeemedAt *time.Time
	DeviceID   *ULID
	RevokedAt  *time.Time
}

DeviceJoinToken is an enrollment secret minted by an admin. It fixes the identity the enrolling device receives, so the device never chooses its own name, SPIFFE ID or scopes. Stored only as a SHA-256 digest. A token is single use unless MaxUses says otherwise (a bulk token for a factory line).

func (DeviceJoinToken) Active added in v2.10.0

func (t DeviceJoinToken) Active(now time.Time) bool

Active reports whether the token can still enroll a device at now.

func (DeviceJoinToken) EffectiveMaxUses added in v2.14.0

func (t DeviceJoinToken) EffectiveMaxUses() int

EffectiveMaxUses is MaxUses with the zero value read as one.

type EmailChange added in v2.14.0

type EmailChange struct {
	ID     ULID
	UserID ULID
	// SessionID is the session that asked for a confirm record; the link dies with it.
	SessionID ULID
	Kind      string
	TokenHash []byte
	// OldEmail is the address before the change; an undo link restores it.
	OldEmail string
	// OldEmailVerifiedAt is the verified state of OldEmail before the change; an undo restores it.
	OldEmailVerifiedAt *time.Time
	NewEmail           string
	// RequestedAt, on an undo record, is when the change was asked for: the undo removes
	// credentials added since.
	RequestedAt *time.Time
	CreatedAt   time.Time
	ExpiresAt   time.Time
	UsedAt      *time.Time
}

EmailChange is the stored state behind one confirm or undo link. Only the token hash is kept.

type GrantDelegationInput

type GrantDelegationInput struct {
	UserID             ULID
	AgentID            ULID
	OrganizationID     *ULID
	Scope              []string
	Resource           string
	MaxDurationSeconds int
	ExpiresAt          *time.Time
}

GrantDelegationInput is the input bundle for GrantDelegation. UserID and AgentID are mandatory; Scope and Resource are mandatory and validated against the AS's configured ProtectedResources.

type Group

type Group struct {
	ID             ULID      `json:"id"`
	OrganizationID ULID      `json:"organizationId"`
	DisplayName    string    `json:"displayName"`
	ExternalID     string    `json:"externalId,omitempty"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`
}

Group is a SCIM-first concept. v0.7 stores them flat (no nesting), scoped to one organization. Application semantics (mapping a group to a role) land in v0.8 RBAC.

type IdentityConflictError

type IdentityConflictError struct {
	ConflictingUserID ULID
}

IdentityConflictError is returned (wrapped in ErrIdentityConflict) by LinkOAuthToCurrentUser when the OAuth account is already owned by a different user. ConflictingUserID carries that user's ID so consumer UIs can present a merge-confirmation flow.

func (*IdentityConflictError) Error

func (e *IdentityConflictError) Error() string

Error implements the error interface.

func (*IdentityConflictError) Unwrap

func (e *IdentityConflictError) Unwrap() error

Unwrap lets errors.Is(err, ErrIdentityConflict) traverse through.

type JWKSKey

type JWKSKey struct {
	KID        string
	Alg        string // "EdDSA"
	Use        string // "sig"
	PublicJWK  []byte
	PrivateEnc []byte
	State      string // "next" | "current" | "previous" | "retired"
	CreatedAt  time.Time
	PromotedAt *time.Time
	RetiredAt  *time.Time
}

JWKSKey is one signing key in the AS's JWKS state machine. State transitions: next -> current -> previous -> retired. The private key bytes are AES-GCM encrypted at rest using Config.EncryptionKey.

type KnownDevice added in v2.14.0

type KnownDevice struct {
	FirstSeenAt time.Time
	LastSeenAt  time.Time
}

KnownDevice is one recognized device of a user as listed for data export. It carries no hash.

type MagicLink struct {
	ID        ULID       `json:"id"`
	Email     string     `json:"email"`
	TokenHash []byte     `json:"-"`
	ExpiresAt time.Time  `json:"expiresAt"`
	UsedAt    *time.Time `json:"usedAt,omitempty"`
	CreatedAt time.Time  `json:"createdAt"`
}

type OAuthAccount

type OAuthAccount struct {
	ID              ULID       `json:"id"`
	UserID          ULID       `json:"userId"`
	Provider        string     `json:"provider"`
	ProviderUserID  string     `json:"providerUserId"`
	AccessTokenEnc  []byte     `json:"-"`
	RefreshTokenEnc []byte     `json:"-"`
	ExpiresAt       *time.Time `json:"expiresAt,omitempty"`
	Scope           string     `json:"scope"`
	CreatedAt       time.Time  `json:"createdAt"`
	UpdatedAt       time.Time  `json:"updatedAt"`
}

OAuthAccount records the linkage between one of our Users and a remote OAuth provider identity (e.g. user X authenticates via GitHub). The (provider, provider_user_id) pair is unique; re-running the OAuth flow for the same provider account upserts this row rather than creating a duplicate. Tokens are encrypted at rest via crypto.Encrypt and are never serialized over JSON.

type OAuthClient

type OAuthClient struct {
	ID                      ULID     `json:"-"`
	ClientID                string   `json:"client_id"`
	ClientSecretHash        []byte   `json:"-"`
	ClientName              string   `json:"client_name"`
	RedirectURIs            []string `json:"redirect_uris"`
	GrantTypes              []string `json:"grant_types"`
	ResponseTypes           []string `json:"response_types"`
	Scope                   string   `json:"scope"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
	ApplicationType         string   `json:"application_type"`
	Contacts                []string `json:"contacts,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	ClientURI               string   `json:"client_uri,omitempty"`
	PolicyURI               string   `json:"policy_uri,omitempty"`
	TosURI                  string   `json:"tos_uri,omitempty"`
	JwksURI                 string   `json:"jwks_uri,omitempty"`
	Jwks                    []byte   `json:"jwks,omitempty"`
	SoftwareID              string   `json:"software_id,omitempty"`
	SoftwareVersion         string   `json:"software_version,omitempty"`
	// AccessTokenFormat selects how access tokens issued to this client are
	// encoded: AccessTokenFormatJWT (RFC 9068, default) or
	// AccessTokenFormatOpaque (random reference token, introspection only).
	// Empty inherits the server default.
	AccessTokenFormat string `json:"access_token_format,omitempty"`
	// AccessTokenSignedResponseAlg is the JWS alg used to sign this client's
	// JWT access tokens (EdDSA, ES256 or RS256). Empty inherits the server
	// default. Ignored for opaque tokens.
	AccessTokenSignedResponseAlg string `json:"access_token_signed_response_alg,omitempty"`
	// AuthorizationDetailsTypes lists the RFC 9396 authorization_details
	// types the client may request. Empty allows every type the server
	// supports.
	AuthorizationDetailsTypes []string `json:"authorization_details_types,omitempty"`

	// OIDC client metadata. All four are stored together in one JSON column.
	// SubjectType is SubjectTypePublic or SubjectTypePairwise; empty inherits
	// the server default.
	SubjectType string `json:"subject_type,omitempty"`
	// PostLogoutRedirectURIs lists where RP-initiated logout may send the
	// user agent afterwards (exact match).
	PostLogoutRedirectURIs []string `json:"post_logout_redirect_uris,omitempty"`
	// BackchannelLogoutURI receives logout tokens (OpenID Connect
	// Back-Channel Logout 1.0). Empty opts the client out.
	BackchannelLogoutURI string `json:"backchannel_logout_uri,omitempty"`
	// BackchannelLogoutSessionRequired asks for the sid claim in logout tokens.
	BackchannelLogoutSessionRequired bool `json:"backchannel_logout_session_required,omitempty"`

	// RequirePushedAuthorizationRequests makes PAR the only way this client may start an
	// authorization (RFC 9126 section 6).
	RequirePushedAuthorizationRequests bool `json:"require_pushed_authorization_requests,omitempty"`

	Owner                  ClientOwner `json:"-"`
	AnonymousRegistered    bool        `json:"-"`
	RegistrationAccessHash []byte      `json:"-"`
	CreatedAt              time.Time   `json:"client_id_issued_at,omitempty"`
	UpdatedAt              time.Time   `json:"-"`
}

OAuthClient is one registration row backing the OAuth 2.1 authorization server. Persisted by RFC 7591 dynamic client registration (POST /oauth/register) and by future admin/account flows. Fields mirror RFC 7591 client metadata.

func (OAuthClient) OIDCMetadataJSON added in v2.10.0

func (c OAuthClient) OIDCMetadataJSON() []byte

OIDCMetadataJSON encodes the OIDC client metadata for storage. It never returns nil, so NOT NULL columns accept the result.

func (*OAuthClient) SetOIDCMetadataJSON added in v2.10.0

func (c *OAuthClient) SetOIDCMetadataJSON(raw []byte)

SetOIDCMetadataJSON decodes the stored OIDC client metadata. Empty or malformed input leaves the fields at their zero values.

type OAuthConflictRedirectError

type OAuthConflictRedirectError struct {
	URL string
}

OAuthConflictRedirectError is returned (not wrapped) by oauth.Service.Callback when a sign-in email matches an existing user who registered via a different provider AND an OnOAuthConflict lifecycle hook is configured. The HTTP layer detects it and issues a 302 to URL instead of a generic 400.

func (*OAuthConflictRedirectError) Error

type OAuthGrantEvidence added in v2.14.0

type OAuthGrantEvidence struct {
	ClientID string
	// Pending marks a code or refresh token that can still be used and that revoking removes.
	Pending bool
	// IssuedAt dates other evidence: a spent or revoked refresh token whose access token may live,
	// or a device or CIBA request. Zero when Pending.
	IssuedAt time.Time
}

OAuthGrantEvidence is one stored trace of a user's grant to a client.

type OAuthGrantRevocation added in v2.14.0

type OAuthGrantRevocation struct {
	UserID    ULID
	ClientID  string
	RevokedAt time.Time
	// CompletedAt is the RevokedAt of the last revocation whose sweep finished; zero if none did.
	CompletedAt time.Time
	ExpiresAt   time.Time
}

OAuthGrantRevocation is the watermark of one (user, client): evidence issued at or before RevokedAt (plus the configured skew) is refused. An empty ClientID covers every client of the user. ExpiresAt is when the row may be swept.

type OAuthGrantRow added in v2.14.0

type OAuthGrantRow struct {
	ClientID string
	FamilyID ULID
	Scope    []string
	Resource string
	// FirstIssuedAt is the oldest row of the family; IssuedAt and ExpiresAt belong to the live token.
	FirstIssuedAt time.Time
	IssuedAt      time.Time
	ExpiresAt     time.Time
}

OAuthGrantRow is one live rotation family of a user's refresh tokens, the unit ConnectedAppStorage lists. It never carries token hashes or access token ids.

type OAuthTokenRef added in v2.14.0

type OAuthTokenRef struct {
	JTI      string
	IssuedAt time.Time
}

OAuthTokenRef names the access token minted beside one refresh token row.

type OpaqueAccessToken added in v2.8.0

type OpaqueAccessToken struct {
	Hash      []byte
	JTI       string
	ClientID  string
	Claims    []byte
	IssuedAt  time.Time
	ExpiresAt time.Time
	RevokedAt *time.Time
}

OpaqueAccessToken is the server-side record behind a reference (opaque) access token. Only the SHA-256 hash of the token is stored. Claims holds the JSON of the claim set a JWT would have carried, so introspection answers identically for both formats.

type Organization

type Organization struct {
	ID        ULID      `json:"id"`
	Name      string    `json:"name"`
	Slug      string    `json:"slug"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Organization is the top-level multi-tenant container. Slug is a citext unique URL-safe handle (lowercased on write).

type OrganizationMember

type OrganizationMember struct {
	OrganizationID ULID      `json:"organizationId"`
	UserID         ULID      `json:"userId"`
	Role           string    `json:"role"`
	JoinedAt       time.Time `json:"joinedAt"`
}

OrganizationMember binds a user to an organization with a single role. Role values: "owner", "admin", "member". owner can manage SAML and SCIM, admin can manage SCIM only, member is read-only against org metadata.

type PasskeySignals added in v2.14.0

type PasskeySignals struct {
	RPID                     string   `json:"rpId"`
	UserID                   string   `json:"userId"`
	AllAcceptedCredentialIDs []string `json:"allAcceptedCredentialIds"`
	Name                     string   `json:"name"`
	DisplayName              string   `json:"displayName"`
}

PasskeySignals is what the WebAuthn Signal API methods signalAllAcceptedCredentials and signalCurrentUserDetails need for one user. Byte values are unpadded base64url.

type PasswordResetToken

type PasswordResetToken struct {
	ID        ULID       `json:"id"`
	UserID    ULID       `json:"userId"`
	TokenHash []byte     `json:"-"`
	ExpiresAt time.Time  `json:"expiresAt"`
	UsedAt    *time.Time `json:"usedAt,omitempty"`
	CreatedAt time.Time  `json:"createdAt"`
}

PasswordResetToken backs the /auth/email-password/forgot+reset flow. Shape mirrors MagicLink but binds to a known user_id (resets always operate on an existing account), and lives in its own table to keep flows isolated.

type Permission

type Permission struct {
	ID          ULID      `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"createdAt"`
}

Permission is one entry in the closed permission catalog. Names are program identifiers (ASCII, no whitespace) of the shape "domain:verb" or "domain:verb:scope". Seeded permissions live in service_rbac.go.

type ProtectedResource

type ProtectedResource struct {
	Identifier  string
	DisplayName string
	Scopes      []string
}

ProtectedResource describes one resource server protected by this AS. The Identifier appears in the aud claim of issued tokens; it MUST be the URL the resource server advertises in its own /.well-known/oauth-protected-resource document.

type ProvenanceFilter added in v2.14.0

type ProvenanceFilter struct {
	// Kind is user_message, tool_output, retrieved_document or agent.
	Kind string
	// Hash is 64 lowercase hex characters, from the input hasher (audit.InputHasher.Hash).
	Hash string
}

ProvenanceFilter narrows an audit query by input provenance. Both fields narrow the match.

type RecoveryCode

type RecoveryCode struct {
	ID        ULID       `json:"id"`
	UserID    ULID       `json:"userId"`
	CodeHash  []byte     `json:"-"`
	UsedAt    *time.Time `json:"usedAt,omitempty"`
	CreatedAt time.Time  `json:"createdAt"`
}

RecoveryCode is one of N single-use codes generated at TOTP enrollment. CodeHash carries the 16-byte salt prefix followed by sha256(salt || code), produced by crypto.HashRecoveryCode. UsedAt is set the first time a user consumes the code; the same hash cannot be replayed.

type RefreshToken

type RefreshToken struct {
	ID             ULID
	Hash           []byte
	FamilyID       ULID
	ClientID       string
	UserID         *ULID
	AgentID        *ULID
	Scope          []string
	Resource       string
	ParentJTI      string
	IssuedAt       time.Time
	ExpiresAt      time.Time
	RevokedAt      *time.Time
	RevocationNote string

	// DPoPJKT is the RFC 7638 thumbprint of the DPoP key the grant was
	// bound to at issuance. When non-empty, every refresh must present a
	// DPoP proof signed by the same key (RFC 9449 section 8).
	DPoPJKT string
	// AuthCodeHash is the storage key (hex SHA-256) of the authorization
	// code this token family was first issued from. Empty for grants not
	// minted from a code. Used to revoke the family when the code is
	// replayed (RFC 6749 section 4.1.2).
	AuthCodeHash string
	// AuthorizationDetails is the RFC 9396 authorization_details array
	// granted to this family, as JSON. Nil when none were granted.
	AuthorizationDetails []byte
	// AuthTime, ACR and AMR carry the authentication context of the grant
	// the family was first issued from. They are copied verbatim on every
	// rotation: a refresh never advances AuthTime.
	AuthTime time.Time
	ACR      string
	AMR      []string
}

RefreshToken is the opaque, hashed, rotated-on-use refresh artefact backing the refresh_token grant. FamilyID links rotated tokens; presenting an old token after rotation revokes the family per RFC 9700 section 4.14.

type RegisteredClient

type RegisteredClient struct {
	ClientID                string   `json:"client_id"`
	ClientSecret            string   `json:"client_secret,omitempty"`
	ClientIDIssuedAt        int64    `json:"client_id_issued_at"`
	ClientSecretExpiresAt   int64    `json:"client_secret_expires_at,omitempty"`
	RedirectURIs            []string `json:"redirect_uris"`
	GrantTypes              []string `json:"grant_types"`
	ResponseTypes           []string `json:"response_types"`
	Scope                   string   `json:"scope,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
	ApplicationType         string   `json:"application_type"`
	ClientName              string   `json:"client_name,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	PolicyURI               string   `json:"policy_uri,omitempty"`
	TosURI                  string   `json:"tos_uri,omitempty"`
	JwksURI                 string   `json:"jwks_uri,omitempty"`
	SoftwareID              string   `json:"software_id,omitempty"`
	SoftwareVersion         string   `json:"software_version,omitempty"`

	AccessTokenFormat            string   `json:"access_token_format,omitempty"`
	AccessTokenSignedResponseAlg string   `json:"access_token_signed_response_alg,omitempty"`
	AuthorizationDetailsTypes    []string `json:"authorization_details_types,omitempty"`

	SubjectType                      string   `json:"subject_type,omitempty"`
	PostLogoutRedirectURIs           []string `json:"post_logout_redirect_uris,omitempty"`
	BackchannelLogoutURI             string   `json:"backchannel_logout_uri,omitempty"`
	BackchannelLogoutSessionRequired bool     `json:"backchannel_logout_session_required,omitempty"`

	RequirePushedAuthorizationRequests bool `json:"require_pushed_authorization_requests,omitempty"`
}

RegisteredClient is the JSON body returned on a successful registration (RFC 7591 section 3.2.1). The client_secret is returned in plaintext exactly once; the AS stores only the Argon2id hash.

type RegistrationToken added in v2.8.0

type RegistrationToken struct {
	ID ULID
	// TokenHash is sha256 of the token string.
	TokenHash []byte
	// Prefix is the first characters of the token, kept so operators can
	// recognize a token in lists without the secret being recoverable.
	Prefix string
	Label  string
	// OrganizationID scopes the token to one organization's admin view. Nil
	// for tokens created through the programmatic API without an org.
	OrganizationID *ULID
	// Scopes caps the scope a client registered with this token may request.
	// Empty means no scope restriction.
	Scopes []string
	// GrantTypes caps the grant types the registered client may declare.
	// Empty means no restriction.
	GrantTypes []string
	// MaxUses is how many registrations the token allows. 1 makes it one-time.
	MaxUses    int
	Uses       int
	CreatedBy  *ULID
	CreatedAt  time.Time
	ExpiresAt  time.Time
	LastUsedAt *time.Time
	RevokedAt  *time.Time
}

RegistrationToken is an initial access token (RFC 7591 section 1.2) for POST /oauth/register. Tokens are created through the admin API, shown once, and stored only as a SHA-256 digest. The token is 256 random bits, so a plain digest is sufficient at rest.

func (RegistrationToken) Active added in v2.8.0

func (t RegistrationToken) Active(now time.Time) bool

Active reports whether the token can still be redeemed at now.

type Role

type Role struct {
	ID             ULID      `json:"id"`
	OrganizationID *ULID     `json:"organizationId,omitempty"`
	Name           string    `json:"name"`
	Description    string    `json:"description"`
	Permissions    []string  `json:"permissions"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`
}

Role binds a permission set to an organization (or to the global namespace when OrganizationID is nil, i.e. system roles such as super_admin). Permissions is the hydrated permission-name slice and is not persisted on the Role row itself; storage adapters fill it on read via PermissionsByRole.

type SAMLAttributeMap

type SAMLAttributeMap struct {
	Email      string            `json:"email"`
	Name       string            `json:"name,omitempty"`
	GivenName  string            `json:"givenName,omitempty"`
	FamilyName string            `json:"familyName,omitempty"`
	Groups     string            `json:"groups,omitempty"`
	Extra      map[string]string `json:"extra,omitempty"`
}

SAMLAttributeMap projects SAML attribute names to canonical user fields. Stored as jsonb in saml_connections.attribute_map.

func DefaultSAMLAttributeMap

func DefaultSAMLAttributeMap() SAMLAttributeMap

DefaultSAMLAttributeMap returns the WS-Federation claim URIs that Microsoft, Okta, and OneLogin emit by default. A per-connection map can override any of these by writing a non-empty string for the field.

type SAMLConnection

type SAMLConnection struct {
	ID             ULID             `json:"id"`
	OrganizationID ULID             `json:"organizationId"`
	IdPEntityID    string           `json:"idpEntityId"`
	IdPSSOURL      string           `json:"idpSsoUrl"`
	IdPX509Cert    string           `json:"idpX509Cert"`
	SPEntityID     string           `json:"spEntityId"`
	SPACSURL       string           `json:"spAcsUrl"`
	AttributeMap   SAMLAttributeMap `json:"attributeMap"`
	CreatedAt      time.Time        `json:"createdAt"`
	UpdatedAt      time.Time        `json:"updatedAt"`
}

SAMLConnection is one IdP binding for one organization. An organization can hold multiple connections (e.g. two distinct Okta tenants for subsidiaries), each routed by id in the URL.

type SAMLIdentity

type SAMLIdentity struct {
	ID           ULID       `json:"id"`
	ConnectionID ULID       `json:"connectionId"`
	UserID       ULID       `json:"userId"`
	NameID       string     `json:"nameId"`
	NameIDFormat string     `json:"nameIdFormat"`
	LastLoginAt  *time.Time `json:"lastLoginAt,omitempty"`
	CreatedAt    time.Time  `json:"createdAt"`
}

SAMLIdentity links a successful SAML login to a user. Lookup key is (connection_id, name_id); name_id is whatever Subject.NameID.Value the IdP emitted, opaque and stable across sessions for most IdPs.

type SCIMGroupFilter

type SCIMGroupFilter struct {
	DisplayName string
	ExternalID  string
}

SCIMGroupFilter is the equality-only filter accepted on /scim/v2/Groups.

type SCIMToken

type SCIMToken struct {
	ID             ULID       `json:"id"`
	OrganizationID ULID       `json:"organizationId"`
	Name           string     `json:"name"`
	TokenHash      []byte     `json:"-"`
	CreatedAt      time.Time  `json:"createdAt"`
	LastUsedAt     *time.Time `json:"lastUsedAt,omitempty"`
	RevokedAt      *time.Time `json:"revokedAt,omitempty"`
}

SCIMToken is a hashed bearer token bound to one organization. Plaintext is only ever returned from CreateSCIMToken; subsequent reads only ever see the hash. Hash is sha256(token); rationale documented in the v0.7 spec.

type SCIMUserFilter

type SCIMUserFilter struct {
	UserName   string
	ExternalID string
	Email      string
}

SCIMUserFilter is the equality-only filter accepted on /scim/v2/Users. Anything outside this whitelist returns 400 invalidFilter.

type SSODomain added in v2.14.0

type SSODomain struct {
	ID           ULID   `json:"id"`
	ConnectionID ULID   `json:"connectionId"`
	Domain       string `json:"domain"`
	// Token goes into the published TXT value. It is public by design, so it is stored as is.
	Token     string    `json:"token"`
	CreatedAt time.Time `json:"createdAt"`
	// VerifiedAt is nil until DNS ownership is proven, and again after the proof lapses.
	VerifiedAt    *time.Time `json:"verifiedAt,omitempty"`
	LastCheckedAt *time.Time `json:"lastCheckedAt,omitempty"`
	// FailedChecks counts consecutive failed rechecks of a verified domain.
	FailedChecks int `json:"failedChecks"`
	// RecordName and RecordValue are the TXT record to publish. They are derived, never stored.
	RecordName  string `json:"recordName,omitempty"`
	RecordValue string `json:"recordValue,omitempty"`
}

SSODomain is one email domain claimed by a SAML connection.

type Session

type Session struct {
	ID        ULID       `json:"id"`
	UserID    ULID       `json:"userId"`
	TokenHash []byte     `json:"-"` // never serialize raw hash
	UserAgent string     `json:"userAgent"`
	IP        string     `json:"ip"`
	CreatedAt time.Time  `json:"createdAt"`
	ExpiresAt time.Time  `json:"expiresAt"`
	RevokedAt *time.Time `json:"revokedAt,omitempty"`
	// AuthLevel is "full" or "pending_2fa" (v0.5). Sessions issued by code
	// paths predating v0.5 default to "full" so existing rows keep working.
	AuthLevel string `json:"authLevel,omitempty"`
	// ActiveOrganizationID (v0.7) scopes a session to one organization for
	// the duration of the session. Nil in single-tenant deployments and on
	// any session that has not picked an org yet.
	ActiveOrganizationID *ULID `json:"activeOrganizationId,omitempty"`
	// LastSeenAt is the throttled last-activity time used for idle timeout
	// and the "last seen" column of a session list. Zero on rows written by
	// storage without SessionManagementStorage.
	LastSeenAt time.Time `json:"lastSeenAt"`
	// ElevatedUntil marks a step-up re-authentication window; nil when the
	// session was never elevated.
	ElevatedUntil *time.Time `json:"elevatedUntil,omitempty"`
	// CredentialID names the upstream credential (for example an API token
	// id) a session minted from a session link is tied to; empty otherwise.
	CredentialID string `json:"credentialId,omitempty"`
	// AuthMethods lists the RFC 8176 authentication method references the
	// session proved so far, in the order they were proved (for example
	// ["pwd","otp","mfa"]). Nil on sessions created before the record
	// existed or by a storage without SessionAuthStorage; see AMR* constants.
	AuthMethods []string `json:"authMethods,omitempty"`
	// AuthTime is when the user last proved identity with a method in
	// AuthMethods: sign-in time, advanced by every second factor or step-up.
	// The zero time on sessions without an AuthMethods record.
	AuthTime time.Time `json:"authTime,omitempty"`
}

func (Session) Expired

func (s Session) Expired(now time.Time) bool

Expired reports whether the session is no longer usable at the given time.

func (Session) HasAllMethods added in v2.11.0

func (s Session) HasAllMethods(methods ...string) bool

HasAllMethods reports whether the session recorded every one of methods.

func (Session) HasAnyMethod added in v2.11.0

func (s Session) HasAnyMethod(methods ...string) bool

HasAnyMethod reports whether the session recorded at least one of methods.

func (Session) HasMethod added in v2.11.0

func (s Session) HasMethod(m string) bool

HasMethod reports whether the session recorded the authentication method m (case-insensitive). False for sessions without a record.

type SessionFamily added in v2.14.0

type SessionFamily struct {
	ID     ULID
	UserID ULID
	// SessionID is the session minted with the current generation.
	SessionID  ULID
	Generation int64
	// ParentGeneration is the generation whose token derived the current one, -1 for the first.
	ParentGeneration int64
	// RerotatedFrom is the parent generation a lost-response re-rotation already used, -1 for none.
	RerotatedFrom int64
	// VerifierHash is the SHA-256 of the current token's verifier.
	VerifierHash []byte
	Method       string
	AuthMethods  []string
	AuthTime     time.Time
	UserAgent    string
	IP           string
	Label        string
	// CreatedAt is the original sign-in; the absolute lifetime counts from it.
	CreatedAt  time.Time
	RotatedAt  time.Time
	LastUsedAt time.Time
	// UsedAt is set once the current generation was used: its session authenticated a request or
	// its token was presented while the session was alive.
	UsedAt       *time.Time
	IdleTimeout  time.Duration
	ExpiresAt    time.Time
	ForgottenAt  *time.Time
	RevokedAt    *time.Time
	RevokeReason string
}

SessionFamily is the stored state of one remembered device sign-in: which generation of the remember token is current, the session paired with it and the lifetime limits. Only SHA-256 hashes of remember token verifiers are stored.

type SessionFamilyAdvance added in v2.14.0

type SessionFamilyAdvance struct {
	FamilyID         ULID
	FromGeneration   int64
	ParentGeneration int64
	Rerotate         bool
	VerifierHash     []byte
	SessionID        ULID
	UserAgent        string
	IP               string
	At               time.Time
	IdleTimeout      time.Duration
	ExpiresAt        time.Time
}

SessionFamilyAdvance is a conditional rotation: it applies only while the family is at FromGeneration, not revoked or forgotten, and (when Rerotate) RerotatedFrom differs from ParentGeneration.

type SessionFamilyToken added in v2.14.0

type SessionFamilyToken struct {
	FamilyID     ULID
	VerifierHash []byte
	Generation   int64
	CreatedAt    time.Time
}

SessionFamilyToken is one entry of a family's token history, so any earlier token is recognised.

type SessionLink struct {
	ID        ULID   `json:"id"`
	UserID    ULID   `json:"userId"`
	TokenHash []byte `json:"-"`
	// CredentialID ties the resulting session to an upstream credential that
	// is re-checked on every session use. Empty for an unbound link.
	CredentialID string `json:"credentialId,omitempty"`
	// SessionTTL bounds the resulting session; zero means the default TTL.
	SessionTTL time.Duration `json:"sessionTtl,omitempty"`
	CreatedAt  time.Time     `json:"createdAt"`
	ExpiresAt  time.Time     `json:"expiresAt"`
	ConsumedAt *time.Time    `json:"consumedAt,omitempty"`
}

SessionLink is a short-lived, single-use grant that exchanges for a session on behalf of UserID. Only the sha256 of the token is stored.

type SigninReport added in v2.14.0

type SigninReport struct {
	// ID is the notice the link was sent with.
	ID        ULID
	UserID    ULID
	TokenHash []byte
	// DeviceHash is the device the sign-in was recorded for, empty when there was none.
	DeviceHash []byte
	UserAgent  string
	IPPrefix   string
	// CreatedAt is when the reported sign-in completed.
	CreatedAt time.Time
	ExpiresAt time.Time
	UsedAt    *time.Time
}

SigninReport is the stored state behind one "this was not me" link. Only SHA-256 hashes of the link token and of the device id are stored.

type Stats

type Stats struct {
	AuditEmitted    uint64 `json:"auditEmitted"`
	AuditWritten    uint64 `json:"auditWritten"`
	AuditDropped    uint64 `json:"auditDropped"`
	AuditFailed     uint64 `json:"auditFailed"`
	AuditSinkFailed uint64 `json:"auditSinkFailed"`
}

Stats holds runtime counters useful for ops dashboards and tests. Counters are monotonically non-decreasing; reads are atomic snapshots. AuditFailed counts batches whose INSERT returned an error; the writer goroutine logs the error and does not retry (the v1.0 tradeoff documented in AuditSinkFailed counts individual sink Stream errors across all registered sinks; incremented once per failing sink per batch (not per event).

type TOTPSecret

type TOTPSecret struct {
	UserID      ULID       `json:"userId"`
	SecretEnc   []byte     `json:"-"`
	ConfirmedAt *time.Time `json:"confirmedAt,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
}

TOTPSecret stores the AES-GCM encrypted shared secret for one user. The secret is base32 plaintext only at enroll-begin and verify time; on disk it is always ciphertext (nonce prepended, courtesy of crypto.Encrypt). ConfirmedAt is NULL until the user proves possession by entering one valid code in /auth/totp/enroll/finish. Unconfirmed rows are overwritten by a subsequent /enroll/begin (no half-state can survive).

type TargetRef

type TargetRef struct {
	Type string `json:"type,omitempty"`
	ID   string `json:"id,omitempty"`
}

TargetRef points at the resource an audit event acts on. ID is a string (not ULID) because some targets are external identifiers (e.g. SCIM externalId) rather than ULIDs.

type TheAuthError

type TheAuthError struct {
	Code    string
	Message string
	Inner   error
	// RetryAfter, when positive, tells HTTP handlers how long the caller
	// should wait before retrying (sent as a Retry-After header).
	RetryAfter time.Duration
}

TheAuthError is the structured error type returned by v0.2+ service methods. Callers can errors.As-extract it and switch on Code for stable handling, or errors.Is-check against a value of the same Code for shorter paths. on the root package. Re-exported from root errors.go as a type alias.

func NewError

func NewError(code, message string, inner error) *TheAuthError

NewError constructs a TheAuthError with the supplied code, message, and optional wrapped cause.

func (*TheAuthError) Error

func (e *TheAuthError) Error() string

Error returns the canonical string form for log output.

func (*TheAuthError) Is

func (e *TheAuthError) Is(target error) bool

Is reports whether target is a *TheAuthError with the same Code, OR is the Inner cause. Lets callers do errors.Is(err, &TheAuthError{Code: ...}) for code-only comparisons without caring about the message or inner cause.

func (*TheAuthError) Unwrap

func (e *TheAuthError) Unwrap() error

Unwrap exposes the inner error for errors.Is/errors.As traversal.

type TrustedDevice added in v2.10.0

type TrustedDevice struct {
	ID         ULID       `json:"id"`
	UserID     ULID       `json:"userId"`
	TokenHash  []byte     `json:"-"`
	Label      string     `json:"label"`
	UserAgent  string     `json:"-"`
	IP         string     `json:"-"`
	CreatedAt  time.Time  `json:"createdAt"`
	LastUsedAt time.Time  `json:"lastUsedAt"`
	ExpiresAt  time.Time  `json:"expiresAt"`
	RevokedAt  *time.Time `json:"revokedAt,omitempty"`
}

TrustedDevice is a remember-this-device record that lets a password sign-in skip the TOTP prompt. Only the SHA-256 of the cookie token is stored.

type ULID

type ULID = ulid.ULID

ULID is the canonical ID type, generated in app, stored as uuid in Postgres.

func SelfActorFrom added in v2.14.0

func SelfActorFrom(ctx context.Context) (ULID, bool)

SelfActorFrom returns the user recorded by WithSelfActor.

type User

type User struct {
	ID              ULID       `json:"id"`
	Email           string     `json:"email"`
	EmailVerifiedAt *time.Time `json:"emailVerifiedAt,omitempty"`
	Name            string     `json:"name"`
	AvatarURL       string     `json:"avatarUrl"`
	CreatedAt       time.Time  `json:"createdAt"`
	UpdatedAt       time.Time  `json:"updatedAt"`
	// ExternalID (v0.7 SCIM) stores the SCIM client's stable identifier so
	// upsert by externalId works. Empty for users not created via SCIM.
	ExternalID string `json:"externalId,omitempty"`
	// GivenName / FamilyName / DisplayName (v0.7 SCIM) capture the structured
	// name attributes SCIM clients provision; they are best-effort projections
	// alongside Name and may be empty for users created via other flows.
	GivenName   string `json:"givenName,omitempty"`
	FamilyName  string `json:"familyName,omitempty"`
	DisplayName string `json:"displayName,omitempty"`
}

type UserRole

type UserRole struct {
	UserID    ULID      `json:"userId"`
	RoleID    ULID      `json:"roleId"`
	GrantedAt time.Time `json:"grantedAt"`
	GrantedBy *ULID     `json:"grantedBy,omitempty"`
}

UserRole records a grant of one role to one user. GrantedBy is the actor that issued the grant; nil indicates a system grant (e.g. seeded by SeedOrganizationRoles itself).

type WebAuthnCredential

type WebAuthnCredential struct {
	ID           ULID       `json:"id"`
	UserID       ULID       `json:"userId"`
	CredentialID []byte     `json:"credentialId"`
	PublicKey    []byte     `json:"-"`
	SignCount    uint32     `json:"signCount"`
	Transports   []string   `json:"transports"`
	AAGUID       []byte     `json:"aaguid"`
	Name         string     `json:"name"`
	CreatedAt    time.Time  `json:"createdAt"`
	LastUsedAt   *time.Time `json:"lastUsedAt,omitempty"`
	// BackupEligible / BackupState mirror the WebAuthn BE / BS authenticator
	// flags (a "backup eligible" credential is a synced passkey: iCloud
	// Keychain, Google Password Manager, etc.). go-webauthn's login
	// validation rejects an assertion whose BE flag differs from the stored
	// credential, so these MUST round-trip or every synced passkey login
	// fails. They are pointers on purpose: nil means "never recorded" (a
	// credential registered before this column existed) which the login path
	// reconciles via trust-on-first-use, and is distinct from a non-nil
	// false (a genuine non-backup-eligible credential recorded after the fix).
	BackupEligible *bool `json:"backupEligible,omitempty"`
	BackupState    *bool `json:"backupState,omitempty"`
}

WebAuthnCredential mirrors the persistent subset of webauthn.Credential. We store the COSE-encoded public key plus the metadata we own (nickname, timestamps, sign count). One row per registered authenticator; the same user can register many. CredentialID is the raw byte string the authenticator returned at registration and must be globally unique to prevent a stolen credential being re-registered against a different user.

SignCount is monotonic per credential. A login that supplies a non-greater value than the stored count is treated as a clone-attempt and refused via ErrReplayDetected (carve-out: an authenticator that never implements sign counts always returns 0, which the library handles as a per-spec exception).

Jump to

Keyboard shortcuts

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