sqlite

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 24 Imported by: ? 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.

README

theauth-go storage/sqlite

Pure Go (modernc.org/sqlite, no cgo) storage adapter for theauth-go. It runs on a *sql.DB you own.

go get github.com/glincker/theauth-go/storage/sqlite

Capabilities

Capability Migration
Users, sessions, magic links, passwords, OAuth accounts, passkeys, TOTP, audit 0001 to 0005, 0008
Session management and session links 0006
Scoped API tokens, device codes 0007, 0009, 0018
Account lifecycle (disable, delete, must change password), trusted devices 0010
Device identity (join tokens, enrolled devices) 0011
Shared signals 0012
Organizations and per-session active organization 0013
SAML connections and identities 0014 (needs 0013)
SCIM tokens, groups, group members 0015 (needs 0013)
RBAC permissions, roles, grants 0016 (needs 0013)
Audit accountability fields and tamper-evident hash chain 0017
Agent tool approvals (single use) 0019
OAuth 2.1 authorization server: clients, authorization codes, refresh tokens, revoked jti denylist, JWKS keys 0020 to 0024
Pushed authorization requests, opaque access tokens, device authorization grant, registration tokens 0025 to 0028
Cascade triggers for OAuth clients 0029
Agents and agent credentials 0030
Delegation grants 0031
jwt-bearer jti cache 0032
CIBA backchannel requests 0033
Session authentication methods (amr, auth_time) 0034

Migrate applies every pending file. If you own the schema, use Migrations or RenderMigrations and apply the files you need in order. The OAuth 2.1 authorization server (0020 to 0029) runs on this store alone, together with agents and delegation grants (0030, 0031), the jwt-bearer cache (0032) and CIBA (0033). See docs/mcp-oauth-sqlite.md for a guide, and docs/storage-capabilities.md for how this store compares with the others.

Running on an older schema

A database that has not run every migration keeps working for the features it already had.

  • Sessions without 0034. Sessions are read and written without an authentication record (AuthMethods is nil and AuthTime is zero), and AppendSessionAuthMethods returns ErrStorageMissingCapability. Tokens fall back to amr: ["pwd"]. Apply 0034 and create a new Store to turn the record on.
  • Audit without 0017. Events are written and read in the old shape and are not chained. Rows written before the migration stay unchained and are never rewritten.
  • OAuth server tables (0020 to 0029). Apply them before you enable Config.AuthorizationServer.

Enable SAML and SCIM

db, _ := sql.Open("sqlite", "file:app.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_txlock=immediate")
_ = sqlitestore.Migrate(ctx, db)
store, _ := sqlitestore.New(db)

auth, err := theauth.New(theauth.Config{
	Storage:       store,
	BaseURL:       "https://app.example.com",
	Organizations: &theauth.OrganizationsConfig{},
	SAML:          &theauth.SAMLConfig{SPCertificatePEM: certPEM, SPPrivateKeyPEM: keyPEM},
	SCIM:          &theauth.SCIMConfig{RequireHTTPS: true},
})

Notes

  • Foreign keys must be on; New refuses a database with them off. Use busy_timeout, WAL mode and _txlock=immediate on a shared file. A single process per database file is the supported shape; use Postgres or MySQL for several replicas.
  • OAuth signing keys are sealed with Config.EncryptionKey (32 bytes). Back up the key with the database file.
  • Organization slugs are lowercased and unique. Deleting an organization cascades to members, SAML connections and identities, SCIM tokens, groups and roles, and clears the active organization of sessions that pointed at it.
  • SCIM tokens are stored as sha256 hashes. SAML connections hold the IdP certificate and URLs only.
  • SweepExpired removes expired sessions, magic links, reset tokens, trusted devices, session links, device codes and join tokens. Call it from a ticker.
  • Deactivating a user through SCIM revokes their sessions (all of them when it was their last organization, otherwise those active in that organization) and removes the membership.

Documentation

Overview

Package sqlite implements theauth storage on a caller-owned *sql.DB using the pure Go modernc.org/sqlite driver.

The caller owns the database and its pragmas: foreign keys must be on for every connection, and busy_timeout plus WAL mode are strongly advised. Schema is managed either by the host (via Migrations and RenderMigrations) or by this package (via Migrate).

Index

Constants

View Source
const (
	// BackchannelStatusConsumed marks an approved request whose tokens were
	// redeemed through RedeemBackchannelRequest.
	BackchannelStatusConsumed = "consumed"
	// BackchannelStatusExpired marks a pending request swept by
	// ExpireBackchannelRequests.
	BackchannelStatusExpired = "expired"
)

Extra CIBA lifecycle states persisted by this store beyond the three the service layer writes (pending, approved, denied).

View Source
const DefaultTablePrefix = "theauth_"

DefaultTablePrefix is the table name prefix used when WithTablePrefix is not set.

Variables

View Source
var ErrBackchannelStateConflict = errors.New("theauth sqlite: backchannel request is not pending")

ErrBackchannelStateConflict is returned by UpdateBackchannelRequest when the stored request is no longer pending, so a second approve or deny loses.

Functions

func Migrate

func Migrate(ctx context.Context, db *sql.DB, opts ...Option) error

Migrate applies pending migrations tracked in <prefix>schema_migrations. Each step runs under BEGIN IMMEDIATE so concurrent processes serialize, and is recorded in the same transaction as its DDL.

func Migrations

func Migrations() fs.FS

Migrations returns the numbered forward-only .sql files, in the root of the FS, using the default table prefix.

Types

type AuditChainBreak added in v0.3.0

type AuditChainBreak = theauth.AuditChainBreak

AuditChainBreak, AuditChainResult: see theauth.AuditChainResult.

type AuditChainResult added in v0.3.0

type AuditChainResult = theauth.AuditChainResult

AuditChainBreak, AuditChainResult: see theauth.AuditChainResult.

type DBTX

type DBTX interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

DBTX is the subset of *sql.DB and *sql.Tx the Store runs its statements on.

type Migration

type Migration struct {
	// Version is the file name without the .sql suffix, for example 0001_core.
	Version string
	SQL     string
}

Migration is one forward-only schema step.

func RenderMigrations

func RenderMigrations(opts ...Option) ([]Migration, error)

RenderMigrations returns the migrations in version order with the table prefix applied.

type Option

type Option func(*config) error

Option configures New and Migrate.

func AllowForeignKeysOff

func AllowForeignKeysOff() Option

AllowForeignKeysOff lets New succeed when PRAGMA foreign_keys is off, which disables ON DELETE CASCADE.

func WithTablePrefix

func WithTablePrefix(prefix string) Option

WithTablePrefix sets the table name prefix, which must match between Migrate and New.

type Store

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

Store is the SQLite-backed storage adapter.

func New

func New(db *sql.DB, opts ...Option) (*Store, error)

New wraps db, which the caller keeps ownership of, and verifies foreign keys are enforced.

func NewTx

func NewTx(tx *sql.Tx, opts ...Option) (*Store, error)

NewTx binds a Store to the caller's open transaction. The Store never commits or rolls back; multi-statement methods use SAVEPOINTs inside tx. Run Migrate on the *sql.DB beforehand, as it cannot run inside a Tx.

func (*Store) APITokenByHash

func (s *Store) APITokenByHash(ctx context.Context, hash []byte) (*theauth.APIToken, error)

APITokenByHash returns the token with the given secret hash, else ErrStorageNotFound.

func (*Store) APITokenByID

func (s *Store) APITokenByID(ctx context.Context, id theauth.ULID) (*theauth.APIToken, error)

APITokenByID returns the token with the given ID, else ErrStorageNotFound.

func (*Store) APITokensByAgentID added in v0.3.0

func (s *Store) APITokensByAgentID(ctx context.Context, agentID theauth.ULID) ([]theauth.APIToken, error)

APITokensByAgentID returns every token minted for the agent, newest first.

func (*Store) APITokensByOwner

func (s *Store) APITokensByOwner(ctx context.Context, ownerID theauth.ULID) ([]theauth.APIToken, error)

APITokensByOwner returns every token of the owner, newest first.

func (*Store) AccountStateByUserID added in v0.2.0

func (s *Store) AccountStateByUserID(ctx context.Context, userID theauth.ULID) (theauth.AccountState, error)

AccountStateByUserID returns the user's lifecycle flags; a user without a row yields the zero state.

func (*Store) AddGroupMembers added in v0.2.0

func (s *Store) AddGroupMembers(ctx context.Context, groupID theauth.ULID, userIDs []theauth.ULID) error

AddGroupMembers adds members, ignoring those already present.

func (*Store) AdvanceTOTPStep

func (s *Store) AdvanceTOTPStep(ctx context.Context, userID theauth.ULID, step int64) (bool, error)

AdvanceTOTPStep records step as the user's last used TOTP step, returning false when it is not strictly newer.

func (*Store) AgentByClientID added in v0.3.0

func (s *Store) AgentByClientID(ctx context.Context, clientID string) (*theauth.Agent, error)

AgentByClientID looks an agent up by its OAuth client id.

func (*Store) AgentByID added in v0.3.0

func (s *Store) AgentByID(ctx context.Context, id theauth.ULID) (*theauth.Agent, error)

AgentByID implements the agent lookup; a missing row is ErrStorageNotFound.

func (*Store) AgentCredentialsByAgentID added in v0.3.0

func (s *Store) AgentCredentialsByAgentID(ctx context.Context, agentID theauth.ULID) ([]theauth.AgentCredential, error)

AgentCredentialsByAgentID returns every credential of the agent, oldest first, including revoked rows.

func (*Store) AgentsByOwner added in v0.3.0

func (s *Store) AgentsByOwner(ctx context.Context, owner theauth.AgentOwner) ([]theauth.Agent, error)

AgentsByOwner lists the agents of a user or organization, oldest first. The owner must set UserID or OrganizationID (UserID wins when both are set).

func (*Store) AppendSessionAuthMethods added in v0.3.0

func (s *Store) AppendSessionAuthMethods(ctx context.Context, id theauth.ULID, methods []string, at time.Time) ([]string, time.Time, error)

AppendSessionAuthMethods adds methods to the session's auth_methods and advances auth_time. The first statement of the transaction is a write, so SQLite holds the write lock for the whole read-merge-write and concurrent appends serialize without losing methods.

func (*Store) ApproveToolApproval added in v0.3.0

func (s *Store) ApproveToolApproval(ctx context.Context, id, approver string, now time.Time) (bool, error)

func (*Store) AtomicRotateJWKS added in v0.3.0

func (s *Store) AtomicRotateJWKS(ctx context.Context, retireKIDs []string, demoteKID, promoteKID string, freshKey theauth.JWKSKey, now time.Time) error

AtomicRotateJWKS implements as.JWKSAtomicRotator in one write-first transaction, so concurrent rotations serialize. Order matters for the one-current-per-algorithm index: retire, demote, promote, then insert. Unknown kids roll back.

func (*Store) BackchannelRequestByID added in v0.3.0

func (s *Store) BackchannelRequestByID(ctx context.Context, authReqID string) (theauth.BackchannelRequest, error)

func (*Store) ChainSupported added in v0.3.0

func (s *Store) ChainSupported() bool

ChainSupported reports that this backend keeps the tamper-evident audit hash chain (memory returns false). It hashes like postgres and mysql; the golden vector test pins them.

func (*Store) ClaimDeviceCode

func (s *Store) ClaimDeviceCode(ctx context.Context, hash []byte, now time.Time) (*theauth.DeviceCode, error)

ClaimDeviceCode atomically moves an approved, unexpired request to redeemed; one concurrent caller wins.

func (*Store) ConfirmTOTPSecret

func (s *Store) ConfirmTOTPSecret(ctx context.Context, userID theauth.ULID, at time.Time) error

ConfirmTOTPSecret confirms the user's pending secret, else ErrStorageNotFound.

func (*Store) ConsumeAuthorizationCode added in v0.3.0

func (s *Store) ConsumeAuthorizationCode(ctx context.Context, code string) (*theauth.AuthorizationCode, error)

ConsumeAuthorizationCode implements theauth.OAuthServerStorage. A single DELETE ... RETURNING is the winner check: SQLite serializes writers, so exactly one of N concurrent callers receives the row. Expiry is left to the caller, as in the other backends.

func (*Store) ConsumeDeviceAuthorization added in v0.3.0

func (s *Store) ConsumeDeviceAuthorization(ctx context.Context, id theauth.ULID, now time.Time) (bool, error)

ConsumeDeviceAuthorization implements theauth.DeviceAuthorizationStorage: approved to consumed, with exactly one winner under concurrency.

func (s *Store) ConsumeMagicLink(ctx context.Context, tokenHash []byte) (*theauth.MagicLink, error)

ConsumeMagicLink atomically marks an unused, unexpired link used and returns it.

func (*Store) ConsumePasswordResetToken

func (s *Store) ConsumePasswordResetToken(ctx context.Context, tokenHash []byte) (*theauth.PasswordResetToken, error)

ConsumePasswordResetToken atomically marks an unused, unexpired token used and returns it.

func (*Store) ConsumePushedRequest added in v0.3.0

func (s *Store) ConsumePushedRequest(ctx context.Context, requestURI string) ([]byte, error)

ConsumePushedRequest atomically marks the row consumed and returns its payload. It returns ErrStorageNotFound when the request_uri is unknown, already consumed, or expired. The conditional UPDATE is the single winner.

func (*Store) ConsumeRecoveryCode

func (s *Store) ConsumeRecoveryCode(ctx context.Context, userID theauth.ULID, code string, at time.Time) error

ConsumeRecoveryCode marks the matching unused code used, else ErrStorageNotFound.

func (s *Store) ConsumeSessionLink(ctx context.Context, tokenHash []byte, now time.Time) (*theauth.SessionLink, error)

ConsumeSessionLink atomically marks an unused, unexpired link used and returns it, else ErrStorageNotFound.

func (*Store) ConsumeToolApproval added in v0.3.0

func (s *Store) ConsumeToolApproval(ctx context.Context, id, agentID, action, resource string, now time.Time) (bool, error)

ConsumeToolApproval implements theauth.ToolApprovalStorage. The conditional UPDATE is the single winner check: only one caller sees one affected row.

func (*Store) CountUnusedRecoveryCodes

func (s *Store) CountUnusedRecoveryCodes(ctx context.Context, userID theauth.ULID) (int, error)

CountUnusedRecoveryCodes returns how many unused recovery codes userID holds.

func (*Store) CountUsers

func (s *Store) CountUsers(ctx context.Context) (int, error)

CountUsers returns the number of user rows.

func (*Store) CountUsersWithPermissionInOrg added in v0.2.0

func (s *Store) CountUsersWithPermissionInOrg(ctx context.Context, orgID theauth.ULID, perm string) (int, error)

CountUsersWithPermissionInOrg counts distinct users holding perm through an organization role.

func (s *Store) CreateMagicLink(ctx context.Context, ml theauth.MagicLink) error

CreateMagicLink stores a single-use magic link.

func (*Store) CreatePasswordResetToken

func (s *Store) CreatePasswordResetToken(ctx context.Context, t theauth.PasswordResetToken) error

CreatePasswordResetToken stores a single-use reset token.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, sess theauth.Session) (theauth.Session, error)

CreateSession inserts a session, defaulting AuthLevel to full.

func (s *Store) CreateSessionLink(ctx context.Context, l theauth.SessionLink) error

CreateSessionLink stores a single-use session link.

func (*Store) CreateSessionWithAuthLevel

func (s *Store) CreateSessionWithAuthLevel(ctx context.Context, sess theauth.Session) (theauth.Session, error)

CreateSessionWithAuthLevel is CreateSession; the level is read from sess.AuthLevel.

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, u theauth.User) (theauth.User, error)

CreateUser inserts u and returns the stored row. Email uniqueness is case-insensitive.

func (*Store) DecideDeviceAuthorization added in v0.3.0

func (s *Store) DecideDeviceAuthorization(ctx context.Context, id theauth.ULID, status string, userID theauth.ULID, now time.Time) (bool, error)

DecideDeviceAuthorization implements theauth.DeviceAuthorizationStorage as a compare and set from pending to the given status.

func (*Store) DecideDeviceCode

func (s *Store) DecideDeviceCode(ctx context.Context, userCode string, d theauth.DeviceDecision, now time.Time) error

DecideDeviceCode moves a pending, unexpired request to approved or denied in one statement.

func (*Store) DelegationGrantByID added in v0.3.0

func (s *Store) DelegationGrantByID(ctx context.Context, id theauth.ULID) (*theauth.DelegationGrant, error)

DelegationGrantByID returns the grant or ErrStorageNotFound.

func (*Store) DelegationGrantByUserAgentResource added in v0.3.0

func (s *Store) DelegationGrantByUserAgentResource(ctx context.Context, userID, agentID theauth.ULID, resource string) (*theauth.DelegationGrant, error)

DelegationGrantByUserAgentResource returns the live grant for the tuple, or the most recent revoked one when no live grant exists.

func (*Store) DelegationGrantsByAgentID added in v0.3.0

func (s *Store) DelegationGrantsByAgentID(ctx context.Context, agentID theauth.ULID) ([]theauth.DelegationGrant, error)

DelegationGrantsByAgentID lists every grant held by the agent, oldest first.

func (*Store) DelegationGrantsByUserID added in v0.3.0

func (s *Store) DelegationGrantsByUserID(ctx context.Context, userID theauth.ULID) ([]theauth.DelegationGrant, error)

DelegationGrantsByUserID lists every grant of the user, oldest first.

func (*Store) DeleteBackchannelRequest added in v0.3.0

func (s *Store) DeleteBackchannelRequest(ctx context.Context, authReqID string) error

func (*Store) DeleteExpiredDeviceAuthorizations added in v0.3.0

func (s *Store) DeleteExpiredDeviceAuthorizations(ctx context.Context, before time.Time) (int64, error)

func (*Store) DeleteExpiredDeviceCodes

func (s *Store) DeleteExpiredDeviceCodes(ctx context.Context, before time.Time) (int, error)

DeleteExpiredDeviceCodes removes requests that expired before the cutoff.

func (*Store) DeleteGroup added in v0.2.0

func (s *Store) DeleteGroup(ctx context.Context, id theauth.ULID) error

DeleteGroup removes a group and, by cascade, its memberships.

func (*Store) DeleteOAuthAccountByProvider

func (s *Store) DeleteOAuthAccountByProvider(ctx context.Context, userID theauth.ULID, provider string) error

DeleteOAuthAccountByProvider unlinks a user's account for one provider.

func (*Store) DeleteOAuthClient added in v0.3.0

func (s *Store) DeleteOAuthClient(ctx context.Context, clientID string) error

DeleteOAuthClient implements theauth.OAuthServerStorage. The 0029 trigger removes the client's codes and tokens in the same statement.

func (*Store) DeleteOrganization added in v0.2.0

func (s *Store) DeleteOrganization(ctx context.Context, id theauth.ULID) error

DeleteOrganization removes the organization and, by cascade, its members, connections, tokens, groups and roles.

func (*Store) DeleteOrganizationMember added in v0.2.0

func (s *Store) DeleteOrganizationMember(ctx context.Context, orgID, userID theauth.ULID) error

DeleteOrganizationMember removes one membership.

func (*Store) DeleteRole added in v0.2.0

func (s *Store) DeleteRole(ctx context.Context, id theauth.ULID) error

DeleteRole removes a role and, by cascade, its grants and permission links.

func (*Store) DeleteSAMLConnection added in v0.2.0

func (s *Store) DeleteSAMLConnection(ctx context.Context, id theauth.ULID) error

DeleteSAMLConnection removes a connection and, by cascade, its identities.

func (*Store) DeleteTOTPSecret

func (s *Store) DeleteTOTPSecret(ctx context.Context, userID theauth.ULID) error

DeleteTOTPSecret removes the user's secret and recovery codes.

func (*Store) DeleteUserCascade added in v0.2.0

func (s *Store) DeleteUserCascade(ctx context.Context, userID theauth.ULID) error

DeleteUserCascade removes the user and every row that belongs to it in one transaction.

func (*Store) DeleteWebAuthnCredential

func (s *Store) DeleteWebAuthnCredential(ctx context.Context, id theauth.ULID, userID theauth.ULID) error

DeleteWebAuthnCredential removes a credential owned by userID.

func (*Store) DenyAccessToken added in v0.3.0

func (s *Store) DenyAccessToken(ctx context.Context, jti string, expiresAt time.Time) error

DenyAccessToken records jti as revoked until expiresAt (opt-in access token revocation) and opportunistically purges entries that have lapsed.

func (*Store) DeviceAuthorizationByDeviceCodeHash added in v0.3.0

func (s *Store) DeviceAuthorizationByDeviceCodeHash(ctx context.Context, hash []byte) (*theauth.DeviceAuthorization, error)

func (*Store) DeviceAuthorizationByUserCodeHash added in v0.3.0

func (s *Store) DeviceAuthorizationByUserCodeHash(ctx context.Context, hash []byte) (*theauth.DeviceAuthorization, error)

func (*Store) DeviceByID added in v0.2.0

func (s *Store) DeviceByID(ctx context.Context, id theauth.ULID) (*theauth.Device, error)

DeviceByID returns the device, else ErrStorageNotFound.

func (*Store) DeviceCodeByHash

func (s *Store) DeviceCodeByHash(ctx context.Context, hash []byte) (*theauth.DeviceCode, error)

DeviceCodeByHash returns the request with the given device code hash, else ErrStorageNotFound.

func (*Store) DeviceCodeByUserCode

func (s *Store) DeviceCodeByUserCode(ctx context.Context, userCode string) (*theauth.DeviceCode, error)

DeviceCodeByUserCode returns the request with the given user code, else ErrStorageNotFound.

func (*Store) DeviceJoinTokenByHash added in v0.2.0

func (s *Store) DeviceJoinTokenByHash(ctx context.Context, hash []byte) (*theauth.DeviceJoinToken, error)

DeviceJoinTokenByHash returns the token with the given digest, else ErrStorageNotFound.

func (*Store) DeviceJoinTokenByID added in v0.2.0

func (s *Store) DeviceJoinTokenByID(ctx context.Context, id theauth.ULID) (*theauth.DeviceJoinToken, error)

DeviceJoinTokenByID returns the token, else ErrStorageNotFound.

func (*Store) ExpireBackchannelRequests added in v0.3.0

func (s *Store) ExpireBackchannelRequests(ctx context.Context, now time.Time) (int64, error)

ExpireBackchannelRequests marks every pending request whose deadline has passed as expired and returns how many rows changed.

func (*Store) GrantUserRole added in v0.2.0

func (s *Store) GrantUserRole(ctx context.Context, ur theauth.UserRole) error

GrantUserRole binds a role to a user and keeps the first grant on repeat calls.

func (*Store) GroupByExternalIDInOrg added in v0.2.0

func (s *Store) GroupByExternalIDInOrg(ctx context.Context, orgID theauth.ULID, externalID string) (*theauth.Group, error)

GroupByExternalIDInOrg returns the group carrying the external ID in one organization.

func (*Store) GroupByID added in v0.2.0

func (s *Store) GroupByID(ctx context.Context, id theauth.ULID) (*theauth.Group, error)

GroupByID returns the group with the given ID.

func (*Store) GroupMembers added in v0.2.0

func (s *Store) GroupMembers(ctx context.Context, groupID theauth.ULID) ([]theauth.ULID, error)

GroupMembers lists a group's member user IDs.

func (*Store) InsertAPIToken

func (s *Store) InsertAPIToken(ctx context.Context, t theauth.APIToken) (theauth.APIToken, error)

InsertAPIToken stores a token and returns the stored row.

func (*Store) InsertAgent added in v0.3.0

func (s *Store) InsertAgent(ctx context.Context, a theauth.Agent) (theauth.Agent, error)

InsertAgent stores a. A duplicate id or client_id returns theauth.ErrStorageNotFound. An empty Status defaults to active and a zero CreatedAt to now.

func (*Store) InsertAgentCredential added in v0.3.0

func (s *Store) InsertAgentCredential(ctx context.Context, c theauth.AgentCredential) error

InsertAgentCredential stores a credential row. A duplicate id returns ErrStorageNotFound.

func (*Store) InsertAuditEvents

func (s *Store) InsertAuditEvents(ctx context.Context, events []theauth.AuditEvent) error

InsertAuditEvents appends a batch in one transaction. Rows are linked into a per-organization hash chain (see VerifyAuditChain). If the database has not run migration 0017 the rows are written without chain or accountability columns, so hosts upgrading in two steps keep working.

func (*Store) InsertAuthorizationCode added in v0.3.0

func (s *Store) InsertAuthorizationCode(ctx context.Context, c theauth.AuthorizationCode) error

func (*Store) InsertBackchannelRequest added in v0.3.0

func (s *Store) InsertBackchannelRequest(ctx context.Context, req theauth.BackchannelRequest) error

InsertBackchannelRequest fails on a duplicate auth_req_id (primary key).

func (*Store) InsertDelegationGrant added in v0.3.0

func (s *Store) InsertDelegationGrant(ctx context.Context, g theauth.DelegationGrant) (theauth.DelegationGrant, error)

InsertDelegationGrant allows at most one live grant per (user, agent, resource). A second live insert or a duplicate id returns ErrStorageNotFound; a revoked grant frees the tuple.

func (*Store) InsertDevice added in v0.2.0

func (s *Store) InsertDevice(ctx context.Context, d theauth.Device) error

InsertDevice stores a device, returning ErrDeviceConflict when its SPIFFE ID is taken.

func (*Store) InsertDeviceAuthorization added in v0.3.0

func (s *Store) InsertDeviceAuthorization(ctx context.Context, d theauth.DeviceAuthorization) error

InsertDeviceAuthorization implements theauth.DeviceAuthorizationStorage. An expired holder of the same user code is deleted first; a live one yields ErrDeviceAuthUserCodeTaken.

func (*Store) InsertDeviceCode

func (s *Store) InsertDeviceCode(ctx context.Context, d theauth.DeviceCode) error

InsertDeviceCode stores a request, returning ErrDeviceUserCodeTaken on a user code collision.

func (*Store) InsertDeviceJoinToken added in v0.2.0

func (s *Store) InsertDeviceJoinToken(ctx context.Context, t theauth.DeviceJoinToken) error

InsertDeviceJoinToken stores a join token.

func (*Store) InsertGroup added in v0.2.0

func (s *Store) InsertGroup(ctx context.Context, g theauth.Group) (theauth.Group, error)

InsertGroup stores a group; (organization, display name) and (organization, external ID) are unique.

func (*Store) InsertJTI added in v0.3.0

func (s *Store) InsertJTI(ctx context.Context, jti string, expiresAt time.Time) error

InsertJTI records a jti for RFC 7523 replay protection. It returns ErrStorageNotFound when the jti is already recorded and unexpired (the JWTBearerStorage duplicate signal). One upsert statement decides the winner: an expired row is overwritten, a live row blocks the insert, so concurrent presentations of the same jti produce exactly one success.

func (*Store) InsertJWKSKey added in v0.3.0

func (s *Store) InsertJWKSKey(ctx context.Context, k theauth.JWKSKey) error

InsertJWKSKey implements theauth.OAuthServerStorage. A duplicate kid, or a second current key for the same algorithm, is rejected by the schema.

func (*Store) InsertOAuthClient added in v0.3.0

func (s *Store) InsertOAuthClient(ctx context.Context, c theauth.OAuthClient) (theauth.OAuthClient, error)

func (*Store) InsertOpaqueAccessToken added in v0.3.0

func (s *Store) InsertOpaqueAccessToken(ctx context.Context, t theauth.OpaqueAccessToken) error

func (*Store) InsertOrganization added in v0.2.0

func (s *Store) InsertOrganization(ctx context.Context, o theauth.Organization) (theauth.Organization, error)

InsertOrganization stores o with a lowercased slug and returns ErrSlugTaken on a duplicate.

func (*Store) InsertPermission added in v0.2.0

func (s *Store) InsertPermission(ctx context.Context, p theauth.Permission) (theauth.Permission, error)

InsertPermission is idempotent on the name: a duplicate returns the existing row.

func (*Store) InsertPushedRequest added in v0.3.0

func (s *Store) InsertPushedRequest(ctx context.Context, requestURI string, payload []byte, expiresAt time.Time) error

InsertPushedRequest stores a pushed authorization request. requestURI is the full urn: string, payload the JSON encoded AuthorizeRequest.

func (*Store) InsertRecoveryCodes

func (s *Store) InsertRecoveryCodes(ctx context.Context, codes []theauth.RecoveryCode) error

InsertRecoveryCodes stores a batch of recovery codes atomically.

func (*Store) InsertRefreshToken added in v0.3.0

func (s *Store) InsertRefreshToken(ctx context.Context, t theauth.RefreshToken) error

func (*Store) InsertRegistrationToken added in v0.3.0

func (s *Store) InsertRegistrationToken(ctx context.Context, t theauth.RegistrationToken) error

func (*Store) InsertRole added in v0.2.0

func (s *Store) InsertRole(ctx context.Context, r theauth.Role) (theauth.Role, error)

InsertRole stores a role; names are unique within an organization and among system roles.

func (*Store) InsertSAMLConnection added in v0.2.0

func (s *Store) InsertSAMLConnection(ctx context.Context, c theauth.SAMLConnection) (theauth.SAMLConnection, error)

InsertSAMLConnection stores a connection bound to an existing organization.

func (*Store) InsertSCIMToken added in v0.2.0

func (s *Store) InsertSCIMToken(ctx context.Context, t theauth.SCIMToken) (theauth.SCIMToken, error)

InsertSCIMToken stores a token hash bound to an existing organization.

func (*Store) InsertTrustedDevice added in v0.2.0

func (s *Store) InsertTrustedDevice(ctx context.Context, d theauth.TrustedDevice) error

InsertTrustedDevice stores a remember-this-device record.

func (*Store) InsertWebAuthnCredential

func (s *Store) InsertWebAuthnCredential(ctx context.Context, c theauth.WebAuthnCredential) (theauth.WebAuthnCredential, error)

InsertWebAuthnCredential stores a credential and returns the stored row.

func (*Store) IsAccessTokenDenied added in v0.3.0

func (s *Store) IsAccessTokenDenied(ctx context.Context, jti string) (bool, error)

IsAccessTokenDenied reports whether jti is on the unexpired denylist.

func (*Store) JWKSKeyByKID added in v0.3.0

func (s *Store) JWKSKeyByKID(ctx context.Context, kid string) (*theauth.JWKSKey, error)

func (*Store) JWKSKeysAll added in v0.3.0

func (s *Store) JWKSKeysAll(ctx context.Context) ([]theauth.JWKSKey, error)

JWKSKeysAll implements theauth.OAuthServerStorage, oldest key first.

func (*Store) ListAPITokens

func (s *Store) ListAPITokens(ctx context.Context) ([]theauth.APIToken, error)

ListAPITokens returns every token, newest first.

func (*Store) ListDevices added in v0.2.0

func (s *Store) ListDevices(ctx context.Context, orgID *theauth.ULID) ([]theauth.Device, error)

ListDevices returns devices newest first. A nil orgID lists every device.

func (*Store) ListGroupsByOrganization added in v0.2.0

func (s *Store) ListGroupsByOrganization(ctx context.Context, orgID theauth.ULID, offset, limit int, filter theauth.SCIMGroupFilter) ([]theauth.Group, int, error)

ListGroupsByOrganization pages through an organization's groups matching the equality filter.

func (*Store) ListPendingDeviceCodes

func (s *Store) ListPendingDeviceCodes(ctx context.Context, f theauth.DevicePendingFilter) ([]theauth.DeviceCode, error)

ListPendingDeviceCodes returns pending, unexpired requests newest first without device code hashes.

func (*Store) ListPermissions added in v0.2.0

func (s *Store) ListPermissions(ctx context.Context) ([]theauth.Permission, error)

ListPermissions returns the catalog ordered by name.

func (*Store) ListRegistrationTokens added in v0.3.0

func (s *Store) ListRegistrationTokens(ctx context.Context, orgID *theauth.ULID) ([]theauth.RegistrationToken, error)

ListRegistrationTokens implements theauth.RegistrationTokenStorage, newest first.

func (*Store) ListTrustedDevices added in v0.2.0

func (s *Store) ListTrustedDevices(ctx context.Context, userID theauth.ULID) ([]theauth.TrustedDevice, error)

ListTrustedDevices returns the user's unrevoked, unexpired devices, newest first.

func (*Store) ListUserSessions

func (s *Store) ListUserSessions(ctx context.Context, userID theauth.ULID) ([]theauth.Session, error)

ListUserSessions returns the user's live sessions, newest first.

func (*Store) ListUsersByOrganization added in v0.2.0

func (s *Store) ListUsersByOrganization(ctx context.Context, orgID theauth.ULID, offset, limit int, filter theauth.SCIMUserFilter) ([]theauth.User, int, error)

ListUsersByOrganization pages through an organization's members matching the equality filter.

func (*Store) MarkEmailVerified

func (s *Store) MarkEmailVerified(ctx context.Context, userID theauth.ULID) error

MarkEmailVerified sets the verification time once and keeps the first value on repeat calls.

func (*Store) MoveOAuthAccount

func (s *Store) MoveOAuthAccount(ctx context.Context, provider, providerUserID string, newUserID theauth.ULID) error

MoveOAuthAccount reassigns a linked account to newUserID.

func (*Store) MovePasswordHash

func (s *Store) MovePasswordHash(ctx context.Context, primaryID, secondaryID theauth.ULID) error

MovePasswordHash moves the hash from secondaryID to primaryID, overwriting any existing one.

func (*Store) MoveTOTPSecret

func (s *Store) MoveTOTPSecret(ctx context.Context, primaryID, secondaryID theauth.ULID) error

MoveTOTPSecret moves secondaryID's secret to primaryID, or drops it when primaryID already has one.

func (*Store) MoveWebAuthnCredentials

func (s *Store) MoveWebAuthnCredentials(ctx context.Context, primaryID, secondaryID theauth.ULID) error

MoveWebAuthnCredentials reassigns every credential of secondaryID to primaryID.

func (*Store) OAuthAccountByProviderUserID

func (s *Store) OAuthAccountByProviderUserID(ctx context.Context, provider, providerUserID string) (*theauth.OAuthAccount, error)

OAuthAccountByProviderUserID looks up a linked account by its provider identity.

func (*Store) OAuthAccountsByUserID

func (s *Store) OAuthAccountsByUserID(ctx context.Context, userID theauth.ULID) ([]theauth.OAuthAccount, error)

OAuthAccountsByUserID lists a user's linked accounts, empty when there are none.

func (*Store) OAuthClientByClientID added in v0.3.0

func (s *Store) OAuthClientByClientID(ctx context.Context, clientID string) (*theauth.OAuthClient, error)

func (*Store) OpaqueAccessTokenByHash added in v0.3.0

func (s *Store) OpaqueAccessTokenByHash(ctx context.Context, hash []byte) (*theauth.OpaqueAccessToken, error)

func (*Store) OpenToolApproval added in v0.3.0

func (s *Store) OpenToolApproval(ctx context.Context, a theauth.ToolApproval) error

func (*Store) OrganizationByID added in v0.2.0

func (s *Store) OrganizationByID(ctx context.Context, id theauth.ULID) (*theauth.Organization, error)

OrganizationByID returns the organization with the given ID.

func (*Store) OrganizationBySlug added in v0.2.0

func (s *Store) OrganizationBySlug(ctx context.Context, slug string) (*theauth.Organization, error)

OrganizationBySlug returns the organization with the given slug, compared case-insensitively.

func (*Store) OrganizationMemberRole added in v0.2.0

func (s *Store) OrganizationMemberRole(ctx context.Context, orgID, userID theauth.ULID) (string, error)

OrganizationMemberRole returns the member's role, or ErrStorageNotFound when the user is not a member.

func (*Store) OrganizationMembersByOrg added in v0.2.0

func (s *Store) OrganizationMembersByOrg(ctx context.Context, orgID theauth.ULID) ([]theauth.OrganizationMember, error)

OrganizationMembersByOrg lists an organization's members, oldest first.

func (*Store) OrganizationsByUser added in v0.2.0

func (s *Store) OrganizationsByUser(ctx context.Context, userID theauth.ULID) ([]theauth.Organization, error)

OrganizationsByUser lists the organizations a user belongs to, oldest first.

func (*Store) PermissionByName added in v0.2.0

func (s *Store) PermissionByName(ctx context.Context, name string) (*theauth.Permission, error)

PermissionByName returns the permission with the given name.

func (*Store) PermissionsByRole added in v0.2.0

func (s *Store) PermissionsByRole(ctx context.Context, roleID theauth.ULID) ([]string, error)

PermissionsByRole returns a role's permission names in order.

func (*Store) PermissionsForUser added in v0.2.0

func (s *Store) PermissionsForUser(ctx context.Context, userID theauth.ULID, orgID *theauth.ULID) ([]string, error)

PermissionsForUser returns the distinct permission names a user holds in one organization scope.

func (*Store) QueryAuditEvents

func (s *Store) QueryAuditEvents(ctx context.Context, q theauth.AuditQuery) ([]theauth.AuditEvent, string, error)

QueryAuditEvents returns events newest first with keyset pagination over (created_at, id).

func (*Store) RecordDeviceAuthorizationPoll added in v0.3.0

func (s *Store) RecordDeviceAuthorizationPoll(ctx context.Context, id theauth.ULID, polledAt time.Time, intervalSeconds int) error

func (*Store) RecordDevicePoll

func (s *Store) RecordDevicePoll(ctx context.Context, hash []byte, at time.Time, intervalSeconds int) error

RecordDevicePoll stores the last poll time and the current polling interval.

func (*Store) RedeemBackchannelRequest added in v0.3.0

func (s *Store) RedeemBackchannelRequest(ctx context.Context, authReqID string, now time.Time) (theauth.BackchannelRequest, bool, error)

RedeemBackchannelRequest moves an approved, unexpired request to consumed in one statement, so exactly one concurrent caller wins. It extends theauth.CIBAStorage for one-time token delivery.

func (*Store) RedeemDeviceJoinToken added in v0.2.0

func (s *Store) RedeemDeviceJoinToken(ctx context.Context, id, deviceID theauth.ULID, now time.Time) (bool, error)

RedeemDeviceJoinToken marks an unredeemed, unrevoked, unexpired token redeemed and reports whether this call did it, so a join token is single use.

func (*Store) RedeemRegistrationToken added in v0.3.0

func (s *Store) RedeemRegistrationToken(ctx context.Context, id theauth.ULID, now time.Time) (bool, error)

RedeemRegistrationToken implements theauth.RegistrationTokenStorage. The uses < max_uses guard keeps a one-time token to one winner.

func (*Store) RefreshTokenByHash added in v0.3.0

func (s *Store) RefreshTokenByHash(ctx context.Context, hash []byte) (*theauth.RefreshToken, error)

func (*Store) RefundDeviceJoinToken added in v0.2.0

func (s *Store) RefundDeviceJoinToken(ctx context.Context, id theauth.ULID) error

RefundDeviceJoinToken undoes a redemption when enrollment failed after it.

func (*Store) RefundRegistrationToken added in v0.3.0

func (s *Store) RefundRegistrationToken(ctx context.Context, id theauth.ULID) error

func (*Store) RegistrationTokenByHash added in v0.3.0

func (s *Store) RegistrationTokenByHash(ctx context.Context, hash []byte) (*theauth.RegistrationToken, error)

func (*Store) RegistrationTokenByID added in v0.3.0

func (s *Store) RegistrationTokenByID(ctx context.Context, id theauth.ULID) (*theauth.RegistrationToken, error)

func (*Store) RemoveGroupMembers added in v0.2.0

func (s *Store) RemoveGroupMembers(ctx context.Context, groupID theauth.ULID, userIDs []theauth.ULID) error

RemoveGroupMembers removes members; absent users are ignored.

func (*Store) RenameWebAuthnCredential

func (s *Store) RenameWebAuthnCredential(ctx context.Context, id, userID theauth.ULID, name string) error

RenameWebAuthnCredential sets a passkey's display name when it belongs to userID.

func (*Store) ReplaceRecoveryCodes

func (s *Store) ReplaceRecoveryCodes(ctx context.Context, userID theauth.ULID, codes []theauth.RecoveryCode) error

ReplaceRecoveryCodes atomically swaps every recovery code of userID for codes.

func (*Store) RevokeAPIToken

func (s *Store) RevokeAPIToken(ctx context.Context, id theauth.ULID, at time.Time) error

RevokeAPIToken revokes a token, keeping the first revocation time on repeat calls.

func (*Store) RevokeAPITokensByOwner

func (s *Store) RevokeAPITokensByOwner(ctx context.Context, ownerID theauth.ULID, at time.Time) (int, error)

RevokeAPITokensByOwner revokes the owner's live tokens and returns how many it changed.

func (*Store) RevokeAgentCredential added in v0.3.0

func (s *Store) RevokeAgentCredential(ctx context.Context, id theauth.ULID, at time.Time) error

RevokeAgentCredential sets revoked_at once. A repeat revoke returns ErrStorageNotFound, as the other adapters do.

func (*Store) RevokeDelegationGrant added in v0.3.0

func (s *Store) RevokeDelegationGrant(ctx context.Context, id theauth.ULID, at time.Time, reason string) error

RevokeDelegationGrant is conditional on revoked_at IS NULL, so exactly one concurrent caller wins and keeps its reason and time. Later calls return ErrStorageNotFound; internal/delegation relies on that to emit one audit event.

func (*Store) RevokeDevice added in v0.2.0

func (s *Store) RevokeDevice(ctx context.Context, id theauth.ULID, at time.Time) (bool, error)

RevokeDevice marks an active device revoked and reports whether it changed anything.

func (*Store) RevokeDeviceJoinToken added in v0.2.0

func (s *Store) RevokeDeviceJoinToken(ctx context.Context, id theauth.ULID, at time.Time) (bool, error)

RevokeDeviceJoinToken revokes a token that is not yet revoked.

func (*Store) RevokeOpaqueAccessToken added in v0.3.0

func (s *Store) RevokeOpaqueAccessToken(ctx context.Context, hash []byte) error

RevokeOpaqueAccessToken implements theauth.OpaqueTokenStorage. Revoking an unknown or already revoked token is not an error, and the first revocation time is kept.

func (*Store) RevokeOtherUserSessions

func (s *Store) RevokeOtherUserSessions(ctx context.Context, userID, keep theauth.ULID) (int, error)

RevokeOtherUserSessions revokes the user's live sessions except keep and returns the count.

func (*Store) RevokeRefreshToken added in v0.3.0

func (s *Store) RevokeRefreshToken(ctx context.Context, hash []byte, reason string) error

RevokeRefreshToken implements theauth.OAuthServerStorage. It is the rotation gate: exactly one caller wins per token; a replay or concurrent refresh gets ErrStorageNotFound.

func (*Store) RevokeRefreshTokenFamily added in v0.3.0

func (s *Store) RevokeRefreshTokenFamily(ctx context.Context, familyID theauth.ULID, reason string) error

RevokeRefreshTokenFamily implements theauth.OAuthServerStorage. Revoking a family with no live tokens is not an error.

func (*Store) RevokeRefreshTokensByAuthCode added in v0.3.0

func (s *Store) RevokeRefreshTokensByAuthCode(ctx context.Context, codeHash, reason string) ([]string, error)

RevokeRefreshTokensByAuthCode revokes every live token issued from the code stored under codeHash (RFC 6749 4.1.2 code replay) and returns their access token jtis, in one statement.

func (*Store) RevokeRegistrationToken added in v0.3.0

func (s *Store) RevokeRegistrationToken(ctx context.Context, id theauth.ULID, at time.Time) (bool, error)

func (*Store) RevokeSCIMTokenByID added in v0.2.0

func (s *Store) RevokeSCIMTokenByID(ctx context.Context, id theauth.ULID, at time.Time) error

RevokeSCIMTokenByID marks a token revoked.

func (*Store) RevokeSession

func (s *Store) RevokeSession(ctx context.Context, id theauth.ULID) error

RevokeSession marks a session revoked and keeps the first revocation time on repeat calls.

func (*Store) RevokeSessionsByCredential

func (s *Store) RevokeSessionsByCredential(ctx context.Context, credentialID string) (int, error)

RevokeSessionsByCredential revokes every live session bound to credentialID and returns the count.

func (*Store) RevokeTrustedDevice added in v0.2.0

func (s *Store) RevokeTrustedDevice(ctx context.Context, userID, id theauth.ULID) error

RevokeTrustedDevice revokes one live device owned by userID.

func (*Store) RevokeUserRole added in v0.2.0

func (s *Store) RevokeUserRole(ctx context.Context, userID, roleID theauth.ULID) error

RevokeUserRole removes a grant, returning ErrStorageNotFound when none existed.

func (*Store) RevokeUserSessions

func (s *Store) RevokeUserSessions(ctx context.Context, userID theauth.ULID) error

RevokeUserSessions revokes every active session of a user.

func (*Store) RevokeUserTrustedDevices added in v0.2.0

func (s *Store) RevokeUserTrustedDevices(ctx context.Context, userID theauth.ULID) (int, error)

RevokeUserTrustedDevices revokes every live device of userID and returns how many it revoked.

func (*Store) RoleByID added in v0.2.0

func (s *Store) RoleByID(ctx context.Context, id theauth.ULID) (*theauth.Role, error)

RoleByID returns a role with its permission names.

func (*Store) RoleByOrgAndName added in v0.2.0

func (s *Store) RoleByOrgAndName(ctx context.Context, orgID *theauth.ULID, name string) (*theauth.Role, error)

RoleByOrgAndName returns a role by name within an organization, or among system roles when orgID is nil.

func (*Store) RolesByOrganization added in v0.2.0

func (s *Store) RolesByOrganization(ctx context.Context, orgID *theauth.ULID) ([]theauth.Role, error)

RolesByOrganization lists roles of one organization, or the system roles when orgID is nil.

func (*Store) RolesForUser added in v0.2.0

func (s *Store) RolesForUser(ctx context.Context, userID theauth.ULID, orgID *theauth.ULID) ([]theauth.Role, error)

RolesForUser lists the user's roles in one organization, or the system roles when orgID is nil.

func (*Store) SAMLConnectionByID added in v0.2.0

func (s *Store) SAMLConnectionByID(ctx context.Context, id theauth.ULID) (*theauth.SAMLConnection, error)

SAMLConnectionByID returns the connection with the given ID.

func (*Store) SAMLConnectionsByOrg added in v0.2.0

func (s *Store) SAMLConnectionsByOrg(ctx context.Context, orgID theauth.ULID) ([]theauth.SAMLConnection, error)

SAMLConnectionsByOrg lists an organization's connections, oldest first.

func (*Store) SAMLIdentityByConnectionAndNameID added in v0.2.0

func (s *Store) SAMLIdentityByConnectionAndNameID(ctx context.Context, connectionID theauth.ULID, nameID string) (*theauth.SAMLIdentity, error)

SAMLIdentityByConnectionAndNameID returns the identity for a NameID on a connection.

func (*Store) SCIMTokenByHash added in v0.2.0

func (s *Store) SCIMTokenByHash(ctx context.Context, hash []byte) (*theauth.SCIMToken, error)

SCIMTokenByHash returns the token row for a hash, including revoked ones.

func (*Store) SCIMTokensByOrg added in v0.2.0

func (s *Store) SCIMTokensByOrg(ctx context.Context, orgID theauth.ULID) ([]theauth.SCIMToken, error)

SCIMTokensByOrg lists an organization's tokens, oldest first.

func (*Store) SessionByID

func (s *Store) SessionByID(ctx context.Context, id theauth.ULID) (*theauth.Session, error)

SessionByID returns the session with the given ID.

func (*Store) SessionByTokenHash

func (s *Store) SessionByTokenHash(ctx context.Context, hash []byte) (*theauth.Session, error)

SessionByTokenHash returns the session for a token hash, including revoked and expired ones.

func (*Store) SetGroupMembers added in v0.2.0

func (s *Store) SetGroupMembers(ctx context.Context, groupID theauth.ULID, userIDs []theauth.ULID) error

SetGroupMembers replaces the member set atomically.

func (*Store) SetMustChangePassword added in v0.2.0

func (s *Store) SetMustChangePassword(ctx context.Context, userID theauth.ULID, required bool) error

SetMustChangePassword sets or clears the forced password change flag.

func (*Store) SetRolePermissions added in v0.2.0

func (s *Store) SetRolePermissions(ctx context.Context, roleID theauth.ULID, permissionIDs []theauth.ULID) error

SetRolePermissions replaces a role's permission set atomically.

func (*Store) SetSessionActiveOrganization added in v0.2.0

func (s *Store) SetSessionActiveOrganization(ctx context.Context, sessionID theauth.ULID, orgID *theauth.ULID) error

SetSessionActiveOrganization points a session at an organization, or clears it when orgID is nil.

func (*Store) SetSessionElevatedUntil

func (s *Store) SetSessionElevatedUntil(ctx context.Context, id theauth.ULID, until *time.Time) error

SetSessionElevatedUntil sets or clears the step-up window of one session.

func (*Store) SetUserDisabledAt added in v0.2.0

func (s *Store) SetUserDisabledAt(ctx context.Context, userID theauth.ULID, at *time.Time) error

SetUserDisabledAt disables the user at the given time, or re-enables it when at is nil.

func (*Store) SetUserPassword

func (s *Store) SetUserPassword(ctx context.Context, userID theauth.ULID, passwordHash string) error

SetUserPassword upserts the user's PHC hash and returns ErrStorageNotFound for an unknown user.

func (*Store) SignalsStore added in v0.2.0

func (s *Store) SignalsStore() signals.Store

SignalsStore returns a signals.Store backed by this database. Pass it as SharedSignalsConfig.Store.

func (*Store) SweepExpired

func (s *Store) SweepExpired(ctx context.Context, now time.Time) (SweepResult, error)

SweepExpired deletes expired rows (sessions, magic links, reset tokens, trusted devices, session links, device codes, join tokens). Consumed tokens go only once expired, so replay detection is not weakened early. Tables from migrations the host has not applied are skipped.

func (*Store) SweepExpiredJTIs added in v0.3.0

func (s *Store) SweepExpiredJTIs(ctx context.Context, before time.Time) error

SweepExpiredJTIs removes every jti that expired before the given time.

func (*Store) TOTPSecretByUserID

func (s *Store) TOTPSecretByUserID(ctx context.Context, userID theauth.ULID) (*theauth.TOTPSecret, error)

TOTPSecretByUserID returns the user's secret row.

func (*Store) ThrottleStore

func (s *Store) ThrottleStore() *ThrottleStore

ThrottleStore returns a login throttle store backed by the same database and table prefix.

func (*Store) TouchAPITokenLastUsed

func (s *Store) TouchAPITokenLastUsed(ctx context.Context, id theauth.ULID, at time.Time) error

TouchAPITokenLastUsed records the last use time of a token.

func (*Store) TouchBackchannelPoll added in v0.3.0

func (s *Store) TouchBackchannelPoll(ctx context.Context, authReqID string, now time.Time, newInterval int) (theauth.BackchannelRequest, error)

TouchBackchannelPoll implements theauth.CIBAStorage in one UPDATE ... RETURNING.

func (*Store) TouchDevice added in v0.2.0

func (s *Store) TouchDevice(ctx context.Context, id theauth.ULID, at time.Time) error

TouchDevice stamps last_seen_at.

func (*Store) TouchSAMLIdentityLastLogin added in v0.2.0

func (s *Store) TouchSAMLIdentityLastLogin(ctx context.Context, id theauth.ULID, at time.Time) error

TouchSAMLIdentityLastLogin records a login time on an identity.

func (*Store) TouchSCIMTokenLastUsed added in v0.2.0

func (s *Store) TouchSCIMTokenLastUsed(ctx context.Context, id theauth.ULID, at time.Time) error

TouchSCIMTokenLastUsed records the last successful use of a token.

func (*Store) TouchSession

func (s *Store) TouchSession(ctx context.Context, id theauth.ULID, at time.Time) error

TouchSession advances last-seen time and never moves it backwards.

func (*Store) TouchTrustedDevice added in v0.2.0

func (s *Store) TouchTrustedDevice(ctx context.Context, id theauth.ULID, at time.Time) error

TouchTrustedDevice sets LastUsedAt.

func (*Store) TrustedDeviceByTokenHash added in v0.2.0

func (s *Store) TrustedDeviceByTokenHash(ctx context.Context, userID theauth.ULID, hash []byte) (*theauth.TrustedDevice, error)

TrustedDeviceByTokenHash returns the record for userID and hash, revoked or expired rows included.

func (*Store) UpdateAgentCredentialLastUsed added in v0.3.0

func (s *Store) UpdateAgentCredentialLastUsed(ctx context.Context, id theauth.ULID, at time.Time) error

UpdateAgentCredentialLastUsed records credential use. Like Postgres it does not fail on a missing row.

func (*Store) UpdateAgentLastActive added in v0.3.0

func (s *Store) UpdateAgentLastActive(ctx context.Context, id theauth.ULID, at time.Time) error

UpdateAgentLastActive records the last activity time.

func (*Store) UpdateAgentStatus added in v0.3.0

func (s *Store) UpdateAgentStatus(ctx context.Context, id theauth.ULID, status string, _ time.Time) error

UpdateAgentStatus sets the lifecycle status. The service layer owns the state machine; a single UPDATE serializes concurrent changes.

func (*Store) UpdateBackchannelRequest added in v0.3.0

func (s *Store) UpdateBackchannelRequest(ctx context.Context, req theauth.BackchannelRequest) error

UpdateBackchannelRequest implements theauth.CIBAStorage. Mutable fields are written only while the row is still pending, in one conditional UPDATE, so approval or denial happens exactly once under concurrency.

func (*Store) UpdateGroup added in v0.2.0

func (s *Store) UpdateGroup(ctx context.Context, g theauth.Group) error

UpdateGroup rewrites a group's display name and external ID.

func (*Store) UpdateJWKSKeyState added in v0.3.0

func (s *Store) UpdateJWKSKeyState(ctx context.Context, kid, state string, at time.Time) error

UpdateJWKSKeyState implements theauth.OAuthServerStorage, stamping promoted_at or retired_at on transition. An unknown kid is ErrStorageNotFound.

func (*Store) UpdateOAuthClient added in v0.3.0

func (s *Store) UpdateOAuthClient(ctx context.Context, c theauth.OAuthClient) (theauth.OAuthClient, error)

UpdateOAuthClient implements theauth.OAuthServerStorage. Owner, secret hash and creation time are immutable here, matching the other backends.

func (*Store) UpdateOrganization added in v0.2.0

func (s *Store) UpdateOrganization(ctx context.Context, o theauth.Organization) error

UpdateOrganization rewrites the name and slug and returns ErrSlugTaken on a duplicate slug.

func (*Store) UpdateRoleRow added in v0.2.0

func (s *Store) UpdateRoleRow(ctx context.Context, r theauth.Role) (theauth.Role, error)

UpdateRoleRow rewrites a role's name and description.

func (*Store) UpdateSAMLConnectionRow added in v0.2.0

func (s *Store) UpdateSAMLConnectionRow(ctx context.Context, c theauth.SAMLConnection) error

UpdateSAMLConnectionRow rewrites the IdP and SP settings of a connection.

func (*Store) UpdateSessionAuthLevel

func (s *Store) UpdateSessionAuthLevel(ctx context.Context, id theauth.ULID, level string) error

UpdateSessionAuthLevel rewrites one session's auth level.

func (*Store) UpdateUserSCIM added in v0.2.0

func (s *Store) UpdateUserSCIM(ctx context.Context, u theauth.User) error

UpdateUserSCIM rewrites the SCIM-managed profile fields of a user.

func (*Store) UpdateWebAuthnBackupFlags

func (s *Store) UpdateWebAuthnBackupFlags(ctx context.Context, credentialID []byte, backupEligible, backupState bool) error

UpdateWebAuthnBackupFlags records BE and BS flags, and is a no-op for a missing credential.

func (*Store) UpdateWebAuthnSignCount

func (s *Store) UpdateWebAuthnSignCount(ctx context.Context, credentialID []byte, newCount uint32, usedAt time.Time) error

UpdateWebAuthnSignCount writes a strictly greater count, else ErrReplayDetected or ErrStorageNotFound.

func (*Store) UpsertOAuthAccount

func (s *Store) UpsertOAuthAccount(ctx context.Context, a theauth.OAuthAccount) (theauth.OAuthAccount, error)

UpsertOAuthAccount inserts or refreshes the tokens of a (provider, provider user) pair.

func (*Store) UpsertOrganizationMember added in v0.2.0

func (s *Store) UpsertOrganizationMember(ctx context.Context, m theauth.OrganizationMember) error

UpsertOrganizationMember adds a member or updates the role of an existing one.

func (*Store) UpsertPendingTOTPSecret

func (s *Store) UpsertPendingTOTPSecret(ctx context.Context, sec theauth.TOTPSecret) error

UpsertPendingTOTPSecret writes an unconfirmed secret and leaves a confirmed one untouched.

func (*Store) UpsertSAMLIdentity added in v0.2.0

func (s *Store) UpsertSAMLIdentity(ctx context.Context, i theauth.SAMLIdentity) (theauth.SAMLIdentity, error)

UpsertSAMLIdentity inserts the (connection, NameID) identity or rebinds an existing one.

func (*Store) UserByEmail

func (s *Store) UserByEmail(ctx context.Context, email string) (*theauth.User, error)

UserByEmail returns the user with the given email, compared case-insensitively.

func (*Store) UserByEmailWithPassword

func (s *Store) UserByEmailWithPassword(ctx context.Context, email string) (*theauth.User, string, error)

UserByEmailWithPassword returns the user and their hash, empty when no password is set.

func (*Store) UserByExternalIDInOrg added in v0.2.0

func (s *Store) UserByExternalIDInOrg(ctx context.Context, orgID theauth.ULID, externalID string) (*theauth.User, error)

UserByExternalIDInOrg returns the organization member carrying the SCIM external ID.

func (*Store) UserByID

func (s *Store) UserByID(ctx context.Context, id theauth.ULID) (*theauth.User, error)

UserByID returns the user with the given ID.

func (*Store) UserPasswordHashByID

func (s *Store) UserPasswordHashByID(ctx context.Context, userID theauth.ULID) (string, error)

UserPasswordHashByID returns the stored hash, or "" when the user has none.

func (*Store) VerifyAuditChain added in v0.3.0

func (s *Store) VerifyAuditChain(ctx context.Context) (AuditChainResult, error)

VerifyAuditChain walks every chain in seq order and reports the first mismatched row. Pre-0017 rows count as Unchained; erased rows verify via their pseudonyms and count as Erased.

func (*Store) WebAuthnCredentialByCredentialID

func (s *Store) WebAuthnCredentialByCredentialID(ctx context.Context, credentialID []byte) (*theauth.WebAuthnCredential, error)

WebAuthnCredentialByCredentialID looks up a credential by its authenticator ID.

func (*Store) WebAuthnCredentialsByUserID

func (s *Store) WebAuthnCredentialsByUserID(ctx context.Context, userID theauth.ULID) ([]theauth.WebAuthnCredential, error)

WebAuthnCredentialsByUserID lists a user's credentials oldest first.

type SweepResult

type SweepResult struct {
	Sessions            int64
	MagicLinks          int64
	PasswordResetTokens int64
	TrustedDevices      int64
	SessionLinks        int64
	DeviceCodes         int64
	DeviceJoinTokens    int64
}

SweepResult counts rows removed by SweepExpired.

type ThrottleStore

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

ThrottleStore is a SQLite-backed theauth.LoginThrottleStore shared by every process using the database.

func (*ThrottleStore) CompareAndSwap

func (t *ThrottleStore) CompareAndSwap(ctx context.Context, key string, prev theauth.LoginThrottleEntry, prevExists bool, next theauth.LoginThrottleEntry) (bool, error)

CompareAndSwap writes next only when the stored entry still equals prev, or is absent when prevExists is false.

func (*ThrottleStore) Delete

func (t *ThrottleStore) Delete(ctx context.Context, key string) error

Delete removes key.

func (*ThrottleStore) DeleteLoginEntries added in v0.2.0

func (t *ThrottleStore) DeleteLoginEntries(ctx context.Context, ident string) error

DeleteLoginEntries removes every login backoff entry for ident across all client IPs.

func (*ThrottleStore) Get

Get returns the entry for key.

func (*ThrottleStore) Set

Set stores e under key unconditionally.

func (*ThrottleStore) SweepExpired

func (t *ThrottleStore) SweepExpired(ctx context.Context, now time.Time) (int, error)

SweepExpired deletes entries whose ExpiresAt is at or before now and returns how many it removed.

Jump to

Keyboard shortcuts

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