Documentation
¶
Overview ¶
Package models is the internal home for the theauth-go data layer: persisted entity structs (User, Session, OAuthClient, Agent, ...), the canonical Permission name catalog, and the sentinel errors that storage adapters and service code share.
This package is internal. The exported root package (github.com/glincker/theauth-go/v2) re-exports every symbol here via type aliases (type X = models.X), const aliases (const X = models.X), and var aliases (var X = models.X). Compile-time API stability is preserved: the alias form keeps every type identity, method set, and exported name unchanged for downstream consumers.
The split exists to keep the root package focused on the public service surface (TheAuth, Storage, Config) without 600+ lines of struct definitions and constant catalogs in the same file tree.
Index ¶
- Constants
- Variables
- type ActorClaim
- type Agent
- type AgentCredential
- type AgentOwner
- type AgentSecret
- type AuditEvent
- type AuditQuery
- type AuthorizationCode
- type BackchannelRequest
- type ClientOwner
- type CreateAgentInput
- type DelegationGrant
- type GrantDelegationInput
- type Group
- type IdentityConflictError
- type JWKSKey
- type MagicLink
- type OAuthAccount
- type OAuthClient
- type OAuthConflictRedirectError
- type Organization
- type OrganizationMember
- type PasswordResetToken
- type Permission
- type ProtectedResource
- type RecoveryCode
- type RefreshToken
- type RegisteredClient
- type Role
- type SAMLAttributeMap
- type SAMLConnection
- type SAMLIdentity
- type SCIMGroupFilter
- type SCIMToken
- type SCIMUserFilter
- type Session
- type SessionLink
- type Stats
- type TOTPSecret
- type TargetRef
- type TheAuthError
- type ULID
- type User
- type UserRole
- type WebAuthnCredential
Constants ¶
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. Lifted to the models package (PR D architecture reorg, 2026-06-20) so internal service packages (password, totp, webauthn, saml) can construct TheAuthError with these codes without taking an import cycle on the root package. Re-exported from root errors.go as untyped string constants.
const ( CodeAccountLocked = "account_locked" CodeSignupClosed = "signup_closed" CodeSetupTokenInvalid = "setup_token_invalid" CodeBadRequest = "bad_request" CodeForbidden = "forbidden" CodeNotFound = "not_found" CodeConflict = "conflict" CodeInternal = "internal_error" )
Codes added with the auth hardening work. Additive: no existing code changed.
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.
const ( OrgRoleOwner = "owner" OrgRoleAdmin = "admin" OrgRoleMember = "member" )
Organization role constants. Scoped to one organization each.
const ( BackchannelStatusPending = "pending" BackchannelStatusApproved = "approved" BackchannelStatusDenied = "denied" )
BackchannelStatus values persisted in backchannel_requests.status.
const ( CIBADeliveryModePoll = "poll" CIBADeliveryModePing = "ping" )
CIBA token delivery mode constants.
const ( JWKSStateNext = "next" JWKSStateCurrent = "current" JWKSStatePrevious = "previous" JWKSStateRetired = "retired" )
JWKS key state constants.
const ( ClientOwnerKindUser = "user" ClientOwnerKindOrganization = "organization" ClientOwnerKindAgent = "agent" ClientOwnerKindAnonymous = "anonymous" )
Client owner kind constants persisted in oauth_clients.owner_kind.
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.
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.
const ( AgentStatusActive = "active" AgentStatusSuspended = "suspended" AgentStatusRevoked = "revoked" )
Agent lifecycle status values persisted in agents.status.
const ( AgentCredentialKindSecret = "secret" AgentCredentialKindX509 = "x509" AgentCredentialKindJWK = "jwk" )
Agent credential kind constants persisted in agent_credentials.kind.
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.
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.
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.
const GrantTypeCIBA = "urn:openid:params:grant-type:ciba"
CIBA grant type URN per RFC 9509 section 4.
const (
ResponseTypeCode = "code"
)
Response type constants. OAuth 2.1 supports only "code".
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.
const (
TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token"
)
Token type URNs used by the RFC 8693 token-exchange grant.
Variables ¶
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 that storage // adapters return on lookup misses. Lives in the models package so service // code can errors.Is-check without importing the storage package // (which would create an import cycle). ErrStorageNotFound = errors.New("theauth: storage row not found") // ErrBadCursor is returned by storage adapters (storage/postgres, // storage/mysql) when a caller-supplied keyset pagination cursor fails // to decode. Handlers errors.Is-check against this instead of // substring-matching err.Error(), so a wording change in the wrapped // decode error can never silently break 400-vs-500 branching. ErrBadCursor = errors.New("theauth: invalid pagination cursor") // 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. Lifted to internal/models in PR F so the extracted // organization handler package can errors.Is-check it without // importing root. 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. ErrASUnsupportedAlg = errors.New("theauth: AuthorizationServer.SigningAlg must be EdDSA") // 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") // 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") // 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 that the storage layer and service code share. These names are re-exported from the root package (github.com/glincker/theauth-go/v2) via var aliases for backward compatibility with v0.1+ callers that errors.Is-check against them.
Only model-layer sentinels live here: storage misses, expiry states, RBAC catalog rejections, organization invariants. Service-flow and wire-protocol sentinels (OAuth error strings, password reset codes, admin precondition checks) stay in the root package.
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.
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.
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") )
Functions ¶
This section is empty.
Types ¶
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"`
}
Agent is the persistent record for an agent identity.
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 AgentOwner ¶
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 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 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"`
}
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.
type AuditQuery ¶
type AuditQuery struct {
OrganizationID *ULID
ActorUserID *ULID
Action string
TargetType string
TargetID string
Since *time.Time
Until *time.Time
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.
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
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 ¶
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 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
}
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 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 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"`
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"`
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.
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 ¶
func (e *OAuthConflictRedirectError) Error() string
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 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 ¶
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 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
}
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"`
}
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 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 ¶
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 ¶
SCIMUserFilter is the equality-only filter accepted on /scim/v2/Users. Anything outside this whitelist returns 400 invalidFilter.
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"`
}
type SessionLink ¶
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 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 docs/2026-06-20-theauth-go-v1.0-design.md section 4.4). 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 ¶
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. Lifted to the models package (PR B architecture reorg, 2026-06-20) so internal subpackages can construct it without taking an import cycle 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 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).