postgresql

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package postgresql implements every Credbound persistence port — Store plus the optional SessionStore, SignupStore, DomainStore, SCIMStore, EmailThrottleStore and OAuthStore capabilities — on PostgreSQL, pairing sqlc-generated database/sql queries for transactional mutations with pgx streaming for paginated reads, and committing each mutation's hash-chained audit event atomically with the change.

All objects live in the dedicated "credbound" schema; apply the module's migrations before use. Open one pgx pool and hand the store both views of it, then wire the store into credbound.Config.Store:

pool, err := pgxpool.New(ctx, dsn)
store, err := postgresql.New(stdlib.OpenDBFromPool(pool), pool)

TransactionHook callbacks can regain the raw *sql.Tx through TxFrom to append host writes to a Credbound commit.

Statements are written for PostgreSQL directly: typed uuid parameters, jsonb operators, and SELECT … FOR UPDATE for the read-then-write invariants. The transactional ones are generated by sqlc from sql/queries/postgresql.sql; the paginated reads, which sqlc cannot express, live in queries.go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*Store)

Option customizes a Store during New.

func WithStreamTimeout

func WithStreamTimeout(timeout time.Duration) Option

WithStreamTimeout overrides the 30 second per-query timeout that bounds streaming list operations. New rejects non-positive values.

type RowQuerier

type RowQuerier interface {
	Query(context.Context, string, ...any) (pgx.Rows, error)
}

RowQuerier is the pgx query surface the store streams paginated reads through; both *pgxpool.Pool and *pgx.Conn satisfy it, but only a pool is safe for concurrent use.

type Store

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

Store is the PostgreSQL-backed implementation of the Credbound persistence ports. It is safe for concurrent use: mutations run inside transactions that commit the audit event atomically with the change, and list operations stream rows under a per-query timeout (WithStreamTimeout). Method semantics, sentinel errors and pagination behavior are specified on the credbound port interfaces.

func New

func New(database *sql.DB, rows RowQuerier, options ...Option) (*Store, error)

New builds the PostgreSQL store from two views of the same database: a *sql.DB used by the sqlc-generated queries for transactional mutations (open one with pgx's stdlib.OpenDB or stdlib.OpenDBFromPool), and a pgx RowQuerier used to stream paginated reads. In production pass a *pgxpool.Pool as the RowQuerier — a single *pgx.Conn is not safe for concurrent use.

func (*Store) AcceptWorkspaceInvitation

func (s *Store) AcceptWorkspaceInvitation(ctx context.Context, invitationID, userID credbound.UUID, at time.Time, membership credbound.Membership, commit credbound.Commit) error

AcceptWorkspaceInvitation marks the invitation accepted by the user and installs the resulting membership in the same commit; an accepted or revoked invitation reports credbound.ErrConflict.

func (*Store) AcceptedWorkspaceInvitations

func (s *Store) AcceptedWorkspaceInvitations(ctx context.Context, userID credbound.UUID) iter.Seq2[credbound.WorkspaceInvitation, error]

AcceptedWorkspaceInvitations streams every invitation the user accepted, oldest first, for the PrivacyStore capability.

func (*Store) ActivateTOTP

func (s *Store) ActivateTOTP(ctx context.Context, factor credbound.TOTPFactor, recovery []credbound.RecoveryCode, commit credbound.Commit) error

ActivateTOTP activates the pending factor and stores its recovery codes in the same commit.

func (*Store) AdoptSCIMUser

func (s *Store) AdoptSCIMUser(ctx context.Context, membership credbound.Membership, link credbound.SCIMUser, commit credbound.Commit) error

AdoptSCIMUser links a directory user to an existing Credbound account, installing the membership in the same commit.

func (*Store) AnonymizeUser

func (s *Store) AnonymizeUser(ctx context.Context, userID credbound.UUID, at time.Time, commit credbound.Commit) error

AnonymizeUser pseudonymizes a user: it scrubs the mutable personal data, disables the account, revokes every credential and removes the second factors, all in the audit commit's transaction, while the append-only audit chain is preserved. Disabling the last enabled root or a sole workspace admin reports ErrConflict, exactly like SetUserDisabled.

func (*Store) AppendAudit

func (s *Store) AppendAudit(ctx context.Context, commit credbound.Commit) error

AppendAudit commits a standalone audit event (and any transactional hook) without another mutation.

func (*Store) AuditChainHead

func (s *Store) AuditChainHead(ctx context.Context) (int64, []byte, error)

AuditChainHead returns the sequence number and hash of the latest chained audit event.

func (*Store) AuditEvents

AuditEvents streams the workspace's audit events, newest first, as one cursor page.

func (*Store) Bootstrap

Bootstrap atomically creates the first user with its primary email, password, workspace, admin membership and root administrator; once the instance is populated it reports credbound.ErrConflict.

func (*Store) ChainedAuditEvents

func (s *Store) ChainedAuditEvents(ctx context.Context, afterSequence int64) iter.Seq2[credbound.AuditEvent, error]

ChainedAuditEvents streams every chained audit event in sequence order for verification with credbound.VerifyAuditChain.

func (*Store) ChangePassword

func (s *Store) ChangePassword(ctx context.Context, password credbound.PasswordCredential, at time.Time, commit credbound.Commit) error

ChangePassword swaps the user's password credential and stamps their active sessions revoked in the same transaction.

func (*Store) ClaimEmailIssuance

func (s *Store) ClaimEmailIssuance(ctx context.Context, address, purpose string, at, notBefore time.Time) (bool, error)

ClaimEmailIssuance atomically records an email issuance for (address, purpose) and reports whether it was allowed: it claims only when no earlier issuance is newer than notBefore, so a caller gets at most one send per cooldown window. Rows older than notBefore no longer throttle anything and are pruned on every claim, so anonymous traffic cannot grow the table beyond the current cooldown window. It is rate-limit bookkeeping keyed by an opaque digest regardless of account existence, so it opens no audit transaction and leaks nothing.

func (*Store) CompletePasswordReset

func (s *Store) CompletePasswordReset(ctx context.Context, resetID credbound.UUID, password credbound.PasswordCredential, at time.Time, commit credbound.Commit) error

CompletePasswordReset consumes the reset and installs the password — the account's first, for a passwordless member provisioned by SSO JIT or SCIM — revoking the user's other pending resets, tokens, sessions and throttle in the same commit; a reused reset reports credbound.ErrConflict.

func (*Store) ConfirmWorkspaceDomain

func (s *Store) ConfirmWorkspaceDomain(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

ConfirmWorkspaceDomain marks the domain verified; confirming twice reports credbound.ErrConflict.

func (*Store) ConfirmedWorkspaceDomainByName

func (s *Store) ConfirmedWorkspaceDomainByName(ctx context.Context, name string) (credbound.WorkspaceDomain, error)

ConfirmedWorkspaceDomainByName resolves a confirmed domain by name; unknown or unconfirmed domains report credbound.ErrNotFound.

func (*Store) ConsumeEmailAuthentication

func (s *Store) ConsumeEmailAuthentication(ctx context.Context, tokenID, userID credbound.UUID, at time.Time, completesLogin bool, commit credbound.Commit) error

ConsumeEmailAuthentication marks the user's credential used and, when the consumption completes the sign-in, updates last-seen and clears the login throttle; reuse reports credbound.ErrConflict.

func (*Store) ConsumeOAuthAuthorizationCode

func (s *Store) ConsumeOAuthAuthorizationCode(ctx context.Context, codeID credbound.UUID, usedAt time.Time, access credbound.OAuthAccessToken, refresh *credbound.OAuthRefreshToken, commit credbound.Commit) error

ConsumeOAuthAuthorizationCode atomically marks the single-use code consumed and stores the access and optional refresh token it was exchanged for.

func (*Store) ConsumeRecoveryCode

func (s *Store) ConsumeRecoveryCode(ctx context.Context, userID credbound.UUID, digest []byte, usedAt time.Time, commit credbound.Commit) (bool, error)

ConsumeRecoveryCode marks the matching unused recovery code used, reporting false when no unused code matches the digest.

func (*Store) CountUnusedRecoveryCodes

func (s *Store) CountUnusedRecoveryCodes(ctx context.Context, userID credbound.UUID) (int64, error)

CountUnusedRecoveryCodes reports how many of the user's recovery codes remain unused.

func (*Store) CreateEmailAuthentication

func (s *Store) CreateEmailAuthentication(ctx context.Context, credential credbound.EmailAuthenticationCredential, commit credbound.Commit) error

CreateEmailAuthentication stores a single-use magic-link or email OTP credential.

func (*Store) CreateOAuthClient

func (s *Store) CreateOAuthClient(ctx context.Context, value credbound.OAuthClient, initialID credbound.UUID, usedAt time.Time, commit credbound.Commit) error

CreateOAuthClient stores a dynamically registered client, consuming a use of the initial access token in the same commit when one gated the registration.

func (*Store) CreateOAuthClientAccessToken

func (s *Store) CreateOAuthClientAccessToken(ctx context.Context, value credbound.OAuthClientAccessToken, commit credbound.Commit) error

CreateOAuthClientAccessToken stores a client-credentials access token.

func (*Store) CreateOAuthGrantAndCode

func (s *Store) CreateOAuthGrantAndCode(ctx context.Context, grant credbound.OAuthGrant, code credbound.OAuthAuthorizationCode, commit credbound.Commit) error

CreateOAuthGrantAndCode atomically stores a user grant with its single-use authorization code.

func (*Store) CreateOAuthInitialAccessToken

func (s *Store) CreateOAuthInitialAccessToken(ctx context.Context, value credbound.OAuthInitialAccessToken, commit credbound.Commit) error

CreateOAuthInitialAccessToken stores an initial access token for gated dynamic client registration.

func (*Store) CreateOAuthIssuer

func (s *Store) CreateOAuthIssuer(ctx context.Context, value credbound.OAuthIssuer, commit credbound.Commit) error

CreateOAuthIssuer stores an authorization server issuer; a duplicate ID or URL reports credbound.ErrConflict.

func (*Store) CreateOAuthProtectedResource

func (s *Store) CreateOAuthProtectedResource(ctx context.Context, value credbound.OAuthProtectedResource, commit credbound.Commit) error

CreateOAuthProtectedResource stores a protected resource; a duplicate ID or URI reports credbound.ErrConflict.

func (*Store) CreatePAT

func (s *Store) CreatePAT(ctx context.Context, pat credbound.PAT, commit credbound.Commit) error

CreatePAT stores a personal access token record; a duplicate ID or prefix reports credbound.ErrConflict.

func (*Store) CreatePasswordReset

func (s *Store) CreatePasswordReset(ctx context.Context, credential credbound.PasswordResetCredential, commit credbound.Commit) error

CreatePasswordReset stores a single-use password reset credential.

func (*Store) CreateSCIMConfiguration

func (s *Store) CreateSCIMConfiguration(ctx context.Context, configuration credbound.SCIMConfiguration, credential credbound.SCIMCredential, commit credbound.Commit) error

CreateSCIMConfiguration stores a workspace's SCIM configuration together with its first bearer credential.

func (*Store) CreateSCIMUser

func (s *Store) CreateSCIMUser(ctx context.Context, user credbound.User, email credbound.EmailAddress, membership credbound.Membership, link credbound.SCIMUser, commit credbound.Commit) error

CreateSCIMUser atomically creates the Credbound user, email and membership for a directory user and links them to the SCIM record.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, session credbound.Session, credentialDigest []byte, commit credbound.Commit) error

CreateSession stores a server-side session; a duplicate ID reports credbound.ErrConflict. A non-empty credentialDigest must still fingerprint the user's current password credential, so a session can never be minted from an authentication whose password was concurrently replaced; a mismatch (or a vanished credential) reports credbound.ErrConflict.

func (*Store) CreateSignup

func (s *Store) CreateSignup(ctx context.Context, user credbound.User, email credbound.EmailAddress, verification *credbound.EmailVerificationCredential, password credbound.PasswordCredential, workspace credbound.Workspace, membership credbound.Membership, commit credbound.Commit) error

CreateSignup atomically creates a self-service user, its primary email (with the optional pending verification), password credential and fresh workspace; an unverified address stays excluded from sign-in lookup until VerifyEmail.

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, user credbound.User, email credbound.EmailAddress, password credbound.PasswordCredential, membership credbound.Membership, commit credbound.Commit) error

CreateUser inserts a user with a primary email, password credential and initial membership in an existing workspace; a duplicate user ID or email address reports credbound.ErrConflict.

func (*Store) CreateWorkspace

func (s *Store) CreateWorkspace(ctx context.Context, workspace credbound.Workspace, owner credbound.Membership, commit credbound.Commit) error

CreateWorkspace inserts a workspace together with its owning membership.

func (*Store) CreateWorkspaceDomain

func (s *Store) CreateWorkspaceDomain(ctx context.Context, domain credbound.WorkspaceDomain, staleBefore time.Time, commit credbound.Commit) error

CreateWorkspaceDomain stores an unconfirmed domain claim; a domain already claimed by any workspace reports credbound.ErrConflict, except that a stale pending claim — still unconfirmed and created before staleBefore — lost its reservation and is replaced in the same transaction.

func (*Store) CreateWorkspaceInvitation

func (s *Store) CreateWorkspaceInvitation(ctx context.Context, invitation credbound.WorkspaceInvitation, commit credbound.Commit) error

CreateWorkspaceInvitation stores an invitation; a pending invitation for the same address in the workspace reports credbound.ErrConflict.

func (*Store) DeletePasskey

func (s *Store) DeletePasskey(ctx context.Context, userID, passkeyID credbound.UUID, commit credbound.Commit) error

DeletePasskey removes one of the user's passkeys.

func (*Store) DeleteSCIMGroup

func (s *Store) DeleteSCIMGroup(ctx context.Context, group credbound.SCIMGroup, memberships []credbound.Membership, commit credbound.Commit) error

DeleteSCIMGroup soft-deletes the group and applies the recomputed memberships in the same commit.

func (*Store) DeleteWorkspaceDomain

func (s *Store) DeleteWorkspaceDomain(ctx context.Context, id credbound.UUID, commit credbound.Commit) error

DeleteWorkspaceDomain removes the domain claim.

func (*Store) DisableSCIMConfiguration

func (s *Store) DisableSCIMConfiguration(ctx context.Context, id credbound.UUID, disabledAt time.Time, commit credbound.Commit) error

DisableSCIMConfiguration marks the configuration disabled so its credentials stop authenticating.

func (*Store) DisableTOTP

func (s *Store) DisableTOTP(ctx context.Context, userID credbound.UUID, commit credbound.Commit) error

DisableTOTP removes the user's TOTP factor and recovery codes.

func (*Store) EmailAuthenticationByID

func (s *Store) EmailAuthenticationByID(ctx context.Context, tokenID credbound.UUID) (credbound.EmailAuthenticationCredential, error)

EmailAuthenticationByID returns the email authentication credential with the given token ID.

func (*Store) EmailByAddress

func (s *Store) EmailByAddress(ctx context.Context, address string) (credbound.EmailAddress, error)

EmailByAddress returns the address record for a canonical address, without its verification credential. It reports credbound.ErrNotFound when no address matches.

func (*Store) EmailVerificationByID

EmailVerificationByID returns the email address and its pending verification credential.

func (*Store) Emails

Emails streams the user's email addresses, newest first, as one cursor page.

func (*Store) InstanceAdministrator

func (s *Store) InstanceAdministrator(ctx context.Context, userID credbound.UUID) (credbound.InstanceAdministrator, error)

InstanceAdministrator returns the user's instance-administration role.

func (*Store) InstanceAdministrators

func (s *Store) InstanceAdministrators(ctx context.Context) iter.Seq2[credbound.InstanceAdministrator, error]

InstanceAdministrators streams every instance role assignment, oldest first.

func (*Store) InstanceAuditEvents

InstanceAuditEvents streams audit events across the whole instance, newest first, as one cursor page.

func (*Store) JITProvisionSSOUser

func (s *Store) JITProvisionSSOUser(ctx context.Context, user credbound.User, email credbound.EmailAddress, membership credbound.Membership, identity credbound.SSOIdentity, _ time.Time, commit credbound.Commit) error

JITProvisionSSOUser atomically creates a user with a verified email, workspace membership and linked SSO identity for domain-based just-in-time provisioning.

func (*Store) LinkSSO

func (s *Store) LinkSSO(ctx context.Context, identity credbound.SSOIdentity, commit credbound.Commit) error

LinkSSO stores a new SSO identity link; an identity already linked to any user reports credbound.ErrConflict. A link carrying LastUsedAt records a completed sign-in, so it also updates last-seen and clears the login throttle.

func (*Store) LoginThrottleByUserID

func (s *Store) LoginThrottleByUserID(ctx context.Context, userID credbound.UUID) (credbound.LoginThrottle, error)

LoginThrottleByUserID returns the user's current login throttle state.

func (*Store) Membership

func (s *Store) Membership(ctx context.Context, workspaceID, userID credbound.UUID) (credbound.Membership, error)

Membership returns the user's membership in the workspace.

func (*Store) Memberships

Memberships streams the workspace's memberships, newest first, as one cursor page.

func (*Store) OAuthAccessTokenByPrefix

func (s *Store) OAuthAccessTokenByPrefix(ctx context.Context, prefix string) (credbound.OAuthAccessToken, error)

OAuthAccessTokenByPrefix returns the access token record addressed by its lookup prefix.

func (*Store) OAuthAuthorizationCodeByPrefix

func (s *Store) OAuthAuthorizationCodeByPrefix(ctx context.Context, prefix string) (credbound.OAuthAuthorizationCode, error)

OAuthAuthorizationCodeByPrefix returns the authorization code record addressed by its lookup prefix.

func (*Store) OAuthClientAccessTokenByPrefix

func (s *Store) OAuthClientAccessTokenByPrefix(ctx context.Context, prefix string) (credbound.OAuthClientAccessToken, error)

OAuthClientAccessTokenByPrefix returns the client-credentials access token addressed by its lookup prefix.

func (*Store) OAuthClientByClientID

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

OAuthClientByClientID resolves the issuer's client by its OAuth client_id.

func (*Store) OAuthClientByID

func (s *Store) OAuthClientByID(ctx context.Context, id credbound.UUID) (credbound.OAuthClient, error)

OAuthClientByID returns the client with the given record ID.

func (*Store) OAuthClients

OAuthClients streams the issuer's clients, newest first, as one cursor page.

func (*Store) OAuthGrant

func (s *Store) OAuthGrant(ctx context.Context, id credbound.UUID) (credbound.OAuthGrant, error)

OAuthGrant returns the grant with the given ID.

func (*Store) OAuthGrants

func (s *Store) OAuthGrants(ctx context.Context, userID, workspaceID credbound.UUID, page credbound.PageRequest) iter.Seq2[credbound.PageEvent[credbound.OAuthGrant], error]

OAuthGrants streams grants, optionally filtered by user and workspace, newest first, as one cursor page.

func (*Store) OAuthInitialAccessTokenByPrefix

func (s *Store) OAuthInitialAccessTokenByPrefix(ctx context.Context, prefix string) (credbound.OAuthInitialAccessToken, error)

OAuthInitialAccessTokenByPrefix returns the token record addressed by its lookup prefix.

func (*Store) OAuthInitialAccessTokens

func (s *Store) OAuthInitialAccessTokens(ctx context.Context, issuerID credbound.UUID) iter.Seq2[credbound.OAuthInitialAccessToken, error]

OAuthInitialAccessTokens streams the issuer's DCR bootstrap credentials, oldest first, revoked ones included and digests omitted.

func (*Store) OAuthIssuerByID

func (s *Store) OAuthIssuerByID(ctx context.Context, id credbound.UUID) (credbound.OAuthIssuer, error)

OAuthIssuerByID returns the issuer with the given ID.

func (*Store) OAuthIssuerByURL

func (s *Store) OAuthIssuerByURL(ctx context.Context, issuer string) (credbound.OAuthIssuer, error)

OAuthIssuerByURL resolves an issuer by its canonical URL.

func (*Store) OAuthIssuers

OAuthIssuers streams all issuers, newest first, as one cursor page.

func (*Store) OAuthProtectedResourceByID

func (s *Store) OAuthProtectedResourceByID(ctx context.Context, id credbound.UUID) (credbound.OAuthProtectedResource, error)

OAuthProtectedResourceByID returns the resource with the given ID.

func (*Store) OAuthProtectedResourceByURI

func (s *Store) OAuthProtectedResourceByURI(ctx context.Context, resource string) (credbound.OAuthProtectedResource, error)

OAuthProtectedResourceByURI resolves a resource by its canonical URI.

func (*Store) OAuthProtectedResources

func (s *Store) OAuthProtectedResources(ctx context.Context, workspaceID credbound.UUID, page credbound.PageRequest) iter.Seq2[credbound.PageEvent[credbound.OAuthProtectedResource], error]

OAuthProtectedResources streams resources, optionally filtered by workspace, newest first, as one cursor page.

func (*Store) OAuthRefreshTokenByPrefix

func (s *Store) OAuthRefreshTokenByPrefix(ctx context.Context, prefix string) (credbound.OAuthRefreshToken, error)

OAuthRefreshTokenByPrefix returns the refresh token record addressed by its lookup prefix.

func (*Store) PATByID added in v0.0.4

func (s *Store) PATByID(ctx context.Context, id credbound.UUID) (credbound.PAT, error)

PATs streams the user's tokens, newest first, as one cursor page with digests omitted. PATByID returns one token by identifier.

func (*Store) PATByPrefix

func (s *Store) PATByPrefix(ctx context.Context, prefix string) (credbound.PAT, error)

PATByPrefix returns the token record addressed by its lookup prefix.

func (*Store) PATs

func (*Store) PasskeyByCredentialID

func (s *Store) PasskeyByCredentialID(ctx context.Context, credentialID []byte) (credbound.Passkey, error)

PasskeyByCredentialID returns the passkey owning the credential ID, for discoverable (usernameless) authentication.

func (*Store) Passkeys

func (s *Store) Passkeys(ctx context.Context, userID credbound.UUID) iter.Seq2[credbound.Passkey, error]

Passkeys streams the user's passkeys in creation order.

func (*Store) PasswordByUserID

func (s *Store) PasswordByUserID(ctx context.Context, userID credbound.UUID) (credbound.PasswordCredential, error)

PasswordByUserID returns the user's stored password credential.

func (*Store) PasswordResetByID

func (s *Store) PasswordResetByID(ctx context.Context, resetID credbound.UUID) (credbound.PasswordResetCredential, error)

PasswordResetByID returns the password reset credential with the given ID.

func (*Store) PendingWorkspaceInvitation

func (s *Store) PendingWorkspaceInvitation(ctx context.Context, workspaceID credbound.UUID, email string) (credbound.WorkspaceInvitation, error)

PendingWorkspaceInvitation returns the workspace's unaccepted, unrevoked invitation for the email address.

func (*Store) RecordAuthentication

func (s *Store) RecordAuthentication(ctx context.Context, userID credbound.UUID, seenAt time.Time, commit credbound.Commit) error

RecordAuthentication marks a successful login, updating the user's last- seen time and clearing any login throttle.

func (*Store) RecordLoginFailure

func (s *Store) RecordLoginFailure(ctx context.Context, userID credbound.UUID, at time.Time, threshold int64, lockedUntil time.Time, commit credbound.Commit) (credbound.LoginThrottle, error)

RecordLoginFailure counts a failed login (restarting the window after an expired lockout) and applies lockedUntil once the failure threshold is reached, returning the updated throttle.

func (*Store) RecordPasswordAuthentication

func (s *Store) RecordPasswordAuthentication(ctx context.Context, userID credbound.UUID, currentHash string, seenAt time.Time, commit credbound.Commit) error

RecordPasswordAuthentication marks a successful password login like RecordAuthentication, but only while currentHash is still the stored credential; a credential that moved or vanished reports credbound.ErrConflict and rolls the transaction back.

func (*Store) RegisterInvitedUser

func (s *Store) RegisterInvitedUser(ctx context.Context, invitationID credbound.UUID, user credbound.User, email credbound.EmailAddress, password credbound.PasswordCredential, membership credbound.Membership, at time.Time, commit credbound.Commit) error

RegisterInvitedUser atomically creates the invited user with email, password and membership while accepting the invitation.

func (*Store) RehashPassword

func (s *Store) RehashPassword(ctx context.Context, password credbound.PasswordCredential, previousHash string, commit credbound.Commit) error

RehashPassword swaps the user's password credential only while the hash the verification ran against is still in place; a concurrent replacement (or a vanished credential) reports credbound.ErrConflict and leaves the store untouched.

func (*Store) ReissueEmailVerification

func (s *Store) ReissueEmailVerification(ctx context.Context, emailID credbound.UUID, verification credbound.EmailVerificationCredential, commit credbound.Commit) error

ReissueEmailVerification replaces the pending verification credential of an unverified address (a fresh digest and expiry); an already-verified or missing address reports credbound.ErrConflict.

func (*Store) RemoveEmail

func (s *Store) RemoveEmail(ctx context.Context, userID, emailID credbound.UUID, commit credbound.Commit) error

RemoveEmail deletes a non-primary address, refusing to remove the user's last verified one (credbound.ErrConflict).

func (*Store) RemoveInstanceRole

func (s *Store) RemoveInstanceRole(ctx context.Context, userID credbound.UUID, commit credbound.Commit) error

RemoveInstanceRole revokes the user's instance role, refusing to remove the last root administrator (credbound.ErrConflict).

func (*Store) RemoveMembership

func (s *Store) RemoveMembership(ctx context.Context, workspaceID, userID credbound.UUID, at time.Time, commit credbound.Commit) error

RemoveMembership deletes the membership, refusing to remove the workspace's last active admin (credbound.ErrConflict) and revoking the member's workspace-scoped tokens.

func (*Store) ReplaceRecoveryCodes

func (s *Store) ReplaceRecoveryCodes(ctx context.Context, userID credbound.UUID, codes []credbound.RecoveryCode, commit credbound.Commit) error

ReplaceRecoveryCodes atomically deletes the user's recovery codes and inserts the replacement set; without an active TOTP factor it reports credbound.ErrNotFound.

func (*Store) ResetSecondFactor

func (s *Store) ResetSecondFactor(ctx context.Context, userID credbound.UUID, at time.Time, commit credbound.Commit) error

ResetSecondFactor removes the user's TOTP factor with its recovery codes and every passkey, and revokes the user's active sessions, in one transaction. It succeeds even when no second factor exists; an unknown user reports credbound.ErrNotFound.

func (*Store) RevokeOAuthAccessToken

func (s *Store) RevokeOAuthAccessToken(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeOAuthAccessToken marks the access token revoked.

func (*Store) RevokeOAuthClientAccessToken

func (s *Store) RevokeOAuthClientAccessToken(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeOAuthClientAccessToken marks the client-credentials access token revoked.

func (*Store) RevokeOAuthGrant

func (s *Store) RevokeOAuthGrant(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeOAuthGrant revokes the grant together with its outstanding access and refresh tokens.

func (*Store) RevokeOAuthInitialAccessToken

func (s *Store) RevokeOAuthInitialAccessToken(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeOAuthInitialAccessToken marks the token revoked.

func (*Store) RevokeOAuthRefreshFamily

func (s *Store) RevokeOAuthRefreshFamily(ctx context.Context, familyID credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeOAuthRefreshFamily revokes every token in the refresh-token family and the access tokens of the grants the family descends from, the fail-safe response to detected refresh token reuse: the thief's already- minted access token must die with the family, not survive until expiry.

func (*Store) RevokePAT

func (s *Store) RevokePAT(ctx context.Context, userID, id credbound.UUID, revokedAt time.Time, commit credbound.Commit) error

RevokePAT marks the user's token revoked.

func (*Store) RevokeSCIMCredential

func (s *Store) RevokeSCIMCredential(ctx context.Context, configurationID, id credbound.UUID, revokedAt time.Time, commit credbound.Commit) error

RevokeSCIMCredential marks the configuration's credential revoked.

func (*Store) RevokeSession

func (s *Store) RevokeSession(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeSession marks the session revoked; an already-revoked session is left unchanged.

func (*Store) RevokeUserCredentials

func (s *Store) RevokeUserCredentials(ctx context.Context, userID credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeUserCredentials revokes all of the user's tokens (PATs and OAuth) and sessions in one commit.

func (*Store) RevokeUserSessions

func (s *Store) RevokeUserSessions(ctx context.Context, userID credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeUserSessions revokes every session of the user.

func (*Store) RevokeWorkspaceInvitation

func (s *Store) RevokeWorkspaceInvitation(ctx context.Context, workspaceID, invitationID credbound.UUID, at time.Time, commit credbound.Commit) error

RevokeWorkspaceInvitation marks the workspace's invitation revoked; an accepted or already-revoked invitation reports credbound.ErrConflict.

func (*Store) RotateOAuthClientCredentials

func (s *Store) RotateOAuthClientCredentials(ctx context.Context, id credbound.UUID, secretDigest, jwks, metadataHash []byte, at time.Time, commit credbound.Commit) error

RotateOAuthClientCredentials replaces the client's secret digest and/or inline JWKS (with its recomputed metadata hash) after an administrative credential rotation.

func (*Store) RotateOAuthRefreshToken

func (s *Store) RotateOAuthRefreshToken(ctx context.Context, previousID credbound.UUID, usedAt time.Time, access credbound.OAuthAccessToken, refresh credbound.OAuthRefreshToken, commit credbound.Commit) error

RotateOAuthRefreshToken atomically retires the used refresh token and stores its successor pair, keeping the family linked for reuse detection.

func (*Store) SCIMConfiguration

func (s *Store) SCIMConfiguration(ctx context.Context, id credbound.UUID) (credbound.SCIMConfiguration, error)

SCIMConfiguration returns the configuration with the given ID.

func (*Store) SCIMConfigurationByCredentialPrefix

func (s *Store) SCIMConfigurationByCredentialPrefix(ctx context.Context, prefix string) (credbound.SCIMConfiguration, credbound.SCIMCredential, error)

SCIMConfigurationByCredentialPrefix resolves the configuration and credential addressed by a bearer token's lookup prefix.

func (*Store) SCIMConfigurations

func (s *Store) SCIMConfigurations(ctx context.Context, workspaceID credbound.UUID) iter.Seq2[credbound.SCIMConfiguration, error]

SCIMConfigurations streams the workspace's provisioning domains, oldest first.

func (*Store) SCIMCredentials

func (s *Store) SCIMCredentials(ctx context.Context, configurationID credbound.UUID) iter.Seq2[credbound.SCIMCredential, error]

SCIMCredentials streams the configuration's bearer credentials, oldest first, with digests omitted.

func (*Store) SCIMGroup

func (s *Store) SCIMGroup(ctx context.Context, configurationID, id credbound.UUID) (credbound.SCIMGroup, error)

SCIMGroup returns the configuration's group with the given ID.

func (*Store) SCIMGroupByExternalID

func (s *Store) SCIMGroupByExternalID(ctx context.Context, configurationID credbound.UUID, externalID string) (credbound.SCIMGroup, error)

SCIMGroupByExternalID resolves the configuration's group by its directory external ID.

func (*Store) SCIMGroups

SCIMGroups streams the configuration's groups matching the filter, newest first, as one cursor page.

func (*Store) SCIMUser

func (s *Store) SCIMUser(ctx context.Context, configurationID, id credbound.UUID) (credbound.SCIMUser, error)

SCIMUser returns the configuration's SCIM user with the given ID.

func (*Store) SCIMUserByExternalID

func (s *Store) SCIMUserByExternalID(ctx context.Context, configurationID credbound.UUID, externalID string) (credbound.SCIMUser, error)

SCIMUserByExternalID resolves the configuration's SCIM user by its directory external ID.

func (*Store) SCIMUserByUserName

func (s *Store) SCIMUserByUserName(ctx context.Context, configurationID credbound.UUID, userName string) (credbound.SCIMUser, error)

SCIMUserByUserName resolves the configuration's SCIM user by normalized userName.

func (*Store) SCIMUsers

SCIMUsers streams the configuration's users matching the filter, newest first, as one cursor page.

func (*Store) SCIMUsersByUser

func (s *Store) SCIMUsersByUser(ctx context.Context, userID credbound.UUID) iter.Seq2[credbound.SCIMUser, error]

SCIMUsersByUser streams every tenant-scoped SCIM profile linked to the user across configurations, oldest first, for the PrivacyStore capability.

func (*Store) SSOIdentities

SSOIdentities streams the user's SSO identity links, newest first, as one cursor page.

func (*Store) SSOIdentity

func (s *Store) SSOIdentity(ctx context.Context, providerConfigurationID credbound.UUID, issuer, subject string) (credbound.SSOIdentity, error)

SSOIdentity resolves a linked identity by provider configuration, issuer and subject.

func (*Store) SaveEmail

func (s *Store) SaveEmail(ctx context.Context, email credbound.EmailAddress, verification credbound.EmailVerificationCredential, commit credbound.Commit) error

SaveEmail adds an additional email address with its pending verification credential; a duplicate address reports credbound.ErrConflict.

func (*Store) SavePasskey

func (s *Store) SavePasskey(ctx context.Context, passkey credbound.Passkey, commit credbound.Commit) error

SavePasskey stores a new passkey; a credential ID already registered to any user reports credbound.ErrConflict.

func (*Store) SaveSCIMCredential

func (s *Store) SaveSCIMCredential(ctx context.Context, credential credbound.SCIMCredential, commit credbound.Commit) error

SaveSCIMCredential stores an additional bearer credential for a configuration.

func (*Store) SaveTOTPEnrollment

func (s *Store) SaveTOTPEnrollment(ctx context.Context, factor credbound.TOTPFactor, commit credbound.Commit) error

SaveTOTPEnrollment stores a pending TOTP factor, replacing any prior pending enrollment; an already-active factor reports credbound.ErrConflict.

func (*Store) SessionByID

func (s *Store) SessionByID(ctx context.Context, id credbound.UUID) (credbound.Session, error)

SessionByID returns the session with the given ID.

func (*Store) Sessions

Sessions streams the user's sessions, newest first, as one cursor page with digests omitted.

func (*Store) SetInstanceRole

func (s *Store) SetInstanceRole(ctx context.Context, admin credbound.InstanceAdministrator, commit credbound.Commit) error

SetInstanceRole grants or changes a user's instance role, refusing to demote the last root administrator (credbound.ErrConflict).

func (*Store) SetOAuthClientDisabled

func (s *Store) SetOAuthClientDisabled(ctx context.Context, id credbound.UUID, disabled bool, at time.Time, commit credbound.Commit) error

SetOAuthClientDisabled enables or disables the client.

func (*Store) SetOAuthIssuerDisabled

func (s *Store) SetOAuthIssuerDisabled(ctx context.Context, id credbound.UUID, disabled bool, at time.Time, commit credbound.Commit) error

SetOAuthIssuerDisabled enables or disables the issuer.

func (*Store) SetOAuthProtectedResourceDisabled

func (s *Store) SetOAuthProtectedResourceDisabled(ctx context.Context, id credbound.UUID, disabled bool, at time.Time, commit credbound.Commit) error

SetOAuthProtectedResourceDisabled enables or disables the resource.

func (*Store) SetPrimaryEmail

func (s *Store) SetPrimaryEmail(ctx context.Context, userID, emailID credbound.UUID, commit credbound.Commit) error

SetPrimaryEmail promotes a verified address to primary and demotes the previous one; an unverified target reports credbound.ErrConflict.

func (*Store) SetUserDisabled

func (s *Store) SetUserDisabled(ctx context.Context, userID credbound.UUID, disabled bool, at time.Time, commit credbound.Commit) error

SetUserDisabled enables or disables a user; disabling refuses to orphan the last enabled root administrator or a workspace's last active admin (credbound.ErrConflict) and revokes the user's tokens and sessions.

func (*Store) SetWorkspaceDisabled

func (s *Store) SetWorkspaceDisabled(ctx context.Context, workspaceID credbound.UUID, disabled bool, at time.Time, commit credbound.Commit) error

SetWorkspaceDisabled enables or disables the workspace; disabling revokes the members' workspace-scoped tokens.

func (*Store) TOTPByUserID

func (s *Store) TOTPByUserID(ctx context.Context, userID credbound.UUID) (credbound.TOTPFactor, error)

TOTPByUserID returns the user's TOTP factor.

func (*Store) TouchPAT

func (s *Store) TouchPAT(ctx context.Context, id credbound.UUID, usedAt time.Time, commit credbound.Commit) error

TouchPAT records a token use, updating the token's and user's last-seen times.

func (*Store) TouchPasskey

func (s *Store) TouchPasskey(ctx context.Context, userID credbound.UUID, credentialID, credentialJSON []byte, usedAt time.Time, commit credbound.Commit) error

TouchPasskey persists the credential's updated JSON (sign counter) and last-used time after a successful assertion, updating last-seen and — the sign-in completed — clearing the login throttle.

func (*Store) TouchSCIMCredential

func (s *Store) TouchSCIMCredential(ctx context.Context, id credbound.UUID, usedAt time.Time, commit credbound.Commit) error

TouchSCIMCredential records a successful use of the credential.

func (*Store) TouchSSO

func (s *Store) TouchSSO(ctx context.Context, userID, identityID credbound.UUID, usedAt time.Time, commit credbound.Commit) error

TouchSSO updates the identity's last-used time and the user's last-seen time after a successful SSO login, clearing the login throttle in the same commit.

func (*Store) TouchSession

func (s *Store) TouchSession(ctx context.Context, id credbound.UUID, at time.Time, commit credbound.Commit) error

TouchSession updates the session's and user's last-seen times. A session already revoked reports credbound.ErrConflict, so an authentication racing a revocation can neither record activity on nor extend the idle window of a dead session.

func (*Store) UnlinkSSO

func (s *Store) UnlinkSSO(ctx context.Context, userID, identityID credbound.UUID, commit credbound.Commit) error

UnlinkSSO removes the user's SSO identity link.

func (*Store) UpdateOAuthIssuer

func (s *Store) UpdateOAuthIssuer(ctx context.Context, value credbound.OAuthIssuer, commit credbound.Commit) error

UpdateOAuthIssuer persists the issuer's mutable attributes.

func (*Store) UpdateSCIMConfiguration

func (s *Store) UpdateSCIMConfiguration(ctx context.Context, configuration credbound.SCIMConfiguration, memberships []credbound.Membership, commit credbound.Commit) error

UpdateSCIMConfiguration persists the configuration's settings and applies the recomputed memberships in the same commit.

func (*Store) UpdateSCIMUser

func (s *Store) UpdateSCIMUser(ctx context.Context, link credbound.SCIMUser, membership credbound.Membership, revokeWorkspacePATs bool, commit credbound.Commit) error

UpdateSCIMUser persists the directory record and membership change, optionally revoking the user's workspace PATs on deactivation.

func (*Store) UpdateUser

func (s *Store) UpdateUser(ctx context.Context, user credbound.User, commit credbound.Commit) error

UpdateUser persists the user's mutable profile fields.

func (*Store) UpdateWorkspace

func (s *Store) UpdateWorkspace(ctx context.Context, workspace credbound.Workspace, commit credbound.Commit) error

UpdateWorkspace persists the workspace's mutable attributes.

func (*Store) UpdateWorkspaceDomainPolicy

func (s *Store) UpdateWorkspaceDomainPolicy(ctx context.Context, id credbound.UUID, policy credbound.WorkspaceDomainPolicyInput, at time.Time, commit credbound.Commit) error

UpdateWorkspaceDomainPolicy replaces the auto-join and SSO-enforcement policy of a confirmed domain; an unconfirmed domain reports credbound.ErrConflict.

func (*Store) UpsertMembership

func (s *Store) UpsertMembership(ctx context.Context, membership credbound.Membership, commit credbound.Commit) error

UpsertMembership inserts or updates a membership, refusing a change that would leave the workspace without an active admin (credbound.ErrConflict); deactivation revokes the member's workspace-scoped tokens.

func (*Store) UpsertOAuthCIMDClient

func (s *Store) UpsertOAuthCIMDClient(ctx context.Context, value credbound.OAuthClient, commit credbound.Commit) error

UpsertOAuthCIMDClient inserts or refreshes a client registered through a Client Identifier Metadata Document.

func (*Store) UpsertSCIMGroup

func (s *Store) UpsertSCIMGroup(ctx context.Context, group credbound.SCIMGroup, memberships []credbound.Membership, commit credbound.Commit) error

UpsertSCIMGroup inserts or replaces a directory group and applies the recomputed memberships in the same commit.

func (*Store) UseTOTP

func (s *Store) UseTOTP(ctx context.Context, userID credbound.UUID, step int64, commit credbound.Commit) (bool, error)

UseTOTP records a successful code for the given time step, reporting false without error when the step was already consumed (replay).

func (*Store) UserByEmail

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

UserByEmail resolves a user by verified email address.

func (*Store) UserByID

func (s *Store) UserByID(ctx context.Context, id credbound.UUID) (credbound.User, error)

UserByID returns the user with the given ID.

func (*Store) UserWorkspaces

UserWorkspaces streams the workspaces the user belongs to, newest first, as one cursor page.

func (*Store) Users

Users streams all users, newest first, as one cursor page.

func (*Store) VerifyEmail

func (s *Store) VerifyEmail(ctx context.Context, emailID credbound.UUID, verifiedAt time.Time, commit credbound.Commit) error

VerifyEmail marks the address verified, makes it usable for sign-in and discards the verification credential; an already-verified address reports credbound.ErrConflict.

func (*Store) WorkspaceByID

func (s *Store) WorkspaceByID(ctx context.Context, workspaceID credbound.UUID) (credbound.Workspace, error)

WorkspaceByID returns the workspace with the given ID.

func (*Store) WorkspaceDomainByID

func (s *Store) WorkspaceDomainByID(ctx context.Context, id credbound.UUID) (credbound.WorkspaceDomain, error)

WorkspaceDomainByID returns the domain record with the given ID.

func (*Store) WorkspaceDomains

WorkspaceDomains streams the workspace's domains, newest first, as one cursor page.

func (*Store) WorkspaceInvitationByID

func (s *Store) WorkspaceInvitationByID(ctx context.Context, invitationID credbound.UUID) (credbound.WorkspaceInvitation, error)

WorkspaceInvitationByID returns the invitation with the given ID.

func (*Store) WorkspaceInvitations

WorkspaceInvitations streams the workspace's invitations, newest first, as one cursor page.

func (*Store) WorkspacePATs added in v0.0.4

func (s *Store) WorkspacePATs(ctx context.Context, workspaceID credbound.UUID, page credbound.PageRequest) iter.Seq2[credbound.PageEvent[credbound.PAT], error]

WorkspacePATs streams the tokens bound to one workspace, newest first, across every owner.

func (*Store) Workspaces

Workspaces streams all workspaces, newest first, as one cursor page.

type Tx

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

Tx is the PostgreSQL transaction capability exposed only during a Credbound TransactionHook. SQL returns nil after the callback has completed.

func TxFrom

func TxFrom(tx credbound.Tx) (*Tx, bool)

TxFrom converts a generic Credbound transaction into the live PostgreSQL capability. It returns false for another store or an expired callback.

func (*Tx) Audit

func (t *Tx) Audit() credbound.AuditEvent

Audit returns the audit event being committed with this transaction.

func (*Tx) Kind

func (t *Tx) Kind() credbound.StoreKind

Kind reports credbound.StorePostgreSQL.

func (*Tx) SQL

func (t *Tx) SQL() *sql.Tx

SQL returns the live transaction so a hook can append host writes to the commit, or nil once the hook callback has completed.

Jump to

Keyboard shortcuts

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