Documentation
¶
Overview ¶
Package auth holds backd's identity model: users, their sign-in identities and password handling. It is storage-neutral; MongoDB specifics live behind Store in internal/mongodb.
A user carries no credentials. Each way of signing in is an Identity (provider + subject), so adding login providers later only adds identities: a password user has a "password" identity, and a user who signs in only through another provider needs none.
Index ¶
- Constants
- Variables
- func ActorOf(ctx context.Context) string
- func AnonymizedCollections() []string
- func AnonymousEmail(userID string) string
- func CheckOrgTemplate(kind string, o email.Override) (removed []string, err error)
- func CheckPassword(password string, minLength int) (string, error)
- func CleanProfile(in map[string]string) map[string]string
- func CompletionJobID(jobID string) string
- func ConnectionMethod(org, provider string) string
- func ConnectionMethodPrefix(org string) string
- func ConnectionProvider(c OrgConnection) *registry.Provider
- func DefaultHashConcurrency(p Argon2Params) int
- func EncryptLock(database, collection string) string
- func ErasedEmail(id string) string
- func HashToken(token string) string
- func IPKey(ip string) string
- func IdempotencyID(database, name, callerSubject, key string) string
- func InvitationOfScope(login *ProviderLogin, hash, scopeOrg string)
- func KeyedJobID(parts ...string) string
- func LooksLikeOrgID(s string) bool
- func NewPKCE() (verifier, challenge string, err error)
- func NewSessionToken() (string, error)
- func NewUploadToken() (token, hash string)
- func NormalizeDomain(raw string) (string, error)
- func OrgContextOf(ctx context.Context) string
- func PKCEChallenge(verifier string) string
- func ProfileValues(input json.RawMessage) []string
- func SSOScopeOf(org string) string
- func SSOSecretName(provider string) string
- func ScheduledJobID(database, function string, scheduledAt time.Time) string
- func SchemaMigrateLock(database, collection string) string
- func SignCallback(key []byte, c CallbackClaims) string
- func ValidPKCEChallenge(s string) bool
- func ValidateClaims(claims map[string]any) error
- func WithAuditSource(ctx context.Context, source func() AuditSource) context.Context
- func WithOffline(ctx context.Context) context.Context
- func WithOrgContext(ctx context.Context, org string) context.Context
- func WithSessionMFA(ctx context.Context, mfa bool) context.Context
- type APIKey
- type AccountPart
- type Argon2Params
- type AssignOrgJob
- type Attempts
- type AuditFilter
- type AuditRecord
- type AuditSource
- type AuthAnonymize
- type AuthChallenge
- type CallbackClaims
- type Caller
- type CheckJob
- type CheckProblem
- type CheckReport
- type CheckedDocument
- type ConnectionInput
- type ConnectionView
- type ConsentContext
- type ConsentInput
- type ConsentNotice
- type ConsentRecord
- type ConsentRef
- type ConsentRequiredError
- type CreatedKey
- type CustomEmail
- type Device
- type DeviceInput
- type DiscoveredOrg
- type DomainRecord
- type DomainRefusedError
- type DomainResolver
- type DomainUpdate
- type DomainView
- type EffectiveRole
- type EmailJob
- type EmailLimitedError
- type EmailRequest
- type EmailToken
- type EncryptCounts
- type EncryptJob
- type EraseJob
- type ErrCheckRunning
- type ErrEncryptRunning
- type ErrExportTooSoon
- type ErrPasswordNoticeRunning
- type ErrSchemaMigrateRunning
- type ExpireResult
- type ExportJob
- type ExportRequest
- type FileDeletion
- type FileDeletionStats
- type FileJournalEntry
- type FuncCaller
- type Hasher
- type HookTeamRole
- type IdempotencyRecord
- type Identity
- type IdentityUpdate
- type ImageJob
- type InvalidCodeError
- type InvalidConsentsError
- type InvalidDeviceError
- type InvalidLocaleError
- type Invitation
- type InvitationInput
- type InvitationResult
- type InvocationFilter
- type InvocationRecord
- type IssuedChallenge
- type Job
- type JobFilter
- type JobResult
- type KeyInUseError
- type KeyOptions
- type KeyRole
- type LogLine
- type LoginCode
- type MFALockedError
- type MFARecord
- type MFAStatus
- type MagicLinkInput
- type ManagedOrg
- type MemberAccess
- type MemberView
- type Membership
- type NewOrgSignupRequest
- type OAuthState
- type OnSignupInput
- type Org
- type OrgConnection
- type OrgDeleteJob
- type OrgDomain
- type OrgInvalidError
- type OrgInvitation
- type OrgInvitationEmail
- type OrgInvitationPreview
- type OrgMember
- type OrgMemberJoined
- type OrgMemberLeft
- type OrgRolesChanged
- type OrgSignIn
- type OrgSignInLink
- type OrgSignupRequest
- type OrgSummary
- type OrgTeam
- type OrgTemplate
- type OrgTemplateVersion
- type OrgUpdate
- type PasskeyInfo
- type PasskeyNameError
- type PasskeyOptions
- type PasskeySignIn
- type PasswordEpoch
- type PasswordExpiredError
- type PasswordNoticeCounts
- type PasswordNoticeJob
- type PasswordStatus
- type PasswordUpdate
- type PolicyError
- type PortableResult
- type PortableStore
- type Principal
- type ProviderLogin
- type ProviderResult
- type PushAudience
- type PushCounts
- type PushDelta
- type PushJob
- type PushOutboxEntry
- type PushRecipient
- type PushSend
- type PushSendFilter
- type PushSendInput
- type PushStarted
- type PushUserFilter
- type ReauthGrant
- type Redeemed
- type RefusedError
- type RevokeJob
- type RoleGrant
- type RoleReport
- type RoleRequiresMFAError
- type RotatedKey
- type SSOHost
- func (h *SSOHost) Engine(proto sso.Protocol) *sso.Engine
- func (h *SSOHost) Ports() (sso.Store, sso.Catalog, sso.Directory, sso.Events)
- func (h *SSOHost) ProviderOf(ctx context.Context, p *registry.Provider, conn *OrgConnection) (sso.Provider, bool, error)
- func (h *SSOHost) UserOf(ctx context.Context, id string) (User, error)
- type SSOHostData
- type SSORequiredResult
- type ScheduleState
- type SchemaMigrateCounts
- type SchemaMigrateFailure
- type SchemaMigrateJob
- type Scope
- type ScopeOp
- type Scopes
- type Secret
- type SecretCache
- type SecretCipher
- type SecretMeta
- type Session
- type SignInClaims
- type SignupRequest
- type SignupResult
- type Step
- type StorageUsage
- type StorageUsageTotals
- type Store
- type TOTPSetup
- type TeamMemberView
- type TeamRoleGrant
- type TeamRoleOp
- type TeamRoleWindow
- type TemplateInvalidError
- type ThrottledError
- type User
- type UserExport
- type UserUpdate
- type UserUsage
- type Users
- func (s *Users) AbandonedUploads(ctx context.Context, limit int) ([]FileJournalEntry, error)
- func (s *Users) AcceptConsents(ctx context.Context, challenge string, given map[string]string, ...) (Verified, error)
- func (s *Users) AcceptConsentsOf(ctx context.Context, u User, given map[string]string, from ConsentContext) (User, error)
- func (s *Users) AcceptInvitation(ctx context.Context, token, password, locale string) (EmailToken, error)
- func (s *Users) AcceptOrgInvitation(ctx context.Context, p Principal, token string) (Membership, error)
- func (s *Users) AccountExport(ctx context.Context, userID string) ([]AccountPart, error)
- func (s *Users) AddOrgTeamMember(ctx context.Context, userID, orgID, id, target string) (MemberView, error)
- func (s *Users) AddRole(ctx context.Context, email, role string) error
- func (s *Users) AdminAddMember(ctx context.Context, orgID, userID string, roles []string) (MemberView, error)
- func (s *Users) AdminAssignOwner(ctx context.Context, orgID, userID string) (MemberView, error)
- func (s *Users) AdminCreateOrg(ctx context.Context, name, slug, owner string) (Membership, error)
- func (s *Users) AdminCreateOrgInvitation(ctx context.Context, orgID string, in InvitationInput) (InvitationResult, error)
- func (s *Users) AdminCreateOrgTeam(ctx context.Context, orgID, name string, roles []string) (OrgTeam, error)
- func (s *Users) AdminDeleteOrg(ctx context.Context, orgID, requestID string) (Org, error)
- func (s *Users) AdminDeleteOrgConnection(ctx context.Context, orgID, provider string) error
- func (s *Users) AdminDeleteOrgTeam(ctx context.Context, orgID, id string) error
- func (s *Users) AdminMembers(ctx context.Context, orgID, after string, limit int) ([]MemberView, bool, error)
- func (s *Users) AdminNewOrgInvitationLink(ctx context.Context, orgID, id string) (InvitationResult, error)
- func (s *Users) AdminOrg(ctx context.Context, orgID string) (Org, error)
- func (s *Users) AdminOrgConnection(ctx context.Context, orgID, provider string) (ConnectionView, error)
- func (s *Users) AdminOrgConnections(ctx context.Context, orgID string) ([]ConnectionView, error)
- func (s *Users) AdminOrgInvitations(ctx context.Context, orgID string) ([]OrgInvitation, error)
- func (s *Users) AdminOrgSummaries(ctx context.Context, status, q string) ([]OrgSummary, error)
- func (s *Users) AdminOrgTeams(ctx context.Context, orgID string) ([]OrgTeam, error)
- func (s *Users) AdminOrgs(ctx context.Context, status string) ([]Org, error)
- func (s *Users) AdminReactivateOrg(ctx context.Context, orgID, slug string) (Org, error)
- func (s *Users) AdminRemoveMember(ctx context.Context, orgID, target string) error
- func (s *Users) AdminRemovePasskey(ctx context.Context, userID, id string) error
- func (s *Users) AdminResendOrgInvitation(ctx context.Context, orgID, id, locale, ip, requestID string) error
- func (s *Users) AdminRevokeOrgInvitation(ctx context.Context, orgID, id string) error
- func (s *Users) AdminSetClaims(ctx context.Context, orgID string, claims map[string]any) (Org, error)
- func (s *Users) AdminSetMemberRoles(ctx context.Context, orgID, target string, roles []string) (MemberView, error)
- func (s *Users) AdminSetOrgConnection(ctx context.Context, orgID, provider string, in ConnectionInput) (ConnectionView, error)
- func (s *Users) AdminSetOrgSSORequired(ctx context.Context, orgID string, on bool) (SSORequiredResult, error)
- func (s *Users) AdminSetOrgSlug(ctx context.Context, orgID, slug string) (Org, error)
- func (s *Users) AdminSetOrgTeamMember(ctx context.Context, orgID, id, target string, add bool) (MemberView, error)
- func (s *Users) AdminTeamMembers(ctx context.Context, orgID, teamID, role, after string, limit int) ([]TeamMemberView, bool, error)
- func (s *Users) AdminUpdateOrgTeam(ctx context.Context, orgID, id string, name *string, roles []string, ...) (OrgTeam, error)
- func (s *Users) AfterOrgSignIn(ctx context.Context, orgID, provider string, res ProviderResult) (joined bool)
- func (s *Users) AllowRealPreview(ctx context.Context, orgID string) error
- func (s *Users) AllowsIssuer(issuer string) bool
- func (s *Users) ApplyRoleSeeds(ctx context.Context) (int, error)
- func (s *Users) Audit(ctx context.Context, action, target string, details map[string]any)
- func (s *Users) AuditAs(ctx context.Context, actor, action, target string, details map[string]any)
- func (s *Users) AuditTrail(ctx context.Context, f AuditFilter) ([]AuditRecord, bool, error)
- func (s *Users) Authenticate(ctx context.Context, token string) (Principal, error)
- func (s *Users) AuthenticateIgnoringConsents(ctx context.Context, token string) (Principal, error)
- func (s *Users) AuthenticateKey(ctx context.Context, key string) (APIKey, error)
- func (s *Users) BeginEnrollment(ctx context.Context, challenge string) (TOTPSetup, error)
- func (s *Users) BeginPasskeyEnrollment(ctx context.Context, challenge string) ([]byte, error)
- func (s *Users) BeginPasskeyReauth(ctx context.Context, p Principal) ([]byte, error)
- func (s *Users) BeginPasskeyRegistration(ctx context.Context, u User) (options []byte, ceremony string, err error)
- func (s *Users) BeginPasskeySignIn(ctx context.Context, strategy, org, ip string) (PasskeyOptions, error)
- func (s *Users) BeginPasskeyStep(ctx context.Context, challenge string) ([]byte, error)
- func (s *Users) BeginTOTPSetup(ctx context.Context, u User) (TOTPSetup, error)
- func (s *Users) CallbackCaller(ctx context.Context, c CallbackClaims) (Caller, error)
- func (s *Users) CanEditTemplate(ctx context.Context, userID, orgID, kind, locale string) error
- func (s *Users) CancelJob(ctx context.Context, id string) (Job, error)
- func (s *Users) ChangeEmailAsAdmin(ctx context.Context, userID, newAddress string) (User, error)
- func (s *Users) ChangePassword(ctx context.Context, p Principal, next string) error
- func (s *Users) CheckConnectionAuthority(ctx context.Context, c OrgConnection) error
- func (s *Users) CheckOrgDomains(ctx context.Context, limit int) (int, error)
- func (s *Users) CheckReauth(ctx context.Context, p Principal, token string) error
- func (s *Users) CheckReport(ctx context.Context, database, collection string) (CheckReport, error)
- func (s *Users) CheckReports(ctx context.Context, documents bool) ([]CheckReport, error)
- func (s *Users) ChooseStrategy(name, first string) (registry.Strategy, error)
- func (s *Users) ClaimDirectUpload(ctx context.Context, id, token string) (FileJournalEntry, error)
- func (s *Users) ClaimFileDeletions(ctx context.Context, limit int) ([]FileDeletion, error)
- func (s *Users) ClaimIdempotency(ctx context.Context, rec IdempotencyRecord) (IdempotencyRecord, bool, error)
- func (s *Users) ClaimJob(ctx context.Context, workerID string) (Job, bool, error)
- func (s *Users) ClaimOrgDomain(ctx context.Context, userID, orgID, domain string) (DomainView, error)
- func (s *Users) ClaimPendingUpload(ctx context.Context, id, token, documentID string) (FileJournalEntry, error)
- func (s *Users) Clock() time.Time
- func (s *Users) CompleteEnrollment(ctx context.Context, challenge, setupID, code string) (Verified, []string, error)
- func (s *Users) CompleteIdempotency(ctx context.Context, id string, result *JobResult, jobID string) error
- func (s *Users) CompleteJob(ctx context.Context, id string, result JobResult) error
- func (s *Users) CompletePasskeyEnrollment(ctx context.Context, challenge string, credential []byte, name string) (Verified, error)
- func (s *Users) CompletePendingUpload(ctx context.Context, id, name, contentType, sha256sum string, size int64, ...) error
- func (s *Users) ConfirmEmailChange(ctx context.Context, token string) (EmailToken, error)
- func (s *Users) ConfirmTOTP(ctx context.Context, u User, keepSession, setupID, code string) ([]string, error)
- func (s *Users) ConsentHistory(ctx context.Context, userID string) ([]ConsentRecord, error)
- func (s *Users) ConsentPseudonym(ctx context.Context, address string) (string, error)
- func (s *Users) Create(ctx context.Context, email string, password *string) (User, error)
- func (s *Users) CreateAPIKey(ctx context.Context, name string, opts KeyOptions) (APIKey, string, error)
- func (s *Users) CreateInvitation(ctx context.Context, email string, ttl time.Duration, createdBy string) (Invitation, string, error)
- func (s *Users) CreateKey(ctx context.Context, name, value, by string) (CreatedKey, error)
- func (s *Users) CreateOrg(ctx context.Context, p Principal, name, slug string) (Membership, error)
- func (s *Users) CreateOrgInvitation(ctx context.Context, userID, orgID string, in InvitationInput) (InvitationResult, error)
- func (s *Users) CreateOrgTeam(ctx context.Context, userID, orgID, name string, roles []string) (OrgTeam, error)
- func (s *Users) CreateResetLink(ctx context.Context, userID, redirectTo string) (token string, expires time.Time, err error)
- func (s *Users) CustomizableKinds() map[string][]string
- func (s *Users) DeactivateAccount(ctx context.Context, p Principal) error
- func (s *Users) Delete(ctx context.Context, email string) error
- func (s *Users) DeleteKey(ctx context.Context, name string) error
- func (s *Users) DeleteOrg(ctx context.Context, userID, orgID, requestID string) (Org, error)
- func (s *Users) DeleteOrgConnection(ctx context.Context, userID, orgID, provider string) error
- func (s *Users) DeleteOrgSecret(ctx context.Context, orgID, name string) error
- func (s *Users) DeleteOrgTeam(ctx context.Context, userID, orgID, id string) error
- func (s *Users) DeleteOrgTemplate(ctx context.Context, userID, orgID, kind, locale string) error
- func (s *Users) DeleteSecret(ctx context.Context, database, name string) error
- func (s *Users) Devices(ctx context.Context, userID string) ([]Device, error)
- func (s *Users) DisableMFA(ctx context.Context, u User) error
- func (s *Users) DiscoverOrgs(ctx context.Context, address, ip string) ([]DiscoveredOrg, error)
- func (s *Users) EnqueueCompletionJob(ctx context.Context, finished Job, target string, timeoutMS int64, ...) (Job, bool, error)
- func (s *Users) EnqueueImageJob(ctx context.Context, database string, e ImageJob, requestID string) error
- func (s *Users) EnqueueImageOp(ctx context.Context, database string, e ImageJob, requestID string) (Job, error)
- func (s *Users) EnqueueJob(ctx context.Context, j Job) (Job, error)
- func (s *Users) EnqueueJobID(ctx context.Context, j Job) (created bool, err error)
- func (s *Users) EnqueueJobs(ctx context.Context, jobs []Job) (int, error)
- func (s *Users) EnqueueKeyedJob(ctx context.Context, j Job) (bool, error)
- func (s *Users) EnqueueScheduledJob(ctx context.Context, j Job, scheduledAt time.Time, skipOverlap bool) (Job, bool, error)
- func (s *Users) EnterOrg(ctx context.Context, u User, orgID, invitationHash string) bool
- func (s *Users) Erase(ctx context.Context, id, requestID string) (Job, error)
- func (s *Users) EraseJobFor(ctx context.Context, userID string) (Job, bool, error)
- func (s *Users) ExpireAllPasswords(ctx context.Context, reason string, keepSessions bool) (ExpireResult, error)
- func (s *Users) ExpirePassword(ctx context.Context, email, reason string) error
- func (s *Users) ExportAuthDocs(ctx context.Context, collection, afterID string, limit int, ek *SecretCipher, ...) (out []map[string]any, unavailable int, last string, read int, err error)
- func (s *Users) FileAdded(ctx context.Context, owner string, size int64) error
- func (s *Users) FileDeletionStats(ctx context.Context) (FileDeletionStats, error)
- func (s *Users) FileRemoved(ctx context.Context, owner string, size int64) error
- func (s *Users) Find(ctx context.Context, email string) (User, error)
- func (s *Users) FindOrgs(ctx context.Context, address, locale, ip, requestID string) error
- func (s *Users) FinishFileDeletion(ctx context.Context, key string) error
- func (s *Users) FinishPasskeyRegistration(ctx context.Context, u User, ceremony string, credential []byte, name string) (PasskeyInfo, error)
- func (s *Users) GetJob(ctx context.Context, id string) (Job, bool, error)
- func (s *Users) Identify(ctx context.Context, credential string) (Caller, error)
- func (s *Users) Identities(ctx context.Context, userID string) ([]Identity, error)
- func (s *Users) IdentityDormant(ctx context.Context, i Identity) bool
- func (s *Users) ImageDeclarations(ctx context.Context) (map[string]string, error)
- func (s *Users) ImportAuthDocs(ctx context.Context, collection string, docs []map[string]any, mode string, ...) ([]PortableResult, error)
- func (s *Users) InvitationByID(ctx context.Context, id string) (Invitation, bool, error)
- func (s *Users) Invitations(ctx context.Context) ([]Invitation, error)
- func (s *Users) Invocations(ctx context.Context, f InvocationFilter) ([]InvocationRecord, bool, error)
- func (s *Users) IsSeeded(email, role string) bool
- func (s *Users) IssueLoginCode(ctx context.Context, userID, method, challenge string, newUser bool, ...) (string, error)
- func (s *Users) IssueLoginCodeFor(ctx context.Context, userID, method, strategy, challenge string, newUser bool, ...) (string, error)
- func (s *Users) IssueLoginCodeIn(ctx context.Context, userID, method, challenge string, newUser bool, ...) (string, error)
- func (s *Users) Jobs(ctx context.Context, f JobFilter) ([]Job, bool, error)
- func (s *Users) JournalDirectUpload(ctx context.Context, e FileJournalEntry, ttl time.Duration) error
- func (s *Users) JournalPendingUpload(ctx context.Context, e FileJournalEntry, ttl time.Duration) error
- func (s *Users) JournalUpload(ctx context.Context, e FileJournalEntry) error
- func (s *Users) KeyCreatedBySession(ctx context.Context, p Principal)
- func (s *Users) KeyMaterial(ctx context.Context, name string) (fieldcrypt.Material, error)
- func (s *Users) KeyUsedBy(name string) []string
- func (s *Users) LatestSchemaMigration(ctx context.Context, database, collection string) (Job, bool, error)
- func (s *Users) LeaveOrg(ctx context.Context, userID, orgID string) error
- func (s *Users) List(ctx context.Context) ([]User, error)
- func (s *Users) ListAPIKeys(ctx context.Context) ([]APIKey, error)
- func (s *Users) ListOrgDomains(ctx context.Context, userID, orgID string) ([]DomainView, error)
- func (s *Users) ListPage(ctx context.Context, contains, after string, skip, limit int) ([]User, bool, error)
- func (s *Users) ListPasskeys(ctx context.Context, userID string) ([]PasskeyInfo, error)
- func (s *Users) ListSecrets(ctx context.Context) ([]SecretMeta, error)
- func (s *Users) LocaleOf(u User) string
- func (s *Users) Login(ctx context.Context, email, password, ip string) (Principal, string, error)
- func (s *Users) Logout(ctx context.Context, p Principal) error
- func (s *Users) LogoutAll(ctx context.Context, p Principal) error
- func (s *Users) MFAStatusOf(ctx context.Context, u User) (MFAStatus, error)
- func (s *Users) MagicLinkByToken(ctx context.Context, token string) (AuthChallenge, error)
- func (s *Users) MagicLinkDestination(c AuthChallenge) string
- func (s *Users) MagicLinkEmailFor(ctx context.Context, challengeID string) (AuthChallenge, string, error)
- func (s *Users) MakeMagicLinkSecrets(ctx context.Context, challengeID string) (token, code string, expires time.Time, err error)
- func (s *Users) MakeReauthCode(ctx context.Context, challengeID string) (string, time.Time, error)
- func (s *Users) MaxSessionExpiry(u User, sess Session) time.Time
- func (s *Users) Members(ctx context.Context, userID, orgID, after string, limit int) ([]MemberView, bool, error)
- func (s *Users) MembersWithoutSSO(ctx context.Context, userID, orgID, after string, limit int) ([]MemberView, bool, error)
- func (s *Users) MembershipOf(ctx context.Context, userID, orgID string) (Membership, error)
- func (s *Users) MyOrgs(ctx context.Context, userID string) ([]Membership, error)
- func (s *Users) NetworksInConfig(email string) bool
- func (s *Users) NewEmailToken(ctx context.Context, purpose, userID, redirectTo string, ttl time.Duration) (token string, expiresAt time.Time, err error)
- func (s *Users) NewEmailTokenFor(ctx context.Context, t EmailToken, ttl time.Duration) (token string, expiresAt time.Time, err error)
- func (s *Users) NewOrgInvitationLink(ctx context.Context, userID, orgID, id string) (InvitationResult, error)
- func (s *Users) NextAccessChange(ctx context.Context, userID string) (time.Time, error)
- func (s *Users) NotifyConsentUpdated(ctx context.Context, consent string) (ConsentNotice, error)
- func (s *Users) NotifyPasswordBatch(ctx context.Context, pj PasswordNoticeJob) (after string, c PasswordNoticeCounts, retryAfter time.Duration, err error)
- func (s *Users) NotifyTemplateFailed(ctx context.Context, orgID, kind string)
- func (s *Users) OnBehalfOf(ctx context.Context, c Caller, userID string) (Caller, error)
- func (s *Users) OpenOrgSession(ctx context.Context, p Principal, orgID string) (Principal, string, error)
- func (s *Users) OpenPendingUploads(ctx context.Context, callerKey string) (int, error)
- func (s *Users) OpenToken(sealed string) (string, error)
- func (s *Users) OrgActive(ctx context.Context, id string) bool
- func (s *Users) OrgByRef(ctx context.Context, ref string) (Org, error)
- func (s *Users) OrgConnection(ctx context.Context, userID, orgID, provider string) (ConnectionView, error)
- func (s *Users) OrgConnectionAllowed(ctx context.Context, userID, orgID, provider string) (registry.OrgCaps, error)
- func (s *Users) OrgConnections(ctx context.Context, userID, orgID string) ([]ConnectionView, error)
- func (s *Users) OrgDomainsAllowed(ctx context.Context, userID, orgID string) error
- func (s *Users) OrgInvitationEmail(ctx context.Context, ref string) (OrgInvitationEmail, error)
- func (s *Users) OrgInvitations(ctx context.Context, userID, orgID string) ([]OrgInvitation, error)
- func (s *Users) OrgName(ctx context.Context, orgID string) string
- func (s *Users) OrgNeedsMFA(ctx context.Context, userID, orgID string) bool
- func (s *Users) OrgSSORequired(ctx context.Context, ref string) (orgID string, required bool)
- func (s *Users) OrgSecret(ctx context.Context, orgID, name string) (value string, ok bool, err error)
- func (s *Users) OrgTeamExists(ctx context.Context, orgID, teamID string) bool
- func (s *Users) OrgTeams(ctx context.Context, userID, orgID string) ([]OrgTeam, error)
- func (s *Users) OrgTemplateFor(ctx context.Context, orgID, kind, locale string) (OrgTemplate, bool)
- func (s *Users) OrgTemplateOf(ctx context.Context, userID, orgID, kind, locale string) (OrgTemplate, error)
- func (s *Users) OrgTemplates(ctx context.Context, userID, orgID string) ([]OrgTemplate, error)
- func (s *Users) OrgsEnabled() bool
- func (s *Users) OrgsManagedBy(ctx context.Context, userID string) ([]ManagedOrg, error)
- func (s *Users) PasskeyCount(ctx context.Context, userID string) (int, error)
- func (s *Users) PasskeyService() (*passkey.Service, error)
- func (s *Users) PasswordExpiredFor(ctx context.Context, u User) (bool, error)
- func (s *Users) PasswordState(ctx context.Context) (PasswordStatus, error)
- func (s *Users) PeekEmailToken(ctx context.Context, token, purpose string) (EmailToken, error)
- func (s *Users) PendingUpload(ctx context.Context, id string) (FileJournalEntry, error)
- func (s *Users) PlanPushAudience(ctx context.Context, job Job) error
- func (s *Users) PlanPushBatch(ctx context.Context, batchID, sendID string, users []string, ...) (PushCounts, error)
- func (s *Users) PlanPushBatchRequiring(ctx context.Context, batchID, sendID string, users []string, ...) (PushCounts, error)
- func (s *Users) PreviewOrgInvitation(ctx context.Context, p Principal, token string) (OrgInvitationPreview, error)
- func (s *Users) PreviewOrgInvitationOf(ctx context.Context, orgRef, token string) (OrgInvitationPreview, error)
- func (s *Users) ProviderSecrets(ctx context.Context, p *registry.Provider) (map[string]string, bool, error)
- func (s *Users) PurgeUnverified(ctx context.Context) (int, error)
- func (s *Users) PushSendByID(ctx context.Context, id string) (PushSend, error)
- func (s *Users) PushSends(ctx context.Context, f PushSendFilter) ([]PushSend, bool, error)
- func (s *Users) QueueEmail(ctx context.Context, r EmailRequest) (Job, error)
- func (s *Users) QueueFileDeletion(ctx context.Context, key, reason string, public bool) error
- func (s *Users) QueueTemplateTest(ctx context.Context, userID, orgID, kind, locale string, draft *email.Override, ...) error
- func (s *Users) RateLimit(ctx context.Context, key string, limit int, window time.Duration) error
- func (s *Users) ReauthMethodsOf(ctx context.Context, u User) ([]string, error)
- func (s *Users) Reauthenticate(ctx context.Context, p Principal, method, proof, ip string) (ReauthGrant, error)
- func (s *Users) RecordConsent(ctx context.Context, userID string, in ConsentInput) (ConsentRecord, error)
- func (s *Users) RecordConsentFor(ctx context.Context, userID string, in ConsentInput) (ConsentRecord, error)
- func (s *Users) RecordInvocation(ctx context.Context, rec InvocationRecord)
- func (s *Users) RedeemEmailToken(ctx context.Context, token, purpose string) (EmailToken, error)
- func (s *Users) RedeemLoginCode(ctx context.Context, code, verifier string) (Redeemed, error)
- func (s *Users) ReduceConsentRecords(ctx context.Context, userID, address string) (int64, error)
- func (s *Users) RegenerateRecoveryCodes(ctx context.Context, u User) ([]string, error)
- func (s *Users) RegisterDevice(ctx context.Context, p Principal, in DeviceInput) (Device, error)
- func (s *Users) ReleaseDirectUpload(ctx context.Context, id string) error
- func (s *Users) ReleaseIdempotency(ctx context.Context, id string) error
- func (s *Users) ReleasePendingUpload(ctx context.Context, id string) error
- func (s *Users) RemoveDevice(ctx context.Context, userID, id, by string) error
- func (s *Users) RemoveDevicesOfPlatform(ctx context.Context, platform string) (int64, error)
- func (s *Users) RemoveMember(ctx context.Context, userID, orgID, target string) error
- func (s *Users) RemoveOrgConnections(ctx context.Context, orgID string) (int, error)
- func (s *Users) RemoveOrgDomain(ctx context.Context, userID, orgID, domain string) error
- func (s *Users) RemoveOrgDomains(ctx context.Context, orgID string) (int, error)
- func (s *Users) RemoveOrgTeamMember(ctx context.Context, userID, orgID, id, target string) (MemberView, error)
- func (s *Users) RemovePasskey(ctx context.Context, u User, id string) error
- func (s *Users) RemovePassword(ctx context.Context, p Principal) error
- func (s *Users) RemoveRole(ctx context.Context, email, role string) error
- func (s *Users) RenamePasskey(ctx context.Context, userID, id, name string) (PasskeyInfo, error)
- func (s *Users) RenewJobLease(ctx context.Context, id string, attempt int, d time.Duration) (bool, error)
- func (s *Users) ReportRoles(ctx context.Context) (RoleReport, error)
- func (s *Users) RequestEmailChange(ctx context.Context, p Principal, newAddress, redirectTo, ip, requestID string) error
- func (s *Users) RequestMagicLink(ctx context.Context, in MagicLinkInput) (string, error)
- func (s *Users) RequestPasswordReset(ctx context.Context, address, redirectTo, ip, requestID string) error
- func (s *Users) RequestReauthCode(ctx context.Context, p Principal, ip, requestID string) error
- func (s *Users) RequestUserExport(ctx context.Context, userID string, req ExportRequest) (UserExport, error)
- func (s *Users) RerunJob(ctx context.Context, id string, timeoutMS int64) (Job, error)
- func (s *Users) ResendOrgInvitation(ctx context.Context, userID, orgID, id, locale, ip, requestID string) error
- func (s *Users) ResendVerification(ctx context.Context, address, redirectTo, ip, requestID string) error
- func (s *Users) ResetMFA(ctx context.Context, userID, actorID string) error
- func (s *Users) ResetPassword(ctx context.Context, token, password string) (EmailToken, error)
- func (s *Users) ResolveOrgContext(ctx context.Context, org, address string) string
- func (s *Users) ResolveProviderLogin(ctx context.Context, in ProviderLogin) (ProviderResult, error)
- func (s *Users) ResolveSecrets(ctx context.Context, refs []registry.SecretRef, database string) (values map[string]string, missing []string, err error)
- func (s *Users) RetryFileDeletion(ctx context.Context, key string, wait time.Duration) error
- func (s *Users) RetryJob(ctx context.Context, id string, delay time.Duration) error
- func (s *Users) RevertEmailChange(ctx context.Context, token string) (EmailToken, error)
- func (s *Users) RevokeAPIKey(ctx context.Context, name string) error
- func (s *Users) RevokeAllSessions(ctx context.Context) (int64, error)
- func (s *Users) RevokeInvitation(ctx context.Context, id string) error
- func (s *Users) RevokeOrgInvitation(ctx context.Context, userID, orgID, id string) error
- func (s *Users) RevokeSession(ctx context.Context, p Principal, id string) error
- func (s *Users) RevokeUserSession(ctx context.Context, userID, id string) error
- func (s *Users) RotateKey(ctx context.Context, name, value string, resume bool, by string) (RotatedKey, error)
- func (s *Users) RuleOrgs(ctx context.Context, userID string, mfa bool, scope string) (map[string]*rules.UserOrg, error)
- func (s *Users) SaveAppleToken(ctx context.Context, userID, clientID, refreshToken string) error
- func (s *Users) SaveCheckReport(ctx context.Context, r CheckReport) error
- func (s *Users) SaveOrgTemplate(ctx context.Context, userID, orgID, kind, locale string, o email.Override) (OrgTemplate, []string, error)
- func (s *Users) ScheduleStates(ctx context.Context) (map[string]ScheduleState, error)
- func (s *Users) SealToken(token string) (string, error)
- func (s *Users) SendInvitation(ctx context.Context, address string, ttl time.Duration, ...) (Invitation, error)
- func (s *Users) Sessions(ctx context.Context, p Principal) ([]Session, error)
- func (s *Users) SetDisabled(ctx context.Context, email string, disabled bool) error
- func (s *Users) SetEmailVerified(ctx context.Context, email string, verified bool) error
- func (s *Users) SetImageDeclaration(ctx context.Context, key, fingerprint string) error
- func (s *Users) SetJobSteps(ctx context.Context, id string, attempt int, steps []Step, omitted int) (bool, error)
- func (s *Users) SetLocale(ctx context.Context, userID, locale string) (User, error)
- func (s *Users) SetNetworks(ctx context.Context, email string, admin, login registry.Networks) (User, error)
- func (s *Users) SetOrgConnection(ctx context.Context, userID, orgID, provider string, in ConnectionInput) (ConnectionView, error)
- func (s *Users) SetOrgRequireMFA(ctx context.Context, p Principal, orgID string, on bool) (Membership, error)
- func (s *Users) SetOrgSSORequired(ctx context.Context, p Principal, orgID string, on bool) (SSORequiredResult, error)
- func (s *Users) SetOrgSecret(ctx context.Context, orgID, name, value, by string) error
- func (s *Users) SetOrgSessionMaxAge(ctx context.Context, userID, orgID string, d time.Duration) (Membership, error)
- func (s *Users) SetPassword(ctx context.Context, email, password string) error
- func (s *Users) SetSchedulePaused(ctx context.Context, database, function string, paused bool, by string) (ScheduleState, error)
- func (s *Users) SetSchemaMigrateProgress(ctx context.Context, jobID string, m SchemaMigrateJob) error
- func (s *Users) SetSecret(ctx context.Context, database, name, value, by string) error
- func (s *Users) SetTeamRole(ctx context.Context, caller, orgID, teamID, target, role string, op TeamRoleOp, ...) (TeamMemberView, error)
- func (s *Users) SetUploadStatus(ctx context.Context, id, status, documentID string) error
- func (s *Users) SignIn(ctx context.Context, email, password, ip string) (Redeemed, error)
- func (s *Users) SignInLinks(ctx context.Context, userID string) ([]OrgSignInLink, error)
- func (s *Users) SignInMethods(ctx context.Context, u User) ([]string, error)
- func (s *Users) SignInToOrg(ctx context.Context, in OrgSignIn) (Redeemed, error)
- func (s *Users) SignInWith(ctx context.Context, strategy, email, password, ip string) (Redeemed, error)
- func (s *Users) SignInWithPasskey(ctx context.Context, in PasskeySignIn) (Redeemed, error)
- func (s *Users) SignUp(ctx context.Context, r SignupRequest) (SignupResult, error)
- func (s *Users) SignUpToOrg(ctx context.Context, r OrgSignupRequest) (SignupResult, error)
- func (s *Users) SignUpWithOrg(ctx context.Context, r NewOrgSignupRequest) (SignupResult, Membership, error)
- func (s *Users) Signup(ctx context.Context, email, password, invitation string, locales ...string) (Principal, string, error)
- func (s *Users) StartAssignOrg(ctx context.Context, database string, e AssignOrgJob, ...) (Job, error)
- func (s *Users) StartEncryptMigration(ctx context.Context, ej EncryptJob, requestedBy, requestID string) (Job, error)
- func (s *Users) StartPasswordNotice(ctx context.Context, requestedBy, requestID string) (Job, error)
- func (s *Users) StartProviderSession(ctx context.Context, u User, provider string, newUser bool, ...) (Redeemed, error)
- func (s *Users) StartProviderSessionFor(ctx context.Context, u User, provider, strategy string, newUser bool, ...) (Redeemed, error)
- func (s *Users) StartProviderSessionIn(ctx context.Context, u User, provider string, newUser bool, ...) (Redeemed, error)
- func (s *Users) StartPushSend(ctx context.Context, in PushSendInput, requestID string) (PushStarted, error)
- func (s *Users) StartRegeneration(ctx context.Context, database string, e ImageJob, ...) (Job, error)
- func (s *Users) StartSchemaCheck(ctx context.Context, scope CheckJob, requestedBy, requestID string) (Job, error)
- func (s *Users) StartSchemaMigration(ctx context.Context, j SchemaMigrateJob, requestedBy, requestID string) (job Job, created bool, err error)
- func (s *Users) StorageUsage(ctx context.Context, limit int) (StorageUsage, error)
- func (s *Users) StorageUsageOf(ctx context.Context, owner string) (realm, user StorageUsageTotals, err error)
- func (s *Users) SweepDevices(ctx context.Context) (stale, orphaned int64, err error)
- func (s *Users) SweepTeamRoles(ctx context.Context) (int64, error)
- func (s *Users) SyncAuditEntries(ctx context.Context) error
- func (s *Users) TeamMembers(ctx context.Context, userID, orgID, teamID, role, after string, limit int) ([]TeamMemberView, bool, error)
- func (s *Users) Unlink(ctx context.Context, userID, provider, by string) error
- func (s *Users) UnlinkIn(ctx context.Context, userID, provider, org, by string) error
- func (s *Users) UpdateMember(ctx context.Context, userID, orgID, target string, roles []string) (MemberView, error)
- func (s *Users) UpdateOrg(ctx context.Context, userID, orgID string, name, slug *string) (Membership, error)
- func (s *Users) UpdateOrgDomain(ctx context.Context, userID, orgID, domain string, in DomainUpdate) (DomainView, error)
- func (s *Users) UpdateOrgTeam(ctx context.Context, userID, orgID, id string, name *string, roles []string, ...) (OrgTeam, error)
- func (s *Users) UpdatePassword(ctx context.Context, in PasswordUpdate) error
- func (s *Users) UploadEntry(ctx context.Context, id string) (FileJournalEntry, error)
- func (s *Users) UseMagicLink(ctx context.Context, token, ip string) (code, destination string, err error)
- func (s *Users) UserByID(ctx context.Context, id string) (User, error)
- func (s *Users) UserExport(ctx context.Context, userID, id string) (UserExport, error)
- func (s *Users) UserExports(ctx context.Context, userID string) ([]UserExport, error)
- func (s *Users) UserSessions(ctx context.Context, userID string) ([]Session, error)
- func (s *Users) UsersWithoutRequiredMFA(ctx context.Context, limit int) ([]User, int, error)
- func (s *Users) ValidateConsents(given map[string]string) error
- func (s *Users) VerificationNeedsPassword(ctx context.Context, t EmailToken) bool
- func (s *Users) VerifiedDomainOf(ctx context.Context, domain string) (OrgDomain, bool)
- func (s *Users) VerifyEmail(ctx context.Context, token, password, ip string) (EmailToken, error)
- func (s *Users) VerifyMFA(ctx context.Context, challenge, method, code, ip string) (Verified, error)
- func (s *Users) VerifyMFAPasskey(ctx context.Context, challenge string, credential []byte, ip string) (Verified, error)
- func (s *Users) VerifyMagicLinkCode(ctx context.Context, requestID, code, verifier, ip string) (Redeemed, error)
- func (s *Users) VerifyOrgDomain(ctx context.Context, userID, orgID, domain string) (DomainView, error)
- func (s *Users) WithdrawConsent(ctx context.Context, u User, consent string, from ConsentContext) (User, error)
- type Verified
- type WithheldRole
Constants ¶
const ( // ProviderApple is the identity provider of Sign in with Apple. ProviderApple = "apple" // RevokeOrigin is the origin of a revoke job in the job list. RevokeOrigin = "backd:apple.revoke" )
const ( AuditUserCreate = "user.create" // by an administrator (or bootstrap) AuditUserSignup = "user.signup" // self-service sign-up AuditUserPassword = "user.password" // set by an administrator AuditPasswordChange = "user.password_change" AuditPasswordSet = "user.password_set" // the user set a password on an account that had none AuditPasswordRemoved = "user.password_removed" // the user removed their password AuditUserVerifyEmail = "user.verify_email" // details: verified AuditPasswordReset = "user.password_reset" // by the link in an email; details: verified_address AuditUserPurged = "user.purged_unverified" // details: count; never addresses AuditUserClaimed = "user.claimed" // an unverified account taken over by its mailbox's owner; details: methods, passkeys, mfa AuditSessionRevokeAll = "session.revoke_all" // an administrator ended every session of the realm; details: count AuditPasswordResetLink = "password.reset_link" // an administrator made a reset link for a user; never the token AuditPasswordNotify = "password.expire_notify" // the notification run ended; details: counts AuditPasswordExpire = "password.expire" // details: scope (user or realm), reason AuditUserDisable = "user.disable" AuditUserEnable = "user.enable" AuditUserDelete = "user.delete" AuditAccountDelete = "user.delete_account" // self-service: the account is deactivated AuditUserErased = "user.erased" // details: job_id and counts, or needs_attention // The export of a user's personal data (design/compliance.md §4): asked for (details: export, // by "user" or the administrator, ticket, and, for a silent one, the reason), built, failed, // downloaded (details: export, by) and deleted at the end of its retention. AuditDataExportRequested = "user.data_export_requested" AuditDataExportSilent = "user.data_export_requested_silently" AuditDataExported = "user.data_exported" AuditDataExportFailed = "user.data_export_failed" AuditDataExportDownloaded = "user.data_export_downloaded" AuditDataExportExpired = "user.data_export_expired" AuditUserNetworks = "user.networks" // details: admin_networks, login_networks AuditSessionRevoke = "session.revoke" // by an administrator; details: session AuditDeviceRemoved = "device.removed" // by an administrator; details: platform, device AuditAppConfig = "appconfig.change" // details: version, kind (set, rollback), paths; never values AuditPushTest = "push.test" // an administrator sent a test push; details: send, kind AuditPushDevices = "push.devices_removed" // an administrator removed every device of a platform (a rotated VAPID key); details: platform, count AuditRoleAdd = "role.add" // details: role AuditRoleRemove = "role.remove" // details: role AuditAPIKeyCreate = "apikey.create" // details: role, expires_at, networks AuditAPIKeyRevoke = "apikey.revoke" AuditEmailChanged = "user.email_changed" // details: by (self or admin) AuditEmailReverted = "user.email_change_reverted" // the old address undid a change AuditInviteSent = "invitation.sent" // details: expires_at AuditInviteCreate = "invitation.create" // details: bound_to_email, expires_at AuditInviteRevoke = "invitation.revoke" AuditAdminLogin = "admin.login" // login of a user holding an admin role AuditAdminRefused = "admin.refused" // details: reason AuditBootstrap = "realm.bootstrap" // Sign-in methods; the target is the user, details: provider, and by // (self or admin) for an unlink. AuditIdentityLinked = "identity.linked" AuditIdentityUnlinked = "identity.unlinked" // Apple revoked a user's tokens when their account went away or Apple was unlinked; // never the token itself. AuditAppleRevoked = "identity.apple_revoked" // A provider sign-in the account's state refused; details: provider, reason // (disabled, network, erased, …). AuditSignInRefused = "identity.signin_refused" // Second factors; the target is the user. user.mfa_reset: by an administrator (the // actor) or `instance`; never codes. AuditMFAEnabled = "user.mfa_enabled" AuditMFADisabled = "user.mfa_disabled" AuditMFAReset = "user.mfa_reset" AuditRecoveryRegenerate = "user.recovery_codes_regenerated" AuditRecoveryCodeUsed = "user.recovery_code_used" // details: codes_left // A fresh proof of identity before a sensitive action; details: method (never a code). AuditReauth = "user.reauth" // The admin data route (documents written past the collections' rules); // the target is database/collection/id, never content. AuditDataCreate = "data.create" AuditDataUpdate = "data.update" AuditDataDelete = "data.delete" AuditDataRestore = "data.restore" AuditDataPurge = "data.purge" // A document moved to another organization by an administrator (target database/collection/id, // details: from, to), and a job that gives a collection's documents without one an organization // (details: org, job_id). AuditDataTransfer = "data.transfer" AuditDataAssignOrg = "data.assign_org" // A schema check started by an administrator; the target is the scope // (<database>/<collection>, <database> or the realm), details: collections, limit. AuditDataCheck = "data.check" // A schema migration started by an administrator (the target is data:<database>/<collection>, // details: dry_run, job_id), and a migration job that ended, by whoever started it (details: // database, collection, from, to, migrated, failed, complete; never a value). AuditDataMigrate = "data.migrate" AuditDataMigrated = "data.migrated" // A job cancelled or re-run by an administrator; the target is job:<id>, // details: function (and, for a re-run, the new job's id). AuditJobCancel = "job.cancel" AuditJobRerun = "job.rerun" // A scheduled function paused or resumed by an administrator; the target is // schedule:<database>/<function>. AuditSchedulePause = "schedule.pause" AuditScheduleResume = "schedule.resume" // An administrator started an export package (target export:<scope>; details: database, // collections, files, partial) and finished it (details: collections, documents, files, bytes, // complete). Never the content. AuditExport = "export" AuditExportDone = "export.done" // AuditExportAuth is an export that includes authentication data: users, password hashes, // organizations, memberships, teams, second factors and devices (details: collections). AuditExportAuth = "export.auth" // An administrator started an import (target import:<realm>; details: mode, dry_run, skip_invalid, // databases, source_realm) and finished it (details: mode, dry_run, files, complete and a count per // outcome: created, replaced, skipped, unchanged, conflict, invalid). Never the content. AuditImport = "import" AuditImportDone = "import.done" // An administrator ran `backd storage check`; details: ok, provider, bucket. AuditStorageCheck = "storage.check" // An administrator ran `backd storage reconcile`; details: delete, orphans, deleted. AuditStorageReconcile = "storage.reconcile" // An administrator ran `backd files regenerate`; details: version, missing_only, job_id. AuditVersionsRegenerate = "files.versions.regenerate" AuditSecretSet = "secret.set" // details: database ("": realm scope); never the value AuditSecretDelete = "secret.delete" // details: database AuditSecretsRotated = "secret.rotate_key" // by backd-server secret rotate-key; details: count // A field key was created, imported or deleted; target secret:realm/NAME, details: fingerprint, // generated. Never the key. AuditKeyCreate = "secret.key.create" AuditKeyDelete = "secret.key.delete" // A field key was rotated; details: fingerprint (the new one), previous, rewrapped. AuditKeyRotate = "secret.key.rotate" // An administrator read encrypted fields in plain through the data route; details: database, // collection, fields, documents. Never a value. AuditDataReveal = "data.reveal" // An administrator started an encryption migration, or rekeyed a field; and the job's result. AuditEncryptStart = "encrypt.start" // details: database, collection, fields, dry_run, job_id AuditEncryptRekey = "encrypt.rekey" // details: database, collection, field, generation AuditEncryptMigrate = "encrypt.migrate" // by the job; details: job_id, counts, retired_keys // AuditTriggerGapResolve is an administrator closing a recorded gap of the trigger dispatcher; // AuditTriggerRescan one re-emitting the changes of a collection. AuditTriggerGapResolve = "triggers.gap_resolve" AuditTriggerRescan = "triggers.rescan" )
Audit actions: security-sensitive changes and events, recorded in the realm's append-only audit trail.
const ( // ActorOffline is the CLI working directly on MongoDB (export and import). ActorOffline = "cli:offline" // ActorConfig applies realm.yaml's role and network seeds. ActorConfig = "config:realm.yaml" // ActorInstance is an operator with direct access to the instance's database and key // (`backd-server user mfa-reset`). ActorInstance = "instance" // ActorBootstrap is `backd-server bootstrap`. ActorBootstrap = "cli:bootstrap" // ActorSystem is backd itself, in the background (purging unverified accounts). ActorSystem = "system" // ActorAnonymous is a caller without credentials. ActorAnonymous = "anonymous" )
Actors that aren't a credential.
const ( ConsentAccepted = "accepted" ConsentWithdrawn = "withdrawn" ConsentMethodSignup = "signup" ConsentMethodPrompt = "prompt" ConsentMethodAPI = "api" ConsentMethodAdmin = "admin" )
Consent actions and the methods that give them (design/compliance.md §5.2).
const ( ScopeRead = authcore.ScopeRead ScopeWrite = authcore.ScopeWrite ScopeCall = authcore.ScopeCall MaxScopes = authcore.MaxScopes KeyLength = authcore.KeyLength PlainKey = authcore.PlainKey )
const ( EncryptOrigin = "backd:encrypt.migrate" // EncryptLease is how long a worker holds the job before another may take it; it renews after // every batch. EncryptLease = 10 * time.Minute // EncryptBatch is how many documents a batch reads. EncryptBatch = 200 )
The job that brings the stored documents of a collection in line with its encryption configuration (design/field-encryption.md §8).
const ( JournalWriting = "writing" // the upload started; the object may be partly stored JournalStored = "stored" // the object is stored; the document doesn't reference it yet JournalAttaching = "attaching" // a write is attaching a pending upload to a document JournalAttached = "attached" // a document references it JournalFailed = "failed" // it never became part of a document; its object was queued for deletion )
Journal states of an upload.
const ( // FileJournalGrace is how long an upload may stay writing or stored before a // worker treats it as abandoned. FileJournalGrace = time.Hour // FileDeletionLease is how long a worker owns a deletion it claimed. FileDeletionLease = 5 * time.Minute )
const ( IdempotencyRunning = "running" IdempotencyDone = "done" )
Idempotency record statuses.
const ( DefaultInvitationTTL = 7 * 24 * time.Hour MaxInvitationTTL = 90 * 24 * time.Hour )
Invitation lifetimes.
const ( JobQueued = "queued" JobRunning = "running" JobDone = "done" )
Job statuses.
const ( StepRunning = "running" StepDone = "done" StepFailed = "failed" StepTimedOut = "timed_out" StepCancelled = "cancelled" )
Step statuses.
const ( MagicLinkPurposeLink = "link" // a link and a code MagicLinkPurposeNoAccount = "no_account" // a message that there is no account for the address )
What a request sends.
const ( MagicLinkTTL = 10 * time.Minute MagicLinkCodeAttempts = MaxChallengeAttempts // ProviderEmail is the sign-in method of an address proved by a link or a code: an // identity of the user, recorded the first time, so that the rules about a user's last // way to sign in see it like any other. ProviderEmail = "email" )
MagicLinkTTL is how long a request's link and code work; MagicLinkCodeAttempts the wrong tries of its code.
const ( MethodTOTP = "totp" MethodRecovery = "recovery_code" // MethodPasskey is a passkey proving a sign-in step. MethodPasskey = "passkey" )
The second factors.
const ( // ChallengeMFA waits for a second factor of a user who has one. ChallengeMFA = "mfa" // ChallengeEnroll waits for a user in a required role to set a second factor up. ChallengeEnroll = "enroll" // ChallengeTOTPSetup is a TOTP secret waiting for its first code (the user is // setting authenticator app up). ChallengeTOTPSetup = "totp_setup" // ChallengeReauth is the token a re-authentication gave, bound to a session; // ChallengeReauthCode a code emailed to a user with no other proof. ChallengeReauth = "reauth" ChallengeReauthCode = "reauth_code" // ChallengeMagicLink is a request for a sign-in link and code (see magiclink.go). ChallengeMagicLink = "magic_link" // ChallengeConsent waits for a user to accept consents (see consents_signin.go). ChallengeConsent = "consent" )
The kinds of AuthChallenge.
const ( ChallengeTTL = 5 * time.Minute MaxChallengeAttempts = 5 )
Challenge limits.
const ( OAuthStateTTL = 10 * time.Minute LoginCodeTTL = time.Minute )
The lifetimes of the two short-lived records of the redirect flow.
const ( IntentSignIn = "signin" IntentLink = "link" )
Intents of a sign-in attempt.
const ( AuditOrgDelete = "org.delete" // details: by, job_id (access ended at once) AuditOrgDeleted = "org.deleted" // the cleanup finished; details: job_id, counts (never content) AuditOrgReactivate = "org.reactivate" // details: slug // AuditTeamDeleted: the cleanup after a team was deleted finished; the target is org:<id>. AuditTeamDeleted = "org.team_deleted" // details: team, job_id, counts (never content) )
Audit actions of deletions; the target is org:<id>.
const ( DomainPending = "pending" // the challenge is issued, the record not seen yet DomainVerified = "verified" // the record was seen, and is seen again every recheck DomainLapsed = "lapsed" // it was verified and the record is gone )
The states of a domain claim.
const ( AuditOrgDomainAdded = "org.domain.added" // details: domain AuditOrgDomainVerified = "org.domain.verified" // details: domain, again (it was lapsed) AuditOrgDomainLapsed = "org.domain.lapsed" // details: domain AuditOrgDomainRemoved = "org.domain.removed" // details: domain, by AuditOrgDomainSettings = "org.domain.settings" // details: domain, discoverable, link_accounts )
Audit actions of verified domains; the target is org:<id>. Details never hold the challenge.
const ( // DomainVerifyPerHour is how many times a manager may ask to check one domain in an hour. DomainVerifyPerHour = 6 // ChallengeLabel is the name under the domain that holds the record. ChallengeLabel = "_backd-challenge" )
Limits of the verification.
const ( OrgMemberJoinedOrigin = "backd:org.member_joined" OrgMemberLeftOrigin = "backd:org.member_left" OrgRolesChangedOrigin = "backd:org.roles_changed" )
Origins of the jobs that call the hooks.
const ( LeftByThemselves = "left" LeftRemoved = "removed" LeftErased = "erased" )
Why a member left an organization (the `reason` of on_member_left).
const ( BindUser = "user" // only that user BindEmail = "email" // the signed-in user whose verified address matches BindNone = "none" // anyone signed in who holds the link )
Bindings of an invitation: who may accept it.
const ( AuditOrgInviteCreate = "org.invitation_create" // details: invitation, binding, roles, teams, sent AuditOrgInviteLink = "org.invitation_link" // a new link was issued; details: invitation AuditOrgInviteAccept = "org.invitation_accept" // details: invitation, user AuditOrgInviteRevoke = "org.invitation_revoke" // details: invitation )
Audit actions of invitations; the target is org:<id>, details never hold a token.
const ( OrgActive = "active" OrgOrphaned = "orphaned" // its last manager was erased; members keep access OrgDeleted = "deleted" )
Statuses of an organization.
const ( AuditOrgCreate = "org.create" // details: by (self, admin), creator AuditOrgUpdate = "org.update" // details: fields AuditOrgMemberAdd = "org.member_add" // details: user, roles, by (invitation, admin) AuditOrgMemberLeave = "org.member_leave" // details: user AuditOrgMemberRemove = "org.member_remove" // details: user AuditOrgRoles = "org.roles" // details: user, added, removed AuditOrgClaims = "org.claims" // details: keys AuditOrgOwner = "org.owner_assign" // details: user )
Audit actions of organizations; the target is org:<id>, details never hold content.
const ( // FindOrgsPerAddress and FindOrgsPerIP are how many times an hour an address, and a client, may // ask for it. FindOrgsPerAddress = 3 FindOrgsPerIP = 30 )
The "which companies am I in?" email (design/scoped-sessions.md §5.4).
const ( AuditOrgSSOSet = "org.sso.set" // details: provider, enabled, secret_changed AuditOrgSSODeleted = "org.sso.deleted" // details: provider AuditOrgSSOLogin = "org.sso.login" // a person signed in through a connection; details: user, provider, joined AuditOrgSSODisabled = "org.sso.disabled" // backd disabled a connection; details: provider, reason AuditOrgSSOLinked = "org.sso.linked" // an account was linked through a connection by a verified domain; details: user, provider, by )
Audit actions of connections; the target is org:<id>, details never hold the secret.
const ( MaxConnectionEmailDomains = 20 MaxConnectionNativeIDs = 10 MaxConnectionBlocked = 1000 // MaxConnectionSecretBytes is the longest client secret a connection takes. MaxConnectionSecretBytes = 1024 )
Limits of a connection's lists.
const ( AuditOrgTeamRoleGrant = "org.team_role_grant" // details: team, user, role, from, until AuditOrgTeamRoleChange = "org.team_role_change" // details: team, user, role, from, until AuditOrgTeamRoleRevoke = "org.team_role_revoke" // details: team, user, role )
Audit actions of team roles; the target is org:<id>.
const ( AuditOrgTeamCreate = "org.team_create" // details: team, name, roles AuditOrgTeamUpdate = "org.team_update" // details: team, name, roles AuditOrgTeamDelete = "org.team_delete" // details: team AuditOrgTeamMemberAdd = "org.team_member_add" // details: team, user AuditOrgTeamMemberRemove = "org.team_member_remove" // details: team, user )
Audit actions of teams; the target is org:<id>.
const ( AuditOrgTemplateSave = "org.template_save" // details: kind, locale, version AuditOrgTemplateDelete = "org.template_delete" // details: kind, locale AuditOrgTemplateTest = "org.template_test" // details: kind, locale )
Audit actions of templates; the target is org:<id>, details never hold the text.
const ( // OrgTemplateVersions is how many previous versions of a template are kept. OrgTemplateVersions = 20 // OrgTemplateTestsPerHour is how many test sends an organization may make. OrgTemplateTestsPerHour = 10 )
Limits of owner templates.
const ( AuditPasskeyRegistered = "passkey.registered" AuditPasskeyRemoved = "passkey.removed" // details also: by (self or admin) )
Audit events of passkeys; the target is the user, details: passkey (backd's id), name.
const ( AuditPasskeyLogin = "passkey.login" AuditPasskeyLoginFailed = "passkey.login_failed" AuditPasskeyCloneSuspected = "passkey.clone_suspected" )
Audit events of passkey sign-ins. passkey.login_failed carries the reason.
const ( PasswordNoticeOrigin = "backd:password.notify" PasswordNoticeLock = "password-notice" // PasswordNoticeLease is how long a worker holds the job before another may take it; the // worker renews it after every batch. PasswordNoticeLease = 10 * time.Minute // PasswordNoticeBatch is how many users a batch looks at. PasswordNoticeBatch = 100 )
PasswordNoticeOrigin is the origin of the job that tells the users with an expired password to choose a new one (design/breach-response.md §4); PasswordNoticeLock lets only one run at a time.
const ( PortableCreated = "created" PortableReplaced = "replaced" PortableSkipped = "skipped" PortableUnchanged = "unchanged" PortableConflict = "conflict" PortableInvalid = "invalid" )
Import outcomes of one portable document.
const ( PushPlan = "plan" PushBatch = "batch" PushDeliver = "deliver" )
The kinds of push job.
const ( PushBatchSize = 1000 PushUnitSize = 100 )
Sizes of what a send is split into.
const ( ReauthPassword = "password" ReauthEmailCode = "email_code" // ReauthTOTP and ReauthRecovery are the second factors' own names. ReauthTOTP = MethodTOTP ReauthRecovery = MethodRecovery // ReauthPasskey is a passkey as the proof: for a user who has one, with or without TOTP. ReauthPasskey = MethodPasskey )
The proofs (the method of a re-authentication).
const ( ReauthCodeTTL = 10 * time.Minute ReauthCodeAttempts = MaxChallengeAttempts )
ReauthCodeTTL and the attempts a code allows.
const ( // CheckOrigin is the origin of a schema check's job. CheckOrigin = "backd:schema.check" // CheckLock is the exclusive name of a schema check's job: one at a time. CheckLock = "schema-check" // CheckLease is how long a worker holds a check before another may claim it; the // worker renews it after every batch. CheckLease = 10 * time.Minute // CheckMaxDuration is the longest a check attempt runs before it stops and // says its report is incomplete. CheckMaxDuration = 6 * time.Hour // DefaultCheckLimit and MaxCheckLimit bound how many invalid documents a // report lists per collection. DefaultCheckLimit = 100 MaxCheckLimit = 1000 // MaxCheckProblems is how many problems a report lists per document. MaxCheckProblems = 5 )
const ( SchemaMigrateOrigin = "backd:schema.migrate" // SchemaMigrateLease is how long a worker holds the job before another may take it; it // renews after every batch. SchemaMigrateLease = 10 * time.Minute // SchemaMigrateBatch and SchemaMigrateBatchBytes bound one batch: documents and bytes of fields. SchemaMigrateBatch = 500 SchemaMigrateBatchBytes = 4 << 20 // SchemaMigrateRate is how many documents a second a job migrates at most. SchemaMigrateRate = 1000 // MaxSchemaMigrateFailures is how many failed documents a job lists; past it only the count. MaxSchemaMigrateFailures = 1000 )
The job that migrates the documents of a versioned collection to its current schema version (design/schema-versioning.md §8): one job per collection, started by a worker at every start or by an administrator, at most one unfinished at a time.
const ( MigrateComplete = "complete" MigratePartial = "partial" MigrateCancelled = "cancelled" )
Job endings, in SchemaMigrateJob.Ending.
const ( FailThrew = "threw" // the migration threw FailAsync = "async" // it returned a promise FailNotJSON = "not_json" // its result isn't JSON, or isn't an object FailNoStep = "no_step" // there is no migration from the document's version FailTimeout = "timeout" // it ran out of time FailInvalid = "invalid" // the result doesn't match the current schema FailFile = "file_field" // it changed a file field FailConflict = "conflict" // the result breaks a unique index FailPlaintext = "write" // the write failed FailMemory = "memory" FailExecutor = "executor" FailUnreadable = "unreadable" )
Failure kinds of a document: what stopped it from migrating.
const ( // AuditUserLogin is a successful sign-in by a user without an admin role (administrators // record admin.login, passkeys passkey.login, organization connections org.sso.login). // Details: strategy, methods, session_id. Off by default. AuditUserLogin = "user.login" // AuditUserStepFailed is a later step that failed: a wrong authenticator or recovery code, or // a step answered with the wrong method. The target is the user. Details: step (the method // that was tried), strategy, reason, attempts and throttled as for user.login_failed. A failed // passkey step is passkey.login_failed. AuditUserStepFailed = "user.step_failed" // AuditUserLoginFailed is a first step that failed. The target is the user, or `anonymous` // with address_hash when the address has no account. Details: strategy, reason, attempts // (when the window saw more than one) and throttled. AuditUserLoginFailed = "user.login_failed" )
Sign-in entries of the audit trail (design/sign-in-audit.md). Like every audit action they are switched on or off with `audit.entries`.
const ( ReasonInvalidCredentials = "invalid_credentials" // a wrong password and an unknown address look the same ReasonDisabled = "disabled" ReasonUnverified = "unverified" ReasonNetwork = "network" ReasonThrottled = "throttled" ReasonPasswordExpired = "password_expired" ReasonInvalidCode = "invalid_code" ReasonInvalidLink = "invalid_link" )
Reasons of a failed sign-in. The app is told what it is told today; the trail may be more precise because only administrators read it.
const ( // ExportOrigin is the origin of the job that builds an export. ExportOrigin = "backd:account.export" // ExportLease is how long a worker holds an export job before another may take it; building // copies files, so it renews between steps. ExportLease = 20 * time.Minute // ExportMinGap is the least time between two exports a user asks for themselves. ExportMinGap = 24 * time.Hour )
The export of a user's personal data (design/compliance.md §4): a request is a UserExport record and a job that builds the package; the record is what the user lists and downloads from, and it outlives the job.
const ( ExportQueued = "queued" ExportRunning = "running" ExportReady = "ready" // the package is stored and can be downloaded until ExpiresAt ExportFailed = "failed" // gave up; the user may ask again ExportExpired = "expired" // the package was deleted at the end of its retention )
Export statuses.
const APIKeyPrefix = "bdk_"
APIKeyPrefix starts every API key; see SessionTokenPrefix.
const AssignOrgOrigin = "backd:org.assign"
AssignOrgOrigin is the origin of the job that gives documents an organization.
const AuditConsentRecorded = "user.consent_recorded" // details: consent, version, action, evidence
AuditConsentRecorded is the audit action of an administrator recording a consent for a user.
const AuditConsentsNotified = "consents.notify"
AuditConsentsNotified is the audit action of an administrator asking users to review a consent; details: consent, version, queued, limited.
const AuditOrgOrphaned = "org.orphaned" // details: user
AuditOrgOrphaned is recorded when an organization loses its last manager to an erase.
const AuditOrgRequireMFA = "org.require_mfa" // details: value
AuditOrgRequireMFA is recorded when an organization turns its second-factor requirement on or off.
const AuditOrgSSORequired = "org.sso_required"
AuditOrgSSORequired is recorded when sso_required is turned on or off; details: value, and when it is turned on without_sso and revoked, when it is released by backd the reason.
const CallbackTokenPrefix = "bdf_"
CallbackTokenPrefix starts every callback token: the credential a function uses to reach the realm's data (ctx.db, ctx.admin.db) for the duration of one invocation.
const ConsentPseudonymSecret = registry.ConsentPseudonymSecret
ConsentPseudonymSecret is the realm secret that keys the pseudonym consent records keep of an erased person. backd makes it the first time an erase needs it; changing it stops matching records to addresses made before.
const EmailNoConsent = "no_consent"
EmailNoConsent is the status a gated email or push answers for a user who doesn't hold the consent it requires.
const (
EraseOrigin = "backd:account.erase"
)
What an erase job is called in the job list and in the audit trail.
const ImageOrigin = "backd:image.versions"
ImageOrigin is the origin of the job that makes a file's image versions.
const InvitationPrefix = "bdi_"
InvitationPrefix starts every invitation token.
const MagicLinkLoginMethod = "link"
MagicLinkLoginMethod is the first factor a link or a code stands for in sessions and challenges.
const MaxDeviceTokenBytes = 4096
MaxDeviceTokenBytes is the largest token a device may register.
const MaxInvitationUses = 1000
MaxInvitationUses is the most an open link may be used.
const MaxOpenPendingUploads = 20
MaxOpenPendingUploads is how many unused pending uploads one caller may hold.
const MaxPasskeys = 10
MaxPasskeys is how many passkeys a user may register.
const MaxPasswordLength = 128
MaxPasswordLength is the longest accepted password, in characters.
const MaxSteps = 100
MaxSteps is how many steps a job or an invocation record keeps: the first half and the latest half of what a function reported.
const OnSignupOrigin = "backd:account.on_signup"
OnSignupOrigin is the origin of the job that calls account.on_signup.
const OrgDeleteOrigin = "backd:org.delete"
OrgDeleteOrigin is the origin of the job that applies the collections' on_org_delete.
const OrgInvitationPrefix = "bdo_"
OrgInvitationPrefix starts every organization invitation token.
const OrgTemplateRealPreviewsPerHour = 30
OrgTemplateRealPreviewsPerHour is how many previews with real data (which call the data hook) an organization may make.
const ProviderPassword = "password"
ProviderPassword is the identity provider for email + password sign-in. Its subject is the user's id, so it doesn't depend on the email.
const PushOrigin = "backd:push"
PushOrigin is the origin of the jobs of a send.
const RecoveryCodeCount = 10
RecoveryCodeCount is how many recovery codes a user gets.
const ResultCancelled = "cancelled"
ResultCancelled is the result status of a job an administrator cancelled.
const ResultSkipped = "skipped"
ResultSkipped is the result status of a scheduled run that didn't happen because the function's previous run hadn't finished (overlap: skip).
const SSOScopeRealm = "realm"
SSOScopeRealm is the scope of the realm's own providers.
const SecretTypeKey = "key"
SecretTypeKey marks a secret as a field key (design/field-encryption.md §3.1): 32 bytes the developer holds a copy of, that only field encryption reads.
const SessionTokenPrefix = "bds_"
SessionTokenPrefix starts every session token, so tokens are easy to recognize (e.g. by secret scanners) and to tell apart from API keys.
const TOTPSetupTTL = 15 * time.Minute
TOTPSetupTTL is how long a TOTP secret waits for its first code.
const TeamDeleteOrigin = "backd:team.delete"
TeamDeleteOrigin is the origin of the job that applies the collections' on_team_delete.
const TeamRoleHistory = 90 * 24 * time.Hour
TeamRoleHistory is how long a grant stays visible after its window ended.
const UnknownOrgScope = "?"
UnknownOrgScope is the organization scope of an attempt started at the address of an organization that can't be signed in to (it is not there, or is deleted): the attempt goes on like any other, so nothing says so, and ends in the refusal a stranger to a real organization gets.
Variables ¶
var ( ErrKeyNameTaken = errors.New("an API key with this name already exists") ErrKeyNotFound = errors.New("API key not found") )
var ( ErrNotFound = errors.New("user not found") ErrEmailTaken = errors.New("email is already registered") // ErrIdentityExists means the user already has an identity of that provider, // or that provider account belongs to another user. ErrIdentityExists = errors.New("identity already exists") // ErrLastSignInMethod means unlinking would leave the user no way to sign in. ErrLastSignInMethod = errors.New("the last sign-in method can't be removed") // ErrBusy means no password-hashing slot freed up before the deadline. ErrBusy = errors.New("too many password operations in progress; try again later") )
var ( // ErrUnknownConsent: the realm declares no consent of that name. ErrUnknownConsent = errors.New("unknown consent") // ErrUnknownConsentVersion: the version isn't one the realm has a text for. ErrUnknownConsentVersion = errors.New("unknown consent version") // ErrConsentRequiredForAccount: a required consent can't be withdrawn without // deleting the account. ErrConsentRequiredForAccount = errors.New("a required consent can't be withdrawn: delete the account instead") )
var ( ErrKeyValue = authcore.ErrKeyValue PortableCollections = authcore.PortableCollections PortableSealed = authcore.PortableSealed )
var ( ParseScope = authcore.ParseScope ParseScopes = authcore.ParseScopes NewSecretCipher = authcore.NewSecretCipher SealWith = authcore.SealWith OpenWith = authcore.OpenWith KeyFingerprint = authcore.KeyFingerprint DecodeKey = authcore.DecodeKey NewKey = authcore.NewKey PortableReset = authcore.PortableReset PortableToPlain = authcore.PortableToPlain PortableWithoutSecrets = authcore.PortableWithoutSecrets ExportKey = authcore.ExportKey OrgScope = authcore.OrgScope )
var ( // ErrPushNotConfigured: the realm has no push: section. ErrPushNotConfigured = errors.New("push notifications are not configured in this realm") // ErrPlatformNotEnabled: the realm has no provider for the platform. ErrPlatformNotEnabled = errors.New("that platform is not enabled in this realm") ErrPushUnavailable = errors.New("push notifications are unavailable: a secret the providers need is not set") ErrWebKeyUnavailable = errors.New("web push is not enabled in this realm") )
var ( // ErrEmailChangeDisabled means the realm doesn't let users change their // own address (account.allow_email_change). ErrEmailChangeDisabled = errors.New("this realm doesn't allow changing the email address") // ErrSameEmail means the new address is the one the user already has. ErrSameEmail = errors.New("that is already the address of this account") )
var ( // ErrAlreadyErased means the user was erased and nothing is left to do. ErrAlreadyErased = errors.New("this user was already erased") // ErrUserErased means an operation that needs a user was asked of an // erased one: all that is left is a tombstone. ErrUserErased = errors.New("this user was erased") )
var ( // ErrInvitationRequired means the realm only accepts sign-ups with an invitation. ErrInvitationRequired = errors.New("sign-up requires an invitation") // ErrInvalidInvitation covers unknown, used, expired and mismatched // invitations alike. ErrInvalidInvitation = errors.New("invalid or expired invitation") )
var ( // ErrJobFinished means the job is done: there is nothing left to cancel. ErrJobFinished = errors.New("the job has already finished") // ErrJobNotFinished means a job can't be re-run while it may still run. ErrJobNotFinished = errors.New("the job hasn't finished: cancel it, or wait for it to end") // ErrJobNotFunction means the job isn't a function call: backd's own // emails and erasures are not cancelled or re-run by hand. ErrJobNotFunction = errors.New("only a function's job can be cancelled or re-run") )
var ( // ErrSecretExists means a secret already has that name; a key is never overwritten by creating one. ErrSecretExists = errors.New("a secret with that name already exists") // ErrSecretIsKey means a plain secret write names a key: keys change only through the key calls. ErrSecretIsKey = errors.New("this name is a field key: keys are created, rotated and deleted as keys") )
Errors of key secrets.
var ( // ErrRotationPending means a rotation started and was not finished: resume it first. ErrRotationPending = errors.New("a rotation of this key is unfinished: resume it first") // ErrNoRotation means there is nothing to resume. ErrNoRotation = errors.New("no rotation of this key is pending") )
Errors of a rotation.
var ( // ErrMagicLinkDisabled: the realm doesn't have magic links. ErrMagicLinkDisabled = errors.New("magic links are not enabled in this realm") // ErrInvalidMagicLink answers a link or a code that is unknown, used or expired. ErrInvalidMagicLink = errors.New("the link or the code is invalid or has expired") // ErrNoRedirect: the request has no place to send the browser (no redirect_to, and the // realm has no sign_in.app_url): the code is the way. ErrNoRedirect = errors.New("the request has nowhere to send the browser") )
var ( // ErrInvalidChallenge answers a challenge that is unknown, used, expired or out of // attempts: the same for all of them. ErrInvalidChallenge = errors.New("the challenge is invalid or expired") // ErrSecondStepRequired is what the single-step entry points answer when the user // needs a second step (the HTTP layer uses the full outcome instead). ErrSecondStepRequired = errors.New("a second factor is required") // ErrMFADisabled: the realm doesn't let users turn MFA on. ErrMFADisabled = errors.New("multi-factor authentication is not enabled in this realm") )
var ( ErrStrategyRequired = registry.ErrStrategyRequired ErrUnknownStrategy = registry.ErrUnknownStrategy )
ErrStrategyRequired and ErrUnknownStrategy answer a first-step call that names no strategy when several start with its method, and one that names a strategy that does not exist or starts with another method.
var ( // ErrMFARequiredByRole: a role of the user requires MFA, so it can't be turned off. ErrMFARequiredByRole = errors.New("a role of this user requires multi-factor authentication") ErrMFAUnavailable = errors.New("multi-factor authentication needs the instance's secrets key (BACKD_SECRETS_KEY)") // ErrMFAAlreadyEnabled: the user already has a second factor. ErrMFAAlreadyEnabled = errors.New("multi-factor authentication is already enabled") // ErrMFANotEnabled: the user has no second factor. ErrMFANotEnabled = errors.New("multi-factor authentication is not enabled") )
var ( // ErrAccountExists: an account has the provider's address, but it can't be // linked on the provider's word alone: sign in another way and link explicitly. ErrAccountExists = errors.New("an account with that address exists") // ErrLinkConflict: the provider account belongs to another user, or the user // already has an identity of that provider. ErrLinkConflict = errors.New("that provider account can't be linked to this user") // ErrSignInRefused: the account can't sign in (disabled, or from this network); // the caller is not told which. ErrSignInRefused = errors.New("sign-in refused") // ErrEmailRequired: the provider gave no address and accounts need one. ErrEmailRequired = errors.New("the provider gave no email address") )
var ( // ErrDomainsDisabled: the realm doesn't let organizations prove domains (organizations.domains). ErrDomainsDisabled = errors.New("verified domains are not enabled in this realm") // ErrDomainNotFound: the organization has no claim on that domain. ErrDomainNotFound = errors.New("the organization has no claim on that domain") // ErrDomainTaken: another organization has verified the domain. ErrDomainTaken = errors.New("another organization has verified that domain") // ErrDomainsLimit: the organization has the most claims it may. ErrDomainsLimit = errors.New("the organization has the most domains it may claim") // ErrDomainExists: the organization already claimed the domain. ErrDomainExists = errors.New("the organization already claimed that domain") )
var ( // ErrInvalidOrgInvitation covers unknown, expired, revoked and used-up tokens alike. ErrInvalidOrgInvitation = errors.New("invalid or expired invitation") // ErrInvitationNotForYou: the token is valid but bound to someone else. ErrInvitationNotForYou = errors.New("this invitation is not for you") // ErrInvitationsLimit: the organization has the most pending invitations it may. ErrInvitationsLimit = errors.New("the organization has the most pending invitations it may") // ErrNeedsSecretsKey: sending the link by email keeps it sealed with the instance's key. ErrNeedsSecretsKey = errors.New("sending an invitation by email needs the instance's secrets key (BACKD_SECRETS_KEY)") )
var ( // ErrOrgsDisabled: the realm doesn't enable organizations. ErrOrgsDisabled = errors.New("organizations are not enabled in this realm") // ErrNotOrgMember covers a non-member and an unknown organization alike. ErrNotOrgMember = errors.New("not a member of that organization") // ErrOrgForbidden: the caller is a member without the capability the action needs. ErrOrgForbidden = errors.New("your roles in this organization don't allow that") // ErrOrgCreateNotAllowed: the realm's create rule refused the caller. ErrOrgCreateNotAllowed = errors.New("you are not allowed to create organizations") // ErrOrgLimit: the caller reached max_created_per_user. ErrOrgLimit = errors.New("the limit of organizations created by one user is reached") // ErrMembershipLimit: the user reached max_memberships_per_user. ErrMembershipLimit = errors.New("that user is a member of the most organizations a user may join") // ErrLastOrgManager: the last member who can manage the organization can't leave or lose that. ErrLastOrgManager = errors.New("the organization needs at least one member who can manage it") // ErrSlugTaken: another organization has that slug. ErrSlugTaken = errors.New("that slug is taken") // ErrOrgUserNotFound: the user an administrator named doesn't exist. ErrOrgUserNotFound = errors.New("user not found") // ErrOrgRequiresMFA: the organization requires a second factor and the session used none. ErrOrgRequiresMFA = errors.New("this organization requires a second factor: sign in again with one") // ErrRequireMFANotAllowed: realm.yaml's organizations.allow_require_mfa is false. ErrRequireMFANotAllowed = errors.New("this realm doesn't let organizations require a second factor (organizations.allow_require_mfa)") // ErrSSORequired: the organization's people sign in through its connection only. ErrSSORequired = errors.New("this organization requires its sign-in connection: use the provider's button") // ErrSSONotReady: sso_required can't be turned on yet. ErrSSONotReady = errors.New("connect a provider and sign in through it before requiring it") // ErrSSOSession: the session was opened through an organization's connection, which can't change // what protects the person's account. ErrSSOSession = errors.New("this action needs a sign-in with your own credentials, not through an organization's connection") // ErrTeamNameTaken: the organization has a team of that name. ErrTeamNameTaken = errors.New("the organization has a team with that name") // ErrTeamLimit and ErrMemberTeamsLimit: max_teams_per_org and max_teams_per_member. ErrTeamLimit = errors.New("the organization has the most teams it may") ErrMemberTeamsLimit = errors.New("that member belongs to the most teams a member may") // ErrOrgNotActive: the organization is deleted. ErrOrgNotActive = errors.New("the organization is not active") )
var ( // ErrSSODisabled: the realm doesn't let organizations set up sign-in (organizations.sso). ErrSSODisabled = errors.New("organization sign-in is not enabled in this realm") // ErrSSOProviderUnknown: the realm doesn't offer that provider to organizations. ErrSSOProviderUnknown = errors.New("that provider is not available to organizations") // ErrConnectionNotFound: the organization has no connection with that provider. ErrConnectionNotFound = errors.New("the organization has no sign-in connection with that provider") // ErrConnectionUnusable: the connection was disabled because the manager who last set it no // longer holds the roles it gives on joining. ErrConnectionUnusable = errors.New("the sign-in connection can't be used") // ErrSSOLimit: the organization has the most connections the realm allows. ErrSSOLimit = errors.New("the organization has the most sign-in connections it may") )
var ( // ErrTemplateNotCustomizable: the kind isn't listed in email.customizable. ErrTemplateNotCustomizable = errors.New("that kind of email can't be customized (email.customizable)") // ErrTemplateTestLimit: too many test sends. ErrTemplateTestLimit = errors.New("too many test emails for this organization; try again later") )
var ( // ErrReauthRequired: the action needs a fresh proof the request didn't have. ErrReauthRequired = errors.New("a fresh proof of identity is required") // ErrReauthMethod: that proof isn't the kind this user gives. ErrReauthMethod = errors.New("that proof is not accepted for this user") )
var ( // ErrInvalidCredentials is the one answer to a failed login, whatever // the reason (unknown email, wrong password, no password, disabled). ErrInvalidCredentials = errors.New("invalid email or password") // ErrUnauthenticated means the token is unknown, expired, revoked or // belongs to a disabled user. ErrUnauthenticated = errors.New("invalid or expired token") // ErrSessionUnscoped: in a realm with organizations every session belongs to one, and this one // does not (it was opened before the realm had them, or by another way): the person signs in // again, to an organization. Operators, who run the realm and belong to none, are the exception. ErrSessionUnscoped = errors.New("this session belongs to no organization: sign in to one") // ErrSignupClosed means the realm doesn't allow self sign-up. ErrSignupClosed = errors.New("sign-up is not open in this realm") // ErrEmailNotVerified answers a login with the right password for an // address that isn't verified yet, in a realm that requires it. It is // only returned after the password was checked, so it reveals nothing // to someone who doesn't have it. ErrEmailNotVerified = errors.New("verify your email address before signing in") )
var DefaultArgon2Params = Argon2Params{Memory: 64 * 1024, Time: 3, Threads: 1}
DefaultArgon2Params follow RFC 9106's second recommendation (64 MiB, 3 passes), with one thread per hash: concurrency is capped per instance instead.
var ErrAssignRunning = errors.New("an assignment of organizations in this collection is already queued or running")
ErrAssignRunning means an assignment of the same collection is queued or running.
var ErrCodeRequired = errors.New("this account uses a second factor: send a code")
ErrCodeRequired means the account uses a second factor and the request carried no code.
var ErrCredentialRequired = errors.New("this is the only credential that lets an administrator role sign in: add another way first")
ErrCredentialRequired: removing the passkey would leave a holder of an admin role with no way to complete any strategy that role allows.
var ErrEmailNotConfigured = errors.New("this realm doesn't send email")
ErrEmailNotConfigured means the realm has no email section: it sends no email.
var ErrEpochNotLater = errors.New("a password epoch as late as this one already exists")
ErrEpochNotLater means the realm already has a password epoch as late as now: it only moves forward (a clock behind the one that set it, or two commands in the same instant).
var ErrExportRunning = errors.New("an export of this user is already in progress")
ErrExportRunning means an export of that user is queued or running.
var ErrInvalidCallback = errors.New("invalid or expired callback token")
ErrInvalidCallback means a callback token is malformed, forged or expired.
var ErrInvalidPasskey = errors.New("the passkey did not work")
ErrInvalidPasskey is every way a passkey sign-in can fail, whatever the cause: unknown credential, bad signature, wrong origin, expired challenge, a banned or unverified user, a cloned key. The reason goes to the audit log, never to the caller.
var ErrInvalidToken = errors.New("invalid, expired or used token")
ErrInvalidToken is every way a token can be refused (unknown, expired, used, or for another purpose); callers answer them all the same.
var ErrInvitationNeedsAddress = errors.New("an invitation sent by email needs an email address")
ErrInvitationNeedsAddress means an invitation to be sent by email has no address to send it to.
var ErrJobExclusive = errors.New("an exclusive job is not finished yet")
ErrJobExclusive means a job with the same exclusive name is not finished yet.
var ErrJobExists = errors.New("job already exists")
ErrJobExists means a job with that id was already enqueued.
var ErrNetworksOutsideRealm = errors.New("admin networks must lie within the realm's admin.allowed_networks")
ErrNetworksOutsideRealm means a user's admin networks aren't all inside the realm's admin.allowed_networks.
var ErrNoKey = errors.New("no such key")
ErrNoKey means the secret is missing or is not a key.
var ErrNoPasswordEpoch = errors.New("no password epoch is set: expire the passwords first")
ErrNoPasswordEpoch means no password was ever expired for the whole realm: there is nobody to notify.
var ErrNotAllowedOnBehalf = errors.New("only API keys can act on behalf of a user")
ErrNotAllowedOnBehalf means a caller other than an API key tried to act on behalf of a user.
var ErrNotPortable = errors.New("this store can't export or import authentication data")
ErrNotPortable means the realm's store can't export authentication data.
var ErrOnBehalfOfAdmin = errors.New("this user holds an admin role: a key cannot act as an administrator")
ErrOnBehalfOfAdmin means a key tried to act as a user who holds an admin role. An administrator cannot be faked: acting as a user must never bring more privileges than the key has, so the administrators' own credentials are the only way to the administrators' rights.
var ErrOrgInvitationGone = errors.New("the invitation ended before its email was sent")
ErrOrgInvitationGone means the invitation ended (revoked, used up, expired or its organization deleted) before its email was written: nothing is sent.
var ErrOrgNotDeleted = errors.New("the organization is not deleted")
ErrOrgNotDeleted: only a deleted organization can be reactivated.
var ErrPasskeyLimit = errors.New("a user can have at most 10 passkeys")
ErrPasskeyLimit: the user has MaxPasskeys passkeys already.
var ErrPasskeysDisabled = errors.New("passkeys are not enabled in this realm")
ErrPasskeysDisabled: the realm has not enabled passkeys (auth.passkeys.enabled).
var ErrPasswordExpired = errors.New("this password has expired: set a new one with a password reset, or ask an administrator")
ErrPasswordExpired means the password is correct but was set before the realm's password epoch or the user's own expiry: it opens nothing until the user chooses a new one (design/breach-response.md §3).
var ErrPasswordRequired = errors.New("the account's password is required to confirm the address")
ErrPasswordRequired means a verification link was used without the password of the account it verifies.
var ( // ErrPushSendNotFound: no send has that id. ErrPushSendNotFound = errors.New("push send not found") )
var ErrRegenerateRunning = errors.New("a regeneration of this field's versions is already queued or running")
ErrRegenerateRunning means a regeneration of the same field is queued or running.
var ErrResetLinkUser = errors.New("the user is disabled or erased: a reset link would open nothing")
ErrResetLinkUser means no reset link can be made for the user: they are disabled or erased.
var ErrSecretNotFound = errors.New("secret not found")
ErrSecretNotFound means no secret is stored at that scope and name.
var ErrSecretsNotConfigured = errors.New("the secrets master key is not configured (BACKD_SECRETS_KEY)")
ErrSecretsNotConfigured means BACKD_SECRETS_KEY isn't set: secrets can be neither stored nor read.
var ErrSelfMFAReset = errors.New("an administrator can't reset their own second factor")
ErrSelfMFAReset: an administrator can't reset their own second factor.
var ErrTeamRoleLimit = errors.New("that member holds the most team roles a member may")
ErrTeamRoleLimit: the member holds the most team role grants one may.
var ErrTeamRoleNotHeld = errors.New("the member doesn't hold that role in the team")
ErrTeamRoleNotHeld: the member doesn't hold the team role whose window a request changes.
var ErrTemplatePreviewLimit = errors.New("too many previews with real data for this organization; try again later")
ErrTemplatePreviewLimit: too many previews with real data.
var ErrUndeclaredRole = errors.New("role is not declared in realm.yaml")
ErrUndeclaredRole means a role isn't declared in the realm's realm.yaml.
var ErrUserDisabled = errors.New("user is disabled")
ErrUserDisabled means the user an API key acts for is disabled.
Functions ¶
func ActorOf ¶ added in v0.8.2
ActorOf is who the context's audit source says is acting: "user:<id>", "key:<name>", or an Actor* constant.
func AnonymizedCollections ¶ added in v0.9.1
func AnonymizedCollections() []string
AnonymizedCollections are the portable collections an anonymized export carries.
func AnonymousEmail ¶ added in v0.9.1
AnonymousEmail is the address an anonymized export gives the user with that id.
func CheckOrgTemplate ¶ added in v0.8.3
CheckOrgTemplate compiles a draft for kind and renders it with sample data, so a problem shows when it is written, with where it is. It returns what the sanitizer dropped from the sample.
func CheckPassword ¶
CheckPassword applies the length policy and returns the password in Unicode NFKC form, which is what gets hashed. Lengths count characters.
func CleanProfile ¶ added in v0.8.2
CleanProfile keeps the known profile fields that are not empty, without control characters and cut to a sane length. It is what a provider (or the browser, for Apple's first authorization) says about the person: a hint for the app, never trusted.
func CompletionJobID ¶ added in v0.8.0
CompletionJobID is the deterministic id of the notification of a job's end.
func ConnectionMethod ¶ added in v0.9.3
ConnectionMethod is the first method of a session opened through the connection of an organization with a provider: not the provider's name alone, which the realm's own providers use too.
func ConnectionMethodPrefix ¶ added in v0.9.3
ConnectionMethodPrefix starts the first method of every session an organization's connection opened.
func ConnectionProvider ¶ added in v0.9.13
func ConnectionProvider(c OrgConnection) *registry.Provider
ConnectionProvider is the provider an organization's connection stands for.
func DefaultHashConcurrency ¶
func DefaultHashConcurrency(p Argon2Params) int
DefaultHashConcurrency is how many password hashes may run at once when PASSWORD_HASH_CONCURRENCY isn't set: no more than the Go scheduler's processors (GOMAXPROCS, which follows the container's CPU limit), and no more than fit in half the memory limit (the cgroup's, or GOMEMLIMIT), so a flood of logins can't get the process killed for running out of memory. runtime.NumCPU is not used: in a container it reports the host's CPUs.
func EncryptLock ¶ added in v0.9.1
EncryptLock is the exclusive key of a collection's migration.
func ErasedEmail ¶ added in v0.4.0
ErasedEmail is the unique, undeliverable address a tombstone gets: the .invalid domain is reserved, so it can't receive mail, and the id makes it unique. The real address is freed for a new registration.
func HashToken ¶
HashToken is the stored form of a token: hex SHA-256. Tokens are random and long, so a fast hash is enough.
func IPKey ¶
IPKey groups client addresses for throttling: IPv4 addresses one by one, IPv6 by /64, since one client usually controls a whole /64.
func IdempotencyID ¶
IdempotencyID builds a record's id: unique per function, per caller (Caller.Subject(), so ownership can never cross callers), per key.
func InvitationOfScope ¶ added in v0.9.13
func InvitationOfScope(login *ProviderLogin, hash, scopeOrg string)
InvitationOfScope puts the invitation of a sign-in attempt where it belongs: with an organization it is that organization's, which lets a new person make an account and join; otherwise it is an account invitation of the realm.
func KeyedJobID ¶ added in v0.8.5
KeyedJobID is the id of a job made for something that happens once, from what identifies it: the same parts give the same id, in the shape of any job id.
func LooksLikeOrgID ¶ added in v0.9.3
LooksLikeOrgID says whether s has the shape of an organization id.
func NewSessionToken ¶
NewSessionToken returns a new random session token (256 bits).
func NewUploadToken ¶ added in v0.8.0
func NewUploadToken() (token, hash string)
NewUploadToken makes the secret a pending upload's creator holds, and the hash that is stored instead of it.
func NormalizeDomain ¶ added in v0.9.13
NormalizeDomain writes a domain the way claims hold it: lower case, ASCII (punycode), no trailing dot, and a name that exists on the public internet (at least two labels, no address, not a public suffix). The empty string and an error say what is wrong.
func OrgContextOf ¶ added in v0.8.3
OrgContextOf returns the organization recorded on ctx, or "".
func PKCEChallenge ¶ added in v0.8.2
PKCEChallenge is the S256 challenge of a verifier.
func ProfileValues ¶ added in v0.8.2
func ProfileValues(input json.RawMessage) []string
ProfileValues are the values of an on_signup job's profile, which the function's logs must not show.
func SSOScopeOf ¶ added in v0.9.13
SSOScopeOf is the scope of the callback of a provider: the realm's, or its connection's organization.
func SSOSecretName ¶ added in v0.9.3
SSOSecretName is the organization secret that holds a provider's client secret.
func ScheduledJobID ¶
ScheduledJobID is the deterministic id of a scheduled run.
func SchemaMigrateLock ¶ added in v0.9.11
SchemaMigrateLock is the exclusive name of a collection's migration: one unfinished at a time.
func SignCallback ¶
func SignCallback(key []byte, c CallbackClaims) string
SignCallback returns a callback token for c, signed with key.
func ValidPKCEChallenge ¶ added in v0.8.2
ValidPKCEChallenge says whether s looks like an S256 challenge (43 URL-safe characters).
func ValidateClaims ¶ added in v0.8.3
ValidateClaims checks an organization's claims: a JSON object of at most 1 KiB.
func WithAuditSource ¶
func WithAuditSource(ctx context.Context, source func() AuditSource) context.Context
WithAuditSource returns a context whose audit records take their actor, request id and client address from source, called when a record is written (the actor may be known only after authentication).
func WithOffline ¶ added in v0.9.1
WithOffline marks a context as that of an offline operation: the audit records written under it say `offline: true`. Only the CLI's direct mode sets it.
func WithOrgContext ¶ added in v0.8.3
WithOrgContext records on ctx the organization the emails queued by the request belong to.
Types ¶
type APIKey ¶
type APIKey struct {
Name string
Role KeyRole // "" (stored before roles existed) counts as data
Networks registry.Networks // where the key may be used from; empty: anywhere
Scopes Scopes // what the key reaches; empty: everything
RateLimit string // the key's own request limit; "": the realm's and the instance's
Prefix string // first characters of the key, for recognizing it
Hash string
CreatedAt time.Time
LastUsedAt *time.Time
ExpiresAt *time.Time // nil: never expires
// Org is the organization the key is bound to when it acts on behalf of a user ("": none).
Org string
}
APIKey is a realm API key for server-side callers. Only a hash of the key is stored.
type AccountPart ¶ added in v0.9.2
type AccountPart struct {
Name string
// Rows are in a stable order. Fields are the API's snake_case names.
Rows []map[string]any
// Truncated says the part stopped at its cap, so the export is incomplete there.
Truncated bool
}
AccountPart is one file of the system data in a user's personal data export (`_account/<Name>.jsonl`): rows of plain values, with the times as RFC 3339 text.
type Argon2Params ¶
Argon2Params are argon2id cost parameters.
type AssignOrgJob ¶ added in v0.8.3
AssignOrgJob is what an assignment carries (design/organizations.md §10): the collection (the job's Database is its database), the organization to give, and the filter the documents must match, as the JSON of a `where`. Only documents without an organization change.
type AuditFilter ¶
type AuditFilter struct {
Action, Actor, Target string
Since, Until time.Time // At >= Since, At < Until
Limit, Skip int
}
AuditFilter selects audit records. Zero fields match everything.
type AuditRecord ¶
type AuditRecord struct {
ID string
At time.Time
ExpiresAt time.Time // removed after this (the realm's retention)
Action string
Actor string // "user:<id>", "key:<name>", "anonymous", or an Actor* constant
Target string // "user:<id>", "key:<name>", "invitation:<id>", or ""
Details map[string]any
RequestID string
ClientIP string
}
AuditRecord is one entry of the audit trail. It names users by id, keys by name and invitations by id, and never holds secrets: no passwords or hashes, tokens, keys, emails or request bodies.
type AuditSource ¶
type AuditSource struct {
Actor, RequestID, ClientIP string
}
AuditSource says who is acting and from where. The HTTP layer puts it in the request context; commands set their own.
type AuthAnonymize ¶ added in v0.9.1
type AuthAnonymize struct {
// PasswordHash, when set, is the hash every password identity gets.
PasswordHash string
}
AuthAnonymize turns the authentication data of an export into that of a staging copy: emails become user-<id>@example.invalid, password hashes are dropped (or replaced by one known password's), identities of external providers stay behind, organization sign-in connections keep their shape with the client ids blanked, and second factors and devices are not exported at all (see AnonymizedCollections).
type AuthChallenge ¶ added in v0.8.2
type AuthChallenge struct {
ID string // HashToken of the value given to the caller
Kind string
UserID string
// Factor is the first factor that was proved: ProviderPassword, a provider's name, ...
Factor string
// Strategy is the strategy the sign-in follows; Methods (below) are the steps done so far.
Strategy string
// Passkey and PasskeySynced say which passkey proved the first step (a consent challenge keeps them
// until the session starts).
Passkey string
PasskeySynced bool
// NewUser and Profile are what a provider sign-in hands over with the session: kept
// until the second step ends it.
NewUser bool
Profile map[string]string
// ViaOrg is the organization whose connection signed the person in (the session will record
// it); it is not Org, the company context of a magic-link request.
ViaOrg string
// Secret is a TOTP secret (SealToken form) of a ChallengeTOTPSetup.
Secret string
// SessionID is the session a re-authentication token or code is bound to; CodeHash is
// the keyed hash of the code of a ChallengeReauthCode (set when the email is made).
SessionID string
CodeHash string
// A magic-link request: TokenHash is the hash of the link's token and CodeHash the code's;
// CodeChallenge the PKCE challenge of the app that asked; RedirectTo where the link ends
// ("" for the realm's app_url); Email the address when it has no user yet (sealed);
// Purpose says what is sent (MagicLinkPurposeLink or MagicLinkPurposeNoAccount); Locale
// the language for a new user.
TokenHash string
CodeChallenge string
RedirectTo string
// Org is the company context of a magic-link request: the page of its link keeps it.
Org string
Email string
Purpose string
Locale string
// Methods are how the session will say it was made (a ChallengeConsent keeps them
// while the user accepts); Consents are the acceptances a magic-link request carried.
Methods []string
Consents map[string]string
Attempts int
CreatedAt time.Time
ExpiresAt time.Time
}
AuthChallenge is a pending step between a first factor and a session. Its key is the hash of the secret value the caller holds.
type CallbackClaims ¶
type CallbackClaims struct {
Realm string `json:"r"`
Function string `json:"f"` // <database>/<name>
UserID string `json:"u,omitempty"`
KeyHash string `json:"k,omitempty"`
// Org is the organization the session of the user belongs to: the function's data calls reach
// that organization and no other.
Org string `json:"og,omitempty"`
Admin bool `json:"a,omitempty"`
Expires time.Time `json:"e"`
// Calls are the functions of the caller's database this invocation may
// ctx.call (its function.yaml `calls`); Depth counts the nested calls
// above it; Inv is its own invocation id, the parent of what it calls.
Calls []string `json:"c,omitempty"`
Depth int `json:"d,omitempty"`
Inv string `json:"i,omitempty"`
// Job and Attempt say which job attempt this run is, so it may report its
// steps (ctx.step): only for an async function's job.
Job string `json:"j,omitempty"`
Attempt int `json:"t,omitempty"`
// Email says the function may send custom emails (function.yaml `email: true`).
Email bool `json:"m,omitempty"`
// Push says the function may send push notifications (function.yaml `push:`).
Push bool `json:"p,omitempty"`
// Config says the function may change the app configuration (function.yaml `config: write`).
Config bool `json:"g,omitempty"`
// MFA and Methods are how the session of the user the call acts as was created, so that
// rules in the function's own data calls see the same `user.mfa` and `user.methods`.
MFA bool `json:"x,omitempty"`
Methods []string `json:"y,omitempty"`
// Strategy is the session's strategy: the roles of the user the call acts as are those it keeps
// active, as in the request that started the call.
Strategy string `json:"z,omitempty"`
// PasskeySynced is whether the passkey that opened the session syncs between devices.
PasskeySynced bool `json:"w,omitempty"`
// ChainRoot and ChainDepth say the invocation is a trigger run (or was called by one):
// the documents it writes are stamped `_meta.chain = {root, depth}`, which is how a change
// caused by a trigger is told from a first-party one (design/triggers-and-realtime.md §11).
ChainRoot string `json:"o,omitempty"`
ChainDepth int `json:"n,omitempty"`
}
CallbackClaims are what a callback token carries: the function, the caller it acts as (a user, an API key, both for a key acting on behalf of a user, or neither for an anonymous caller) or full access (Admin), and when it expires (the invocation's deadline).
func VerifyCallback ¶
VerifyCallback checks a callback token's signature and expiry.
type Caller ¶
type Caller struct {
User *Principal // the user whose rules apply
Key *APIKey // set for API key callers
Func *FuncCaller // set for a function's callbacks
}
Caller is whoever makes a request to a realm with auth enabled: a user with a session, a server-side caller with an API key, an API key acting on behalf of a user (both set), or anonymous (neither). A function calling back (Func set) acts as the caller that invoked it, or, with admin access, as itself.
func (Caller) Actor ¶
Actor names the caller for logs: the subject, and for an API key acting on behalf of a user, "key:<name> as user:<id>".
func (Caller) BypassesRules ¶
BypassesRules reports whether the caller has full access: an API key that isn't acting on behalf of a user, or a function's admin access.
func (Caller) SignInMethods ¶ added in v0.8.2
SignInMethods says how the user the caller acts as signed in, for rules (`user.mfa`, `user.methods`) and functions (`ctx.user`): the first factor and any second one, and whether a second one was used. An API key (also acting on behalf of a user) is ["key"] and never MFA. The list is never nil.
func (Caller) SignInPasskeySynced ¶ added in v0.9.10
SignInPasskeySynced says the session the user the caller acts as signed in with was opened with a passkey that syncs between devices.
func (Caller) SignInStrategy ¶ added in v0.9.10
SignInStrategy is the strategy the user the caller acts as signed in with (`user.strategy`, `ctx.user.strategy`); empty for an API key and for a session from before strategies.
type CheckJob ¶ added in v0.8.0
type CheckJob struct {
Collections []string // "<database>/<collection>", resolved when the check started
Database string // the scope asked for: "" every database
Collection string // "" every collection of Database
Limit int // invalid documents listed per collection
}
CheckJob is what a schema check's job holds: what to check and how much to list.
type CheckProblem ¶ added in v0.8.0
CheckProblem is one way a document fails its schema: a JSON path and the rule that failed, never the value.
type CheckReport ¶ added in v0.8.0
type CheckReport struct {
Database, Collection string
JobID string
StartedAt time.Time
FinishedAt time.Time
Scanned int64
Invalid int64
// Waiting counts the documents below the collection's current schema version that don't match
// it: not drift, they wait for the migration job. ByVersion counts the documents scanned per
// schema version (a missing stamp is 1); only collections with versioned schema files have it.
Waiting int64
ByVersion map[string]int64
// Complete is false when the scan stopped before the end: StoppedBy says why
// ("limit" when Limit invalid documents were found, "time" for CheckMaxDuration).
Complete bool
StoppedBy string
Limit int
// SchemaHash identifies the schema the documents were checked against.
SchemaHash string
Documents []CheckedDocument // up to Limit
}
CheckReport is the latest finished schema check of one collection.
type CheckedDocument ¶ added in v0.8.0
type CheckedDocument struct {
ID string
Deleted bool // soft-deleted (in the trash)
Problems []CheckProblem
// MoreProblems counts the problems left out past MaxCheckProblems.
MoreProblems int
}
CheckedDocument is a document that failed its collection's schema.
type ConnectionInput ¶ added in v0.9.3
type ConnectionInput struct {
ClientID string
Issuer string
Domains []string
Tenant string
HostedDomain string
EmailDomains []string
NativeClientIDs []string
JoinRoles []string
// Enabled nil means true for a new connection and unchanged for an existing one.
Enabled *bool
// ClientSecret is required when the connection has none yet and kept when empty.
ClientSecret string
}
ConnectionInput is what a manager sends for a connection; PUT replaces every field.
type ConnectionView ¶ added in v0.9.3
type ConnectionView struct {
OrgConnection
// SecretSet says whether the client secret is stored; the value is never returned.
SecretSet bool
// DormantIdentities is, after a change of issuer, how many identities of the connection belong to
// another issuer now and match no sign-in until their people link again.
DormantIdentities int
}
ConnectionView is a connection with what the secret's state allows to say.
type ConsentContext ¶ added in v0.8.2
type ConsentContext struct{ IP, UserAgent string }
ConsentContext is where a person gave consents from: for the proof.
type ConsentInput ¶ added in v0.8.2
type ConsentInput struct {
Consent string
Version string // accepted: the version; withdrawn: ignored
Action string
Method string
Evidence string
// Locale is the language of the text the person saw; "" uses the user's, then the realm's.
Locale string
IP string
UserAgent string
}
ConsentInput is a consent given or withdrawn.
type ConsentNotice ¶ added in v0.8.2
type ConsentNotice struct {
Consent string
Version string
// Matched is the users who hold an older version of the consent (or, for a required
// one, none): the ones the message is for.
Matched int
// Queued messages were handed to the email worker; Limited were skipped because an email
// limit was reached; the rest could not be sent to (disabled or erased users).
Queued int
Limited int
}
ConsentNotice is what a notification run did.
type ConsentRecord ¶ added in v0.8.2
type ConsentRecord struct {
ID string
UserID string
Consent string
Version string
Locale string
TextHash string // SHA-256 of the text shown
Action string // ConsentAccepted or ConsentWithdrawn
Method string // ConsentMethodSignup, …
Evidence string // for the admin method: the reference given
At time.Time
// DeleteAt is when a retention removes the record: set at erasure, zero before.
DeleteAt time.Time
// IP and UserAgent are stored only when the realm lists them in compliance.consent_proof.
IP string
UserAgent string
}
ConsentRecord is one entry of a user's append-only consent history: the proof that a text was accepted, or the withdrawal of that acceptance.
type ConsentRef ¶ added in v0.8.2
type ConsentRef struct{ Consent, Version string }
ConsentRef is a consent and version a record refers to.
type ConsentRequiredError ¶ added in v0.8.2
type ConsentRequiredError struct {
Consents []registry.ConsentRef
// Session is true when it is an authenticated request that is refused.
Session bool
}
ConsentRequiredError says which consents a person has to accept: at sign-up they were missing or outdated (400), or an open session is past the reaccept_by date of a version it hasn't accepted (403).
func (*ConsentRequiredError) Error ¶ added in v0.8.2
func (e *ConsentRequiredError) Error() string
type CreatedKey ¶ added in v0.9.1
CreatedKey is what creating a key answers once. Value is set only for a generated key (an imported one is already in the developer's hands) and is never available again.
type CustomEmail ¶ added in v0.4.0
type CustomEmail struct {
Function string // <database>/<name> of the function that asked
To []string
CC []string
BCC []string
Data map[string]any
}
CustomEmail is what a function's email job carries.
type Device ¶ added in v0.8.2
type Device struct {
ID string
UserID string
SessionID string // the session that registered it
Platform string
Name string
TokenHash string // of the token, or of a web subscription's endpoint
Token string // sealed
CreatedAt time.Time
LastSeen time.Time
}
Device is a registered device of a user. Token is the token sealed with the realm's key; it never leaves the store and the senders.
type DeviceInput ¶ added in v0.8.2
DeviceInput is a registration: the platform, the token the provider gave the app (for web, the subscription as JSON) and an optional label.
type DiscoveredOrg ¶ added in v0.9.13
type DiscoveredOrg struct {
Org string
Name string
Providers []string // the names of the organization's usable connections
}
DiscoveredOrg is an organization a domain leads to: what an application needs to send the person to its sign-in.
type DomainRecord ¶ added in v0.9.13
type DomainRecord struct {
Type, Name, Value string
}
DomainRecord is the DNS record to publish.
type DomainRefusedError ¶ added in v0.9.13
type DomainRefusedError struct{ Reason string }
DomainRefusedError is a domain nobody may claim: free mail, a public suffix, blocked by the realm or not a domain at all.
func (*DomainRefusedError) Error ¶ added in v0.9.13
func (e *DomainRefusedError) Error() string
type DomainResolver ¶ added in v0.9.13
DomainResolver reads TXT records. The default asks the host's resolver, or the realm's organizations.domains.resolvers.
type DomainUpdate ¶ added in v0.9.13
type DomainUpdate struct {
Discoverable, LinkAccounts *bool
}
DomainUpdate changes what an organization lets a domain be used for; nil leaves a setting.
type DomainView ¶ added in v0.9.13
type DomainView struct {
OrgDomain
Record DomainRecord
// Reason says, after a check that did not prove the domain, why: record_not_found, mismatch or
// resolver_error.
Reason string
}
DomainView is a claim as the API shows it.
type EffectiveRole ¶ added in v0.8.3
type EffectiveRole struct {
Role string
// Origin is "direct", "default" and the names of the teams that carry it.
Origin []string
}
EffectiveRole is a role a member holds and where it came from.
type EmailJob ¶ added in v0.4.0
type EmailJob struct {
Kind string
UserID string
Locale string
RedirectTo string // checked when the request was made; bound to the token the worker creates
// Org is the company context of the message (an organization id): its data hook and,
// for custom emails, its template overrides apply.
Org string
// Draft is an owner template to render for a test send (Org's company context applies).
Draft *email.Override
// To says whose address the message goes to: "" the user's current one,
// "pending" the address they asked to change to, "previous" the one
// before the last change.
To string
// Notice marks a message that only informs: no token, no link.
Notice bool
// InvitationID is the invitation an invitation email is for (there is no
// user yet): the worker takes the address from it.
InvitationID string
// OrgInvitationID is the organization invitation an org-invitation email is for: the
// worker takes the address and the (sealed) link from it.
OrgInvitationID string
// ExportID is the personal data export the message is about (data-export-ready,
// data-export-made): the worker takes the link and the expiry from its record.
ExportID string
// Event and CodesLeft are what a security-notice says: which change it reports and, for
// a used recovery code, how many remain. Nothing secret.
Event string
CodesLeft int
// ChallengeID is the pending step the email is for (a re-authentication code): the
// worker makes the secret at send time and keeps only its hash there.
ChallengeID string
// Custom is set on an email a function asked for with ctx.email.send. Unlike
// the account emails it stores what the function gave: the recipients'
// addresses and the data for the template, for as long as jobs are kept.
Custom *CustomEmail
}
EmailJob is what an email job stores: which email, for whom, and nothing that works as a credential.
type EmailLimitedError ¶ added in v0.4.0
type EmailLimitedError struct {
RetryAfter time.Duration
// Scope says which limit it was: "recipient", "ip", "function" or
// "invocation".
Scope string
}
EmailLimitedError means an email limit was reached: nothing was queued.
func (*EmailLimitedError) Error ¶ added in v0.4.0
func (e *EmailLimitedError) Error() string
type EmailRequest ¶ added in v0.4.0
type EmailRequest struct {
Kind string // an email kind (verify-email, ...)
UserID string
Address string // the recipient, for the per-recipient limits only (never stored readable)
Locale string
RedirectTo string // already checked against the realm's allowed redirects
// Org is the company context of the message; when empty, the one recorded on the request's
// context (WithOrgContext) is used.
Org string
// Draft is a template to render instead of the realm's (or the organization's saved) one: a
// test send of an owner template. The job keeps it until job retention ends.
Draft *email.Override
ClientIP string // who caused it, for the per-IP limit; "" when nobody did
RequestID string
// Event and CodesLeft are the fields of the same name of EmailJob.
Event string
CodesLeft int
ChallengeID string
// To, Notice, InvitationID and OrgInvitationID are the fields of the same name of EmailJob.
To string
Notice bool
InvitationID string
OrgInvitationID string
// ExportID is the personal data export a data-export-ready or data-export-made email is
// about: the worker takes the link and the expiry from its record.
ExportID string
// Custom marks an email a function asked for; Invocation is the
// invocation that asked (the parent of the job, and what the per-invocation
// cap counts). Address is then the user's, for to_user; Custom holds the
// addresses of the others.
Custom *CustomEmail
Invocation string
Depth int
}
EmailRequest asks for one email to be sent to a user.
type EmailToken ¶ added in v0.4.0
type EmailToken struct {
Hash string // hex SHA-256 of the token; the record's id
Purpose string // verify-email, reset-password, change-email, revert-email-change or invitation
UserID string
RedirectTo string // where the page after the link may send the user (already checked)
// Org is the company context of the flow (see ResolveOrgContext): the pages and the emails
// that follow the link keep it.
Org string
// Address is the address the token acts on: the new one for change-email,
// the previous one for revert-email-change, the invited one for an
// invitation. Empty for the others.
Address string
// InvitationID is the invitation an invitation token accepts (UserID is empty then).
InvitationID string
CreatedAt time.Time
ExpiresAt time.Time
UsedAt time.Time // zero until redeemed
}
EmailToken is the record of a token sent in an email link (verifying an address, resetting a password, ...). backd stores only the SHA-256 hash of the token: the token itself exists only in memory and in the message handed to the delivery function.
type EncryptCounts ¶ added in v0.9.1
type EncryptCounts struct {
Scanned int64 `json:"scanned"`
Encrypted int64 `json:"encrypted"`
Reencrypted int64 `json:"reencrypted"`
Decrypted int64 `json:"decrypted"`
Indexed int64 `json:"indexed"`
Marked int64 `json:"marked"`
Conflicts int64 `json:"conflicts"`
}
EncryptCounts is what a migration did (or, in a dry run, would do).
type EncryptJob ¶ added in v0.9.1
type EncryptJob struct {
Database string
Collection string
Fields []string
DryRun bool
After string
EncryptCounts
}
EncryptJob is what a migration job carries: the collection, the fields asked for (none: all), whether it only counts, and the place it reached with what it did so far.
type EraseJob ¶ added in v0.4.0
type EraseJob struct {
UserID string
Email string
Counts map[string]int64 // "<database>/<collection>/<operation>" → documents
}
EraseJob is what an erase job carries: whose data to erase, the email to match fields that hold it (cleared when the job finishes), and what has been done so far.
An erase job is not a function: it has no executor, a worker applies the collections' policies itself.
type ErrCheckRunning ¶ added in v0.8.0
type ErrCheckRunning struct{ JobID string }
ErrCheckRunning means a schema check is already queued or running in the realm; JobID is its job.
func (*ErrCheckRunning) Error ¶ added in v0.8.0
func (e *ErrCheckRunning) Error() string
type ErrEncryptRunning ¶ added in v0.9.1
type ErrEncryptRunning struct{ JobID string }
ErrEncryptRunning means a migration of that collection is queued or running; JobID is its job.
func (*ErrEncryptRunning) Error ¶ added in v0.9.1
func (e *ErrEncryptRunning) Error() string
type ErrExportTooSoon ¶ added in v0.9.2
ErrExportTooSoon means the user asked for an export less than ExportMinGap after another; the error says for how long to wait.
func (*ErrExportTooSoon) Error ¶ added in v0.9.2
func (e *ErrExportTooSoon) Error() string
type ErrPasswordNoticeRunning ¶ added in v0.9.1
type ErrPasswordNoticeRunning struct{ JobID string }
ErrPasswordNoticeRunning means a notification run is queued or running; JobID is its job.
func (*ErrPasswordNoticeRunning) Error ¶ added in v0.9.1
func (e *ErrPasswordNoticeRunning) Error() string
type ErrSchemaMigrateRunning ¶ added in v0.9.11
ErrSchemaMigrateRunning means a migration of that collection is queued or running and is not the one asked for; JobID is its job.
func (*ErrSchemaMigrateRunning) Error ¶ added in v0.9.11
func (e *ErrSchemaMigrateRunning) Error() string
type ExpireResult ¶ added in v0.9.1
type ExpireResult struct {
ValidAfter time.Time
// Accounts is how many accounts have a password, and so are affected; Sessions how many
// sessions ended.
Accounts, Sessions int64
}
ExpireResult is what ExpireAllPasswords did.
type ExportRequest ¶ added in v0.9.2
type ExportRequest struct {
// Admin is the administrator asking for the user's export; "" for the user's own request,
// which is limited to one a day.
Admin string
Ticket string
// Notify tells the user an administrator made it. Silent exports carry the reason.
Notify bool
Reason string
Locale string
// RequestID is the HTTP request, for the job.
RequestID string
}
ExportRequest says who asks for an export and how.
type FileDeletion ¶ added in v0.8.0
type FileDeletion struct {
Key string
Public bool // the object is in the realm's public storage
Reason string // replaced, cleared, removed, abandoned…
Attempts int
NotBefore time.Time // not claimed before this
CreatedAt time.Time
}
FileDeletion is an object to delete from the bucket.
type FileDeletionStats ¶ added in v0.8.0
type FileDeletionStats struct {
Queued int // objects waiting to be deleted
Retrying int // of them, the ones that failed at least once
Oldest time.Time // when the oldest was queued; zero when empty
}
FileDeletionStats describes the deletion queue.
type FileJournalEntry ¶ added in v0.8.0
type FileJournalEntry struct {
ID string // the file's id (fl_…)
Database string
Collection string
Field string
DocumentID string // "" for an upload no document references yet
Key string // the object's key
// Public is true when the object is in the realm's public storage (a public field): where a
// file is stored is decided when it is uploaded and never changes.
Public bool
// KeyName is, for a public file, the sanitized name its key ends with.
KeyName string
Caller string // who uploaded it, for display (user:<id>, key:<name>, func:…)
Size int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
ExpiresAt time.Time
// A pending upload is one made before the document that will hold it exists
// (or without the document being touched): it is attached by naming it, with
// its token, in a write. Its details are kept here until then.
Pending bool
Direct bool // a direct upload: the client sends the bytes to the bucket and completes it
TokenHash string // SHA-256 of the secret token the creator holds
Owner string // the user who made it; "" for an anonymous caller
CallerKey string // who the open-uploads limit counts it for
PendingUntil time.Time // unused, it expires then (also set for a direct upload to a document)
Name string
Type string
SHA256 string
UploadedAt time.Time
// Image is a pending upload's image details as JSON (width, height and the state of each
// declared version), for the document that will hold it.
Image string
// A multipart direct upload (a file above one signed PUT): the storage's upload id, the
// part size and the SHA-256 of each part as declared at the start. SHA256 is then their
// composite, which storage can verify.
MultipartID string
PartSize int64
PartSHA256 []string
}
FileJournalEntry is one upload.
type FuncCaller ¶
type FuncCaller struct {
Name string // <realm>/<database>/<function>
Admin bool // ctx.admin.db: full access, recorded as the function
// What the invocation behind the token may do next (see CallbackClaims).
Calls []string
Depth int
Invocation string
Email bool // ctx.email.send
Push bool // ctx.push.send
Config bool // ctx.admin.config: may change the app configuration
Job string // the job attempt behind the token, if any (see CallbackClaims)
Attempt int
Expires time.Time
// ChainRoot and ChainDepth: see CallbackClaims. Empty for a run no trigger caused.
ChainRoot string
ChainDepth int
}
FuncCaller marks a caller as a function acting through a callback token.
func FuncCallerOf ¶ added in v0.4.0
func FuncCallerOf(c CallbackClaims) *FuncCaller
FuncCallerOf is the function behind a verified callback token.
type Hasher ¶
type Hasher struct {
Params Argon2Params
// contains filtered or unexported fields
}
Hasher hashes and verifies passwords with argon2id. At most a fixed number of hashes run at once; callers queue for a slot until their context ends, which bounds memory under a flood of requests.
func NewHasher ¶
func NewHasher(concurrency int, params Argon2Params) *Hasher
NewHasher returns a Hasher running at most concurrency hashes at once (DefaultHashConcurrency when concurrency < 1).
func (*Hasher) Concurrency ¶
Concurrency is how many hashes may run at once.
type HookTeamRole ¶ added in v0.8.3
type HookTeamRole struct {
Team string `json:"team"`
Role string `json:"role"`
From string `json:"from,omitempty"`
Until string `json:"until,omitempty"`
}
HookTeamRole is a team role as hooks see it.
type IdempotencyRecord ¶
type IdempotencyRecord struct {
ID string // see IdempotencyID
Function string // <database>/<name>, for display
CallerActor string
InputHash string // sha256 of the exact input bytes
Mode string // sync | async
Status string // running | done
Result *JobResult // nil until done; a sync call's outcome
JobID string // set once done, for async; "" for sync
CreatedAt time.Time
ExpiresAt time.Time
}
IdempotencyRecord ties one Idempotency-Key to its outcome, scoped to the function and the caller: two different callers can never collide on the same client-chosen key, even if they happen to pick the same string. Never stores input or output for keyless calls — this is the one deliberate exception, for calls that declare a key.
type Identity ¶
type Identity struct {
ID string
UserID string
Provider string
Subject string // unique per provider, organization and issuer
// Issuer is the issuer that vouched for Subject (an external provider's identities only): the key
// of an identity is (Provider, Org, Issuer, Subject), so a changed issuer matches nothing
// instead of matching someone else (design/sso.md §6.1). Password and email identities have none.
Issuer string
// Org is the organization whose connection signed the person in (design/sso.md §9); empty for
// the realm's own providers and the password. A user holds one identity per provider per
// organization.
Org string
PasswordHash string // ProviderPassword only: argon2id, PHC string format
// Email and EmailVerified are what an external provider last reported.
Email string
EmailVerified bool
// LastUsedAt is the last successful sign-in with this identity; zero if
// none was recorded yet.
LastUsedAt time.Time
// PasswordChangedAt is when a password identity's password was created or last replaced;
// zero for identities from before it was recorded, which count as changed at CreatedAt.
PasswordChangedAt time.Time
// AppleRefreshToken is Apple's refresh token, sealed with the realm's secrets cipher
// (see SealToken) and kept only to revoke it when the account goes away; AppleClientID
// is the client id it was issued to.
AppleRefreshToken string
AppleClientID string
CreatedAt time.Time
UpdatedAt time.Time
}
Identity is one way a user signs in.
A user has at most one identity per provider (the store enforces it) and any number of providers. The password identity has no email of its own: the user's is the one that counts.
type IdentityUpdate ¶ added in v0.8.2
type IdentityUpdate struct {
Email *string
EmailVerified *bool
LastUsedAt *time.Time
AppleRefreshToken *string
AppleClientID *string
}
IdentityUpdate changes the set fields of an identity.
type ImageJob ¶ added in v0.8.1
type ImageJob struct {
Collection string
Field string
DocumentID string
FileID string
// Version, when set, makes just that version, whatever its state: a function asked
// for it. Params are the parameters to make it with, as JSON ("" means the declared
// ones); the job's result carries the outcome for the function waiting on it.
Version string
Params string
// Scan makes this a job over a whole field (backd files regenerate): every file
// whose copies no longer match what the field declares is made again, for Version only
// when it is set. MissingOnly leaves the copies that exist alone. Rate is how many files
// a second at most (0 for the default). DocumentID and FileID are empty.
Scan bool
MissingOnly bool
Rate int
}
ImageJob is what an image-versions job carries: the file, and where it is. The job's Database is the file's database and its Function the collection.
type InvalidCodeError ¶ added in v0.8.2
type InvalidCodeError struct{ AttemptsLeft int }
InvalidCodeError is a second-factor code that is wrong; AttemptsLeft counts what the challenge still allows.
func (*InvalidCodeError) Error ¶ added in v0.8.2
func (e *InvalidCodeError) Error() string
type InvalidConsentsError ¶ added in v0.8.2
type InvalidConsentsError struct{ Reasons []string }
InvalidConsentsError is a request that names consents or versions the realm doesn't have.
func (*InvalidConsentsError) Error ¶ added in v0.8.2
func (e *InvalidConsentsError) Error() string
type InvalidDeviceError ¶ added in v0.8.2
type InvalidDeviceError struct{ Reason string }
InvalidDeviceError says why a token isn't acceptable.
func (*InvalidDeviceError) Error ¶ added in v0.8.2
func (e *InvalidDeviceError) Error() string
type InvalidLocaleError ¶ added in v0.4.0
type InvalidLocaleError struct{ Allowed []string }
InvalidLocaleError means a language the realm doesn't list was asked for.
func (*InvalidLocaleError) Error ¶ added in v0.4.0
func (e *InvalidLocaleError) Error() string
type Invitation ¶
type Invitation struct {
ID string
TokenHash string
Email string // "" if anyone holding the token may use it
CreatedBy string // "key:<name>"
CreatedAt time.Time
ExpiresAt time.Time
}
Invitation lets one person sign up in a realm with `signup: invite`. Only a hash of its token is stored.
type InvitationInput ¶ added in v0.8.3
type InvitationInput struct {
Binding string
User string
Email string
Roles []string
Teams []string
Send bool
TTL time.Duration // 0: the default
MaxUses int // BindNone; 0: 1
Locale string
IP string
Request string
}
InvitationInput is a request to invite.
type InvitationResult ¶ added in v0.8.3
type InvitationResult struct {
Invitation OrgInvitation
Token string
Link string // "" when the realm sets no invitation_link
}
InvitationResult is what creating or renewing an invitation answers: the link is shown only here.
type InvocationFilter ¶
type InvocationFilter struct {
Function, RequestID string
// Actor keeps the calls made by one caller ("user:<id>").
Actor string
Since, Until time.Time
Limit, Skip int
}
InvocationFilter selects invocation records. Zero fields match everything.
type InvocationRecord ¶
type InvocationRecord struct {
ID string
At time.Time
ExpiresAt time.Time // removed after this (the realm's log retention)
Function string // <database>/<name>
Actor string // "user:<id>", "key:<name>", "anonymous", or "func:<name> as ..."
Mode string // sync today; async, webhook later
Status string // executor.Status* (ok, function_error, timeout, memory, cpu, crash, ...)
Code string // the function's own error code, when Status is function_error
DurationMS int64
RequestID string
JobID string // async jobs (roadmap F11); empty until then
ParentID string // the invocation that called this one (ctx.call); empty otherwise
Origin string // http, function, cron, admin, trigger:<db>/<collection>/<trigger> or backd:<event>
// EventID is the change a trigger run was made for (a replay of it shares the id).
EventID string
Logs []LogLine
// Steps are what the call reported with ctx.step and ctx.progress, closed
// when it ended; StepsOmitted counts those dropped from the middle.
Steps []Step
StepsOmitted int
}
InvocationRecord is one function call, recorded in the realm's system database (roadmap F10). Inputs and outputs are never stored — only what's needed to debug what happened and read the function's own logs.
type IssuedChallenge ¶ added in v0.8.2
type IssuedChallenge struct {
Token string
Kind string
Methods []string
// Next are the methods the person may use now (totp; a recovery code stands in for it)
// and Strategy the strategy the sign-in follows.
Next []string
Strategy string
// Consents are the consents and versions a ChallengeConsent waits for.
Consents []registry.ConsentRef
}
IssuedChallenge is a challenge handed to the caller: the value to send back and what it accepts.
type Job ¶
type Job struct {
ID string
Database string
Function string // name only; Database plus this is the function
Input json.RawMessage
CallerActor string // for display: "user:<id>", "key:<name>", "anonymous"
CallerUserID string // "" unless the caller was a signed-in user
// CallerOrg is the organization the caller's session belonged to when the job was queued, so
// that work started in one organization cannot read another's when it runs later.
CallerOrg string
CallerKeyHash string // "" unless the caller was an API key
Scheduled bool // created by the function's cron schedule, acts as the function itself
ActsAsFunction bool // run as the function itself, with full access (a scheduled function run by hand)
Origin string // http, function (ctx.call), cron, admin or backd:<event>
ParentID string // the invocation that queued it with ctx.call; empty otherwise
RerunOf string // the finished job an administrator re-ran to make this one; empty otherwise
Depth int // nested calls above it
// EventID is the change that made a trigger's job; ChainRoot and ChainDepth where it sits
// in a chain of writes caused by trigger runs (empty and 0 for a job no trigger made, or
// called by one: they carry the chain over).
EventID string
ChainRoot string
ChainDepth int
// SerialKey makes the jobs that share it run one at a time, oldest SerialOrder first (an
// `ordered` trigger: one document's changes, in the order they were made). A job whose
// predecessor hasn't finished isn't claimed, and a retry waiting out its delay holds its
// place. Empty for jobs that run whenever a worker is free.
SerialKey string
SerialOrder int64
// Email is set on an email job: backd's own request to send a message, which
// a worker renders and hands to the realm's delivery function. It holds no
// message and no token.
Email *EmailJob
// Erase is set on an erase job (origin backd:account.erase).
Erase *EraseJob
// Check is set on a schema check's job (origin CheckOrigin).
Check *CheckJob
// Image is set on the job that makes a file's image versions (origin ImageOrigin).
Image *ImageJob
// Assign is set on the job that gives documents without one an organization (origin
// AssignOrgOrigin); OrgDelete on the cleanup after an organization was deleted.
Assign *AssignOrgJob
OrgDelete *OrgDeleteJob
// Revoke is set on a job that revokes a user's Apple refresh token (origin RevokeOrigin).
Revoke *RevokeJob
// Push is set on the jobs of a push send (origin PushOrigin): planning an audience, a batch
// of users, or a delivery unit.
Push *PushJob
// PasswordNotice is set on the job that tells the users with an expired password to choose
// a new one (origin PasswordNoticeOrigin).
PasswordNotice *PasswordNoticeJob
// Encrypt is set on the job that migrates a collection's documents to its encryption
// configuration (origin EncryptOrigin).
Encrypt *EncryptJob
// Export is set on the job that builds a user's personal data export (origin ExportOrigin).
Export *ExportJob
// SchemaMigrate is set on the job that migrates a collection's documents to its current
// schema version (origin SchemaMigrateOrigin).
SchemaMigrate *SchemaMigrateJob
// Exclusive, when set, lets only one job of that name be unfinished at a
// time: enqueuing another fails with ErrJobExclusive.
Exclusive string
TimeoutMS int64 // the function's timeout at enqueue time, for the worker's lease
RequestID string
Status string // queued | running | done
Attempts int // times a worker claimed it
Failures int // attempts that ended in a failure worth retrying
NextAttemptAt time.Time // when a retry may be claimed; zero unless one is waiting
CreatedAt time.Time
CompletedAt time.Time // zero until done
ExpiresAt time.Time
Result *JobResult // nil until done
// Steps are what the running (or last) attempt reported with ctx.step and
// ctx.progress, the last being the current one; StepsOmitted counts those
// left out of the middle when there were more than MaxSteps. A new attempt
// starts with none.
Steps []Step
StepsOmitted int
}
Job is one async function call (roadmap F11), stored in the realm's system database until it's claimed, run, and its result read or expired. Unlike sync calls, whose input and output are never stored, a job's input and result are — there's nowhere else to keep them until the caller reads them back.
type JobFilter ¶
type JobFilter struct {
Database, Function string // Function is the name only; "" matches every function
Origin string // exact origin, such as function:main/ship; "" matches every one
EraseUser string // the erase jobs of this user
Status string // queued, running or done
Scheduled *bool // nil: both; true: cron runs only; false: called ones only
Since, Until time.Time // on created_at: from Since, before Until
Limit, Skip int
}
JobFilter selects jobs to list. Zero fields match everything.
type JobResult ¶
type JobResult struct {
Status string
Output json.RawMessage
Code string
Message string
Details json.RawMessage
DurationMS int64
// HTTPStatus is the function's own chosen status (ctx.error's first
// argument) when Status is "function_error"; unused otherwise. A
// job never answers HTTP itself, but an idempotent sync replay
// (roadmap F12) needs it to reconstruct the original response.
HTTPStatus int
}
JobResult is how a job's run ended: the same vocabulary as a sync call's executor.Result (executor.Status*), flattened here so this package doesn't need to import the executor.
type KeyInUseError ¶ added in v0.9.1
KeyInUseError is a refusal to delete a key that fields still name, or that still wraps data keys (and with them, values).
func (*KeyInUseError) Error ¶ added in v0.9.1
func (e *KeyInUseError) Error() string
type KeyOptions ¶
type KeyOptions struct {
TTL time.Duration // 0: never expires
Role KeyRole // "" means data
Networks registry.Networks // where the key may be used from; empty: anywhere
Scopes Scopes // what a data key reaches; empty: everything
// RateLimit is the key's own request limit, "<requests>/<window>" or "none" (design/rate-limiting.md):
// it replaces the limits of the key's classes. "" uses the realm's and the instance's.
RateLimit string
// Org binds a data key that acts on behalf of users to one organization (its id or slug): it
// counts only that organization, as a session scoped to it would. Only in a realm with
// organizations.
Org string
}
KeyOptions are the settings of a new API key.
type KeyRole ¶
type KeyRole string
KeyRole is what an API key may do.
const ( // KeyRoleData keys reach data routes, bypassing rules, and may act on // behalf of a user. The default: what services need. KeyRoleData KeyRole = "data" // KeyRoleAdmin keys also reach the admin API (/_admin): users, roles, // invitations and API keys. For management tooling only. KeyRoleAdmin KeyRole = "admin" )
func ParseKeyRole ¶
ParseKeyRole returns the role named s ("" means data).
type LogLine ¶
LogLine is one line of a function's captured console output, already masked by the executor.
type LoginCode ¶ added in v0.8.2
type LoginCode struct {
ID string // HashToken(code)
UserID string
// Method is the first factor the code stands for: the provider's name (magic links will
// add their own), so that a second step can be asked for after the code is redeemed.
Method string
// Strategy is the strategy the sign-in follows.
Strategy string
CodeChallenge string
// NewUser says the sign-in made the user, and Profile is what the provider said of them:
// the redemption hands both over once.
NewUser bool
Profile map[string]string
// Org is the organization whose connection signed the person in; the session records it.
Org string
CreatedAt time.Time
ExpiresAt time.Time
}
LoginCode is the one-time code the app gets in place of a session: it is redeemed with the PKCE verifier its challenge came from.
type MFALockedError ¶ added in v0.8.2
MFALockedError means too many second factors failed for the user: nothing is tried until RetryAfter has passed.
func (*MFALockedError) Error ¶ added in v0.8.2
func (e *MFALockedError) Error() string
type MFARecord ¶ added in v0.8.2
type MFARecord struct {
UserID string
Secret string // SealToken form
EnabledAt time.Time
LastStep int64
RecoveryCodes []string
}
MFARecord is a user's second-factor state: the TOTP secret (sealed), the last time step accepted and the unused recovery codes (keyed hashes).
type MFAStatus ¶ added in v0.8.2
type MFAStatus struct {
// Available says the realm lets users turn TOTP on (it may be off with users who
// still have it).
Available bool
Enabled bool
Methods []string
RecoveryCodesLeft int
// Required says a role of the user requires MFA.
Required bool
// Passkeys is how many passkeys the user has.
Passkeys int
}
MFAStatus is what a user can see of their second factor.
type MagicLinkInput ¶ added in v0.8.2
type MagicLinkInput struct {
Email string
// RedirectTo is where the link ends (already checked against the realm's allowed
// redirects); "" for the realm's sign_in.app_url.
RedirectTo string
// CodeChallenge is the S256 PKCE challenge of a verifier only the asking app holds.
CodeChallenge string
Locales []string
IP, RequestID string
// Consents are accepted for the account a new address gets when the link is used.
Consents map[string]string
// Org is the organization (id or slug) the person signs in to with the link: only its members
// are sent one, the session is scoped to it, and a new address never gets an account this way
// (design/scoped-sessions.md §5).
Org string
// Strategy is the strategy to sign in with ("" when the app names none).
Strategy string
}
MagicLinkInput is a request for a link and a code.
type ManagedOrg ¶ added in v0.8.3
type ManagedOrg struct {
ID string
Name string
// LastManager says nobody else could manage it: erasing the user leaves it orphaned.
LastManager bool
}
ManagedOrg is an organization a user can manage, for the report before an erase.
type MemberAccess ¶ added in v0.8.3
type MemberAccess struct {
Roles []string `json:"roles"`
Teams []string `json:"teams"`
TeamRoles []HookTeamRole `json:"team_roles"`
EffectiveRoles []string `json:"effective_roles"`
}
MemberAccess is what a member holds in an organization, as hooks see it: direct roles, teams, team roles (all of them, with their windows) and the effective organization roles now, which change when a team's roles do.
type MemberView ¶ added in v0.8.3
type MemberView struct {
Member OrgMember
Email string // "" when the viewer may not see it
Effective []EffectiveRole
// Overlap lists roles held directly and through a team (or by default).
Overlap []string
// MFA says whether the member has a second factor; set only for viewers who manage the
// organization (nil otherwise).
MFA *bool
// TeamRoles are the member's team role grants, in force or not, judged at Now.
TeamRoles []TeamRoleGrant
Now time.Time
// MFARoles are the roles the member holds now (organization roles and team roles) that
// require a second factor; set only for viewers who manage the organization.
MFARoles []string
}
MemberView is a member as the members list shows them.
type Membership ¶ added in v0.8.3
type Membership struct {
Org Org
Member OrgMember
Roles []EffectiveRole
// TeamRoles are the team roles that count now, by team id, and TeamGrants the same grants
// with their windows.
TeamRoles map[string][]string
TeamGrants []TeamRoleGrant
// Withheld are the roles the member holds that don't count for this session because they
// require a second factor it didn't use.
Withheld []WithheldRole
}
Membership is what a user's request needs to know about one organization.
func (Membership) RoleNames ¶ added in v0.8.3
func (m Membership) RoleNames() []string
RoleNames returns the effective role names.
type NewOrgSignupRequest ¶ added in v0.9.3
type NewOrgSignupRequest struct {
SignupRequest
// Name and Slug are the organization's; the slug is required.
Name, Slug string
}
NewOrgSignupRequest is a new person creating an account and their organization.
type OAuthState ¶ added in v0.8.2
type OAuthState struct {
ID string // HashToken(state)
Provider string
// Strategy is the strategy the app asked for ("" when it named none).
Strategy string
// Org is the organization whose connection the attempt goes through ("" for the realm's
// own providers): the callback must be the one of that organization.
Org string
// ScopeOrg is the organization the person is signing in to: the session records it. It is
// the connection's organization for a connection, and the organization of the route for a
// realm provider used to sign in to one.
ScopeOrg string
Intent string
CodeChallenge string // the app's PKCE challenge (S256)
Verifier string // backd's own PKCE verifier, for the provider
Nonce string
RedirectTo string
InvitationID string // HashToken of the invitation token, if one was passed (an organization's for a ScopeOrg)
LinkUserID string // IntentLink: whose identity is being added
Locales []string
// Host is the sso engine's opaque host data, stored and returned untouched.
Host []byte
// Consents are the consents the app accepted for a sign-up through this attempt.
Consents map[string]string
CreatedAt time.Time
ExpiresAt time.Time
}
OAuthState is a sign-in attempt in progress: what backd must remember between sending the user to the provider and the provider sending them back. Its key is the hash of the state value the provider echoes.
type OnSignupInput ¶ added in v0.8.2
type OnSignupInput struct {
UserID string `json:"user_id"`
Provider string `json:"provider"`
Profile map[string]string `json:"profile,omitempty"`
}
OnSignupInput is what account.on_signup receives: the new user's id, how they signed up ("password", or a provider's name) and, from a provider, the profile it gave.
type Org ¶ added in v0.8.3
type Org struct {
ID string
Name string
Slug string // unique among organizations that aren't deleted; "" when none
FormerSlug string // the slug a deleted organization had
CreatedBy string // user id; "" when created by a function
Status string
RequireMFA bool
// SSORequired makes the organization's connection the only way in: the other ways to sign in
// to it answer ErrSSORequired (design/scoped-sessions.md §6).
SSORequired bool
// SessionMaxAge shortens the lifetime of the sessions opened in the organization (0: the
// realm's).
SessionMaxAge time.Duration
Claims map[string]any
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt time.Time
}
Org is an organization.
func (Org) Counts ¶ added in v0.8.3
Counts reports whether memberships of the organization count for a session: it is the session's own organization (a session reaches one organization and no other, design/scoped-sessions.md), it is active (or orphaned: its members keep access) and its require_mfa is met. It is the one place that decides, so every reader of memberships goes through it.
type OrgConnection ¶ added in v0.9.3
type OrgConnection struct {
ID string // org:provider, which is also what makes the pair unique
Org string
Provider string // google, microsoft or oidc
ClientID string
// Issuer is an OpenID Connect connection's: the server's URL, which has to match one of the realm's
// organizations.sso.oidc.issuers. Domains are the verified domains of the organization whose addresses
// it admits (empty: all of them).
Issuer string
Domains []string
// Tenant is Microsoft's tenant id (a GUID); HostedDomain is Google's Workspace domain.
// The one that applies is required: they are what limits who may sign in.
Tenant string
HostedDomain string
// EmailDomains optionally narrows further: the verified email's domain must be one of them.
EmailDomains []string
// NativeClientIDs are extra audiences the id-token endpoint accepts (mobile apps).
NativeClientIDs []string
// JoinRoles are given to a person who joins the organization through the connection.
JoinRoles []string
Enabled bool
// Blocked are the ids of members a manager removed: they sign in but are not joined again
// until invited. Kept by the sign-in code, not set through the API.
Blocked []string
CreatedBy string
UpdatedBy string // who last set it: the join roles were checked against their capabilities
CreatedAt time.Time
UpdatedAt time.Time
}
OrgConnection is an organization's sign-in provider. The client secret is not here: it is an organization secret (SSOSecretName) nobody can read.
func (OrgConnection) Admits ¶ added in v0.9.3
func (c OrgConnection) Admits(in SignInClaims) bool
Admits says whether the person the token describes may come in through the connection: the Workspace domain or the tenant is the connection's (the cryptographic restriction), Google's address is verified, and the address is in one of email_domains when the connection lists any. A token is checked for its signature, issuer and audience before this.
func (OrgConnection) HasBlocked ¶ added in v0.9.3
func (c OrgConnection) HasBlocked(user string) bool
HasBlocked reports whether a manager removed the user while the connection existed.
type OrgDeleteJob ¶ added in v0.8.3
OrgDeleteJob is what a deletion's cleanup carries: the organization, and the team when it is the cleanup after a team was deleted (on_team_delete). The job's Database is empty: it goes through every collection of the realm that has organizations (or teams).
type OrgDomain ¶ added in v0.9.13
type OrgDomain struct {
ID string // <org>:<domain>
Org string
Domain string // lower case, in ASCII (punycode)
State string
// Challenge is the value to publish; it is public once published, so it is kept as is.
Challenge string
// Discoverable lets the domain be used to find the organization from an address; LinkAccounts
// lets an organization sign-in on the domain link existing accounts.
Discoverable bool
LinkAccounts bool
// Failures counts the failed checks in a row; Checks the automatic checks of a pending claim.
Failures int
Checks int
CreatedBy string
CreatedAt, VerifiedAt, LastCheckedAt, NextCheckAt time.Time
}
OrgDomain is an organization's claim on a domain.
type OrgInvalidError ¶ added in v0.8.3
type OrgInvalidError struct{ Field, Reason string }
OrgInvalidError is a request the organization rules refuse, with the field to point at.
func (*OrgInvalidError) Error ¶ added in v0.8.3
func (e *OrgInvalidError) Error() string
type OrgInvitation ¶ added in v0.8.3
type OrgInvitation struct {
ID string
Org string
TokenHash string
SealedToken string // set only when an email carries the link
Binding string
User string // BindUser
Email string // BindEmail
Roles []string
Teams []string
MaxUses int
Uses int
CreatedBy string
CreatedAt time.Time
ExpiresAt time.Time
RevokedAt time.Time
}
OrgInvitation is an invitation to an organization. Only a hash of the token is stored, plus the token sealed with the realm's key for as long as an email that carries it may be sent.
type OrgInvitationEmail ¶ added in v0.8.3
type OrgInvitationEmail struct {
Address string
Org string
OrgName string
Roles []string
Token string
Link string
ExpiresAt time.Time
}
OrgInvitationEmail is what the worker needs to write the message of an invitation.
type OrgInvitationPreview ¶ added in v0.8.3
type OrgInvitationPreview struct {
Org Org
Roles []string
Teams []OrgTeam
Binding string
ExpiresAt time.Time
// contains filtered or unexported fields
}
OrgInvitationPreview is what someone is shown before accepting.
type OrgMember ¶ added in v0.8.3
type OrgMember struct {
Org string
User string
Roles []RoleGrant // direct
Teams []string
TeamRoles []TeamRoleGrant // held within a team, member of it or not
JoinedAt time.Time
InvitedBy string
}
OrgMember is a user's membership of one organization.
func (OrgMember) ActiveTeamRoles ¶ added in v0.8.3
ActiveTeamRoles returns the team roles that count at now, by team id.
type OrgMemberJoined ¶ added in v0.8.3
type OrgMemberJoined struct {
Event string `json:"event"`
Org string `json:"org"`
User string `json:"user"`
Seq int64 `json:"seq"`
Invitation string `json:"invitation,omitempty"`
MemberAccess
}
OrgMemberJoined is the input of on_member_joined.
type OrgMemberLeft ¶ added in v0.8.3
type OrgMemberLeft struct {
Event string `json:"event"`
Org string `json:"org"`
User string `json:"user"`
Seq int64 `json:"seq"`
Reason string `json:"reason"`
}
OrgMemberLeft is the input of on_member_left.
type OrgRolesChanged ¶ added in v0.8.3
type OrgRolesChanged struct {
Event string `json:"event"`
Org string `json:"org"`
User string `json:"user"`
Seq int64 `json:"seq"`
Before MemberAccess `json:"before"`
After MemberAccess `json:"after"`
}
OrgRolesChanged is the input of on_roles_changed.
type OrgSignIn ¶ added in v0.9.3
type OrgSignIn struct {
// Org is the organization's id or slug.
Org, Email, Password, IP string
// Invitation is an organization invitation token to use as part of the sign-in; with it a
// person who is not a member yet can come in, and joins.
Invitation string
// Strategy is the strategy to sign in with ("" when the app names none).
Strategy string
}
OrgSignIn is a password sign-in to an organization.
type OrgSignInLink ¶ added in v0.9.3
type OrgSignInLink struct {
ID, Slug, Name, Link string
}
OrgSignInLink is an organization of a person, with where its sign-in page is.
type OrgSignupRequest ¶ added in v0.9.3
type OrgSignupRequest struct {
SignupRequest
// Org is the organization's id or slug. Invitation (of SignupRequest) is its invitation token.
Org string
}
OrgSignupRequest is a sign-up to an organization: the person is let in by an invitation.
type OrgSummary ¶ added in v0.8.3
OrgSummary is an organization of the admin list, with how many members it has.
type OrgTeam ¶ added in v0.8.3
OrgTeam is a group of members of an organization that carries organization roles.
type OrgTemplate ¶ added in v0.8.3
type OrgTemplate struct {
Org, Kind, Locale string
email.Override
Version int
UpdatedBy string
UpdatedAt time.Time
// Versions are the previous ones, newest first, at most OrgTemplateVersions.
Versions []OrgTemplateVersion
}
OrgTemplate is an organization's version of one kind in one language.
type OrgTemplateVersion ¶ added in v0.8.3
OrgTemplateVersion is a previous version of a template.
type OrgUpdate ¶ added in v0.8.3
type OrgUpdate struct {
Name *string
Slug *string // "" removes it
// RequireMFA turns the organization's second-factor requirement on or off.
RequireMFA *bool
// SSORequired turns the requirement to sign in through the organization's connection on or off.
SSORequired *bool
// SessionMaxAge sets the organization's session lifetime (0 removes it).
SessionMaxAge *time.Duration
Claims map[string]any
// ClaimsSet says Claims replaces the claims (an empty map clears them).
ClaimsSet bool
Status string // "" leaves it
}
OrgUpdate changes an organization; nil fields stay.
type PasskeyInfo ¶ added in v0.9.10
type PasskeyInfo struct {
ID string
Name string
CreatedAt time.Time
LastUsedAt time.Time
Transports []string
BackupEligible bool
BackupState bool
}
PasskeyInfo is a passkey as the user sees it: never the key material.
type PasskeyNameError ¶ added in v0.9.10
type PasskeyNameError struct{ Reason string }
PasskeyNameError: a passkey name that cannot be used.
func (*PasskeyNameError) Error ¶ added in v0.9.10
func (e *PasskeyNameError) Error() string
type PasskeyOptions ¶ added in v0.9.10
PasskeyOptions are what the app passes to navigator.credentials.get.
type PasskeySignIn ¶ added in v0.9.10
type PasskeySignIn struct {
Ceremony string
Credential []byte // the JSON of the PublicKeyCredential
IP string
// Org is the organization route the call came on ("" for the realm's own door); it must be the
// one the options were asked on.
Org string
}
PasskeySignIn is the second call of a sign-in with a passkey.
type PasswordEpoch ¶ added in v0.9.1
PasswordEpoch is the moment before which no password is valid in a realm. It only moves forward; a password set after it (reset, change, administrator) is valid again.
type PasswordExpiredError ¶ added in v0.9.1
type PasswordExpiredError struct{ EmailQueued bool }
PasswordExpiredError is ErrPasswordExpired for a sign-in: it also says whether the password-expired email, with a reset link, was queued for the user (errors.Is matches ErrPasswordExpired).
func (*PasswordExpiredError) Error ¶ added in v0.9.1
func (e *PasswordExpiredError) Error() string
func (*PasswordExpiredError) Is ¶ added in v0.9.1
func (e *PasswordExpiredError) Is(target error) bool
Is makes errors.Is(err, ErrPasswordExpired) true.
type PasswordNoticeCounts ¶ added in v0.9.1
type PasswordNoticeCounts struct {
// Queued emails; Skipped users it didn't write to (disabled, erased, unverified address,
// already told, or a new password since); Deferred users the email limits held back.
Queued, Skipped, Deferred int64
}
PasswordNoticeCounts is what a notification run did.
type PasswordNoticeJob ¶ added in v0.9.1
type PasswordNoticeJob struct {
Epoch time.Time
Reason string
After string
PasswordNoticeCounts
}
PasswordNoticeJob is what the notification job carries: the epoch it notifies for, the operator's reason, the id it has reached and what it did so far.
type PasswordStatus ¶ added in v0.9.1
type PasswordStatus struct {
Epoch PasswordEpoch // the zero value when none was set
Accounts int64
}
PasswordStatus is the realm's password epoch and how many accounts have a password.
type PasswordUpdate ¶ added in v0.9.4
type PasswordUpdate struct {
Email, Password, NewPassword string
// Method and Code are the second factor of an account that has one: MethodTOTP (the default)
// or MethodRecovery.
Method, Code string
IP string
}
PasswordUpdate is a user choosing a new password while signed out, by proving the current one.
type PolicyError ¶
type PolicyError struct{ Reason string }
PolicyError is a password that doesn't meet the realm's policy.
func (*PolicyError) Error ¶
func (e *PolicyError) Error() string
type PortableResult ¶ added in v0.9.1
PortableResult is what one document of an import came to.
type PortableStore ¶ added in v0.9.1
type PortableStore interface {
// ExportSystem returns up to limit documents of a portable collection with an id after
// afterID, ordered by id.
ExportSystem(ctx context.Context, collection, afterID string, limit int) ([]map[string]any, error)
// GetSystem returns one document of a portable collection, or false.
GetSystem(ctx context.Context, collection, id string) (map[string]any, bool, error)
// ImportSystem applies documents by mode ("create", "skip" or "replace"); with write false
// it only says what would happen, unique indexes included. An identical document is
// unchanged in every mode.
ImportSystem(ctx context.Context, collection string, docs []map[string]any, mode string, write bool) ([]PortableResult, error)
}
PortableStore is what exporting and importing authentication data needs of a store. The documents are raw (the stored shape with "id" for "_id", times as time.Time).
type Principal ¶
type Principal struct {
// User holds the roles active in this session (see Settings.ActiveRoles).
User User
Session Session
// RolesInactive are the roles the user holds that the session's strategy does not allow.
RolesInactive []string
}
Principal is the authenticated caller of a request.
type ProviderLogin ¶ added in v0.8.2
type ProviderLogin struct {
Provider string
// Org is the organization whose connection vouched for the person; their identity is
// (Provider, Org, Subject). Such a login never links by address: TrustsEmail is false.
Org string
// Issuer is the issuer that vouched for Subject: with the provider and the organization, the
// key of the identity.
Issuer string
Subject string // the provider's stable id for the person
Email string
EmailVerified bool // as the provider asserts it
// TrustsEmail: the provider's verified addresses may link an existing account
// and mark a new one verified (Google and Apple).
TrustsEmail bool
Intent string
LinkUserID string // IntentLink: the signed-in user
// Invitation is the hash of the invitation token the attempt carried.
Invitation string
// ScopeOrg and OrgInvitation: the sign-in is to an organization (not through a connection of
// its own) and the attempt carried one of its invitations (a hash), which lets a person with
// no account make one whatever the realm's sign-up mode.
ScopeOrg, OrgInvitation string
Locales []string
IP string
// Consents and UserAgent: what a sign-up through the login accepted, and the proof's context.
Consents map[string]string
UserAgent string
// Profile is what the provider says of the person (CleanProfile's fields): handed to
// the app and to account.on_signup when the login makes a new user, and kept nowhere else.
Profile map[string]string
}
ProviderLogin is a person an external provider has vouched for.
type ProviderResult ¶ added in v0.8.2
type ProviderResult struct {
User User
NewUser bool
Linked bool // an identity was added to an existing user
// Profile is what the provider said of a new user (empty for anyone else).
Profile map[string]string
}
ProviderResult is the outcome of a provider login.
type PushAudience ¶ added in v0.8.2
type PushAudience struct {
All bool
Roles []string // any of
EmailVerified *bool
Locale string
CreatedBefore time.Time
CreatedAfter time.Time
// Consent: only users who hold this consent (any version).
Consent string
}
PushAudience is who a send reaches when it names no users.
type PushCounts ¶ added in v0.8.2
type PushCounts struct {
Queued, Limited, NoDevices, NoConsent int
// Units is the delivery units of the batch, those made now and those that existed.
Units int
}
PushCounts is what planning a batch decided.
type PushDelta ¶ added in v0.8.2
type PushDelta struct {
Units, Queued, Limited, NoDevices, NoConsent int
Sent, Invalid, Failed int
DoneBatch, DoneUnit string
}
PushDelta is what to add to a send's totals. DoneBatch and DoneUnit name the batch or unit that finished: it is counted once, however many times the same update runs.
type PushJob ¶ added in v0.8.2
type PushJob struct {
Kind string
SendID string
// Messages are the message in each language of the realm.
Messages map[string]push.Message
// Batch: the users. Plan: the audience, the last user id it paged to and the next batch.
Users []string
Audience *PushAudience
After string
NextBatch int
// RequiresConsent skips users who don't hold the consent, in a batch or a plan.
RequiresConsent string
// Deliver: who gets it, and how many users of the unit's chunk were not delivered to.
Recipients []PushRecipient
Limited int
NoDevices int
NoConsent int
}
PushJob is what a push job carries.
type PushOutboxEntry ¶ added in v0.8.2
type PushOutboxEntry struct {
ID string
SendID string
UserID string
DeviceID string
Platform string
Status string // push.Status*
Attempt int
Message push.Message
CreatedAt time.Time
ExpiresAt time.Time
}
PushOutboxEntry is a delivery the capture provider stored instead of sending: development only. Unlike a send's record it holds the message.
type PushRecipient ¶ added in v0.8.2
type PushRecipient struct {
UserID string
Locale string
Devices []string // device ids: tokens are loaded when the unit is delivered
}
PushRecipient is a user of a delivery unit with the devices to deliver to.
type PushSend ¶ added in v0.8.2
type PushSend struct {
ID string
Kind string // the template kind, or push.RawKind
Sender string // function:<database>/<name>, or admin:<id>
CreatedAt time.Time
ExpiresAt time.Time
// Users is the number of users named; -1 when the send has an audience.
Users int
// Planned says every batch exists (Batches is final).
Planned bool
Batches int
// Units is the delivery units made so far (final once Planned and every batch is done).
Units int
BatchesDone int
UnitsDone int
// Totals, by what became of each user or device.
Queued int // users handed to delivery
Limited int // users over their limits
NoDevices int // users with no device to reach
NoConsent int // users who don't hold the consent the send requires
Sent int // devices
Invalid int // devices removed as dead
Failed int // devices not delivered to
// CompletedAt is zero until everything is done.
CompletedAt time.Time
}
PushSend is the record of one send: totals, never content.
type PushSendFilter ¶ added in v0.8.2
PushSendFilter selects sends to list. Sender is "function:<database>/<name>" or "admin:<id>"; zero fields match everything.
type PushSendInput ¶ added in v0.8.2
type PushSendInput struct {
Kind string
Sender string
Messages map[string]push.Message
Users []string
Audience *PushAudience
// RequiresConsent names a consent a user must hold to be sent to; the others are
// counted as no_consent.
RequiresConsent string
}
PushSendInput is a send, validated and rendered by the caller.
type PushStarted ¶ added in v0.8.2
type PushStarted struct {
SendID string
// Users is the number named (-1 for an audience); Jobs the jobs created.
Users, Jobs int
// Known says Queued, Limited and NoDevices are final: a send that fits one batch is
// planned at once.
Known bool
Queued, Limited, NoDevice, NoConsent int
}
PushStarted is what starting a send reports.
type PushUserFilter ¶ added in v0.8.2
type PushUserFilter = PushAudience
PushUserFilter selects users for an audience page.
type ReauthGrant ¶ added in v0.8.2
ReauthGrant is a re-authentication token.
type Redeemed ¶ added in v0.8.2
type Redeemed struct {
Principal Principal
Token string
NewUser bool
Profile map[string]string
// Challenge is set instead of a session when the user needs a second step.
Challenge *IssuedChallenge
// RecoveryCodesLeft is set when a recovery code ended the sign-in: how many remain.
RecoveryCodesLeft *int
}
Redeemed is the outcome of redeeming a login code: the session, whether the sign-in made the user and, if so, what the provider said of them.
type RefusedError ¶ added in v0.8.2
RefusedError is a sign-in the account's state refuses; it is ErrSignInRefused to the caller, who is not told why, and says why to the audit.
func (*RefusedError) Error ¶ added in v0.8.2
func (e *RefusedError) Error() string
func (*RefusedError) Is ¶ added in v0.8.2
func (e *RefusedError) Is(target error) bool
type RevokeJob ¶ added in v0.8.2
type RevokeJob struct {
UserID string
ClientID string // the client id the token was issued to
Token string // sealed (SealToken)
}
RevokeJob is a job that revokes an Apple refresh token. It holds the token sealed, and a worker drops it once Apple has revoked it.
type RoleGrant ¶ added in v0.8.3
type RoleGrant struct {
Role string
From time.Time // zero: from the start
Until time.Time // zero: no end
GrantedBy string // user id; "" for an administrator or function
GrantedAt time.Time
}
RoleGrant is one organization role held by a member, with an optional window and who gave it.
type RoleReport ¶
type RoleReport struct {
// DBOnly maps emails to roles assigned only in the database, which a
// rebuild from realm.yaml wouldn't restore.
DBOnly map[string][]string
// Undeclared maps emails to roles realm.yaml no longer declares.
Undeclared map[string][]string
// NetworksDBOnly lists users with network restrictions that realm.yaml
// doesn't set, which a rebuild from realm.yaml wouldn't restore.
NetworksDBOnly []string
// Admins counts the people who can use the admin API with a session:
// emails seeded into an admin role in realm.yaml, and users holding
// one in the database, each counted once.
Admins int
}
RoleReport lists role assignments that realm.yaml doesn't account for.
type RoleRequiresMFAError ¶ added in v0.8.3
RoleRequiresMFAError: the action needs a role that requires a second factor and the session used none.
func IsRoleRequiresMFA ¶ added in v0.8.3
func IsRoleRequiresMFA(err error) (*RoleRequiresMFAError, bool)
IsRoleRequiresMFA reports whether err is a RoleRequiresMFAError, and which.
func (*RoleRequiresMFAError) Error ¶ added in v0.8.3
func (e *RoleRequiresMFAError) Error() string
type RotatedKey ¶ added in v0.9.1
type RotatedKey struct {
Name string
Fingerprint string
Previous string
Version int
Rewrapped int
Resumed bool
Value string
}
RotatedKey is what a rotation answers. Value is set only for a generated key.
type SSOHost ¶ added in v0.9.13
type SSOHost struct {
Users *Users
Realm string
// BaseURL is backd's public address for this realm (email.public_url, else BACKD_URL).
BaseURL string
// Endpoints overrides a provider's URLs (tests point it at a fake); the built-in ones when nil.
Endpoints func(*registry.Provider) sso.Endpoints
// contains filtered or unexported fields
}
SSOHost is a realm's side of the sso engine's ports.
func (*SSOHost) Engine ¶ added in v0.9.13
Engine is the engine over this host and the given protocol.
func (*SSOHost) Ports ¶ added in v0.9.13
Ports are the four ports of the engine over this host, for tests and for callers that build their own.
func (*SSOHost) ProviderOf ¶ added in v0.9.13
func (h *SSOHost) ProviderOf(ctx context.Context, p *registry.Provider, conn *OrgConnection) (sso.Provider, bool, error)
ProviderOf is the provider as the engine uses it, for a realm provider or a connection's: secrets read, endpoints set, the restrictions and the authority check attached. ok is false when a secret it needs is not set (the provider is then unavailable for a redirect flow; the provider returned has no secret then, which a native sign-in of Google or Microsoft does not need).
type SSOHostData ¶ added in v0.9.13
type SSOHostData struct {
// ScopeOrg is the organization the person signs in to (the session records it): the
// connection's organization, or for a realm provider used to sign in to one, that
// organization. UnknownOrgScope for one that can't be signed in to.
ScopeOrg string `json:"scope_org,omitempty"`
// Invitation is the hash of the invitation token the attempt carried.
Invitation string `json:"invitation,omitempty"`
// Locales are the languages asked for, best first.
Locales []string `json:"locales,omitempty"`
// Consents are the consents the app accepted for a sign-up through the attempt.
Consents map[string]string `json:"consents,omitempty"`
}
SSOHostData is what a sign-in attempt carries for backd: the engine stores it with the attempt and hands it back untouched.
func DecodeSSOHost ¶ added in v0.9.13
func DecodeSSOHost(raw []byte) SSOHostData
DecodeSSOHost reads what SSOHostData.Encode wrote.
func (SSOHostData) Encode ¶ added in v0.9.13
func (d SSOHostData) Encode() []byte
Encode is the bytes the engine stores.
type SSORequiredResult ¶ added in v0.9.3
type SSORequiredResult struct {
Membership Membership
// WithoutSSO is how many members had no identity on a connection when it was turned on: they
// can't come in until they sign in through it. Revoked is how many sessions it ended.
WithoutSSO int
Revoked int64
}
SSORequiredResult is the organization after sso_required changed, and what turning it on did.
type ScheduleState ¶ added in v0.8.0
type ScheduleState struct {
Database, Function string
Paused bool
ChangedAt time.Time
ChangedBy string // the actor that last paused or resumed it
}
ScheduleState is the runtime state of a scheduled function: whether an administrator paused it. A function with no state is running. The state is kept after a resume, because ChangedAt keeps a run that fell inside the pause from being made up at the moment of the resume.
type SchemaMigrateCounts ¶ added in v0.9.11
type SchemaMigrateCounts struct {
Scanned int64
Migrated int64
Skipped int64 // already at the current version when the job got to them
Failed int64
}
SchemaMigrateCounts is what a job did (or, in a dry run, would do).
type SchemaMigrateFailure ¶ added in v0.9.11
type SchemaMigrateFailure struct {
ID string
Step string // "2 → 3"
Kind string // one of the Fail* kinds
Path string // the JSON path, for an invalid result
Keyword string // the schema keyword, for an invalid result
}
SchemaMigrateFailure is one document that did not migrate and stays at its version. It never holds a value: the id, where it stopped and why.
type SchemaMigrateJob ¶ added in v0.9.11
type SchemaMigrateJob struct {
Database string
Collection string
Target int // the collection's current version when the job was queued
DryRun bool // runs the migrations and validates, writes nothing
After string
SchemaMigrateCounts
// Failures lists the failed documents, up to MaxSchemaMigrateFailures; Failed counts them all.
Failures []SchemaMigrateFailure
// Ending is set when the job ends: complete, partial or cancelled.
Ending string
}
SchemaMigrateJob is what a migration job carries: the collection, the version it migrates to, the place it reached, what it did so far and what failed.
type Secret ¶
type Secret struct {
Database string // "": realm scope (when Org is empty too)
// Org is the id of the organization an organization-scope secret belongs to. Such a
// secret is written by the organization sign-in code and never read back by anybody.
Org string
Name string
Type string // "": a value functions and providers may read; SecretTypeKey: a field key
// Fingerprint identifies a key's value without revealing it (KeyFingerprint); empty for values.
Fingerprint string
// Version counts a key's values: 1 when created, +1 at each rotation (0 reads as 1).
// Prev* hold the value being replaced while a rotation is unfinished, sealed like the
// current one, so data keys wrapped by it can still be opened until they are re-wrapped.
Version int
PrevCiphertext string
PrevNonce string
PrevVersion int
Ciphertext string // base64
Nonce string // base64
KeyID string // fingerprint of the key it was encrypted with
CreatedAt time.Time
UpdatedAt time.Time
UpdatedBy string
}
Secret is one encrypted value, bound to a realm (implicitly, by which Users it's stored through), a scope and a name. Org set means the organization scope; otherwise Database empty means the realm scope and anything else the database scope.
type SecretCache ¶
type SecretCache struct {
// contains filtered or unexported fields
}
SecretCache holds decrypted secret values (and confirmed-missing lookups) for secretCacheTTL, shared across every realm's Users: NewSecretCache once, assigned to each Users.Cache. Each key includes the realm, so it's safe for every realm to share one instance.
type SecretCipher ¶
type SecretCipher = authcore.SecretCipher
type SecretMeta ¶
type SecretMeta struct {
Database string
Org string
Name string
Type string
// Fingerprint is set for keys.
Fingerprint string
CreatedAt time.Time
UpdatedAt time.Time
UpdatedBy string
}
SecretMeta is a secret without its value, as listed: names, scope and who last changed it, never the value.
type Session ¶
type Session struct {
ID string // public id, used to list and revoke sessions
UserID string
TokenHash string
CreatedAt time.Time
LastUsedAt time.Time
ExpiresAt time.Time
// MaxLifetime is the organization's own limit on the lifetime of its sessions, fixed when the
// session opened (0: the realm's).
MaxLifetime time.Duration
// Methods are how the session was created: the first factor, plus "totp" or "recovery"
// when a second factor was used; MFA says it was. Empty for sessions from before
// they were recorded.
Methods []string
MFA bool
// Strategy is the strategy the session was made with ("" for a session from before
// strategies, or one an organization's connection opened): its roles are those that accept it.
Strategy string
// Passkey is the id of the passkey a sign-in with one used ("" otherwise): removing the passkey
// ends the sessions it opened.
Passkey string
// PasskeySynced says that passkey syncs between devices (backup eligible): rules see it as
// user.passkey_synced, so one can demand a hardware key.
PasskeySynced bool
// Org is the organization the session is scoped to: it reaches that one and no other
// (design/scoped-sessions.md). "" for an operator's session, and for one from before sessions
// were scoped.
Org string
}
Session is a signed-in session. Only a hash of its token is stored.
func (Session) Connection ¶ added in v0.9.3
Connection says whether the session was opened through an organization's connection, and which. Such a session proves "the provider of the organization says this is the person", not that the person owns the account: it can't change what protects it.
type SignInClaims ¶ added in v0.9.3
type SignInClaims struct {
Email string
EmailVerified bool
// HostedDomain is Google's hd, Tenant Microsoft's tid.
HostedDomain string
Tenant string
// Username is Microsoft's preferred_username.
Username string
}
SignInClaims is what a verified ID token says that a connection's restriction checks.
type SignupRequest ¶ added in v0.4.0
type SignupRequest struct {
Email, Password, Invitation string
Locales []string // most wanted first
RedirectTo string // already checked against the realm's allowed redirects
ClientIP, RequestID string
// Consents are the consents accepted at sign-up: name to version. Every required
// consent of the realm must be there at its current version.
Consents map[string]string
UserAgent string
}
SignupRequest is a sign-up from a client.
type SignupResult ¶ added in v0.4.0
type SignupResult struct {
Principal Principal
Token string
Pending bool
// Challenge is set instead of a session when the new user has to set a second factor
// up first (their roles require it).
Challenge *IssuedChallenge
}
SignupResult is what a sign-up gives back: a session, or (Pending) none because the realm wants the address verified first.
type Step ¶ added in v0.8.0
type Step struct {
N int
Name string
Status string // StepRunning, StepDone, StepFailed, StepTimedOut or StepCancelled
StartedAt time.Time
EndedAt time.Time // zero while running
DurationMS int64
Current float64
Total *float64 // nil when the step has no known size
Message string
UpdatedAt time.Time
}
Step is one named step of an attempt, with how far it got.
type StorageUsage ¶ added in v0.8.0
type StorageUsage struct {
Realm StorageUsageTotals
Users []UserUsage
}
StorageUsage is a realm's running totals: all of it, and the users holding the most.
type StorageUsageTotals ¶ added in v0.8.0
StorageUsageTotals is bytes and files a scope holds.
type Store ¶
type Store interface {
// The passkeys of the users (the leaf package's eight methods).
passkey.Store
// CreateUser inserts a user; ErrEmailTaken if the email exists.
CreateUser(ctx context.Context, u User) error
UserByEmail(ctx context.Context, email string) (User, error)
// UserByID returns the user with that id; ErrNotFound if none.
UserByID(ctx context.Context, id string) (User, error)
ListUsers(ctx context.Context) ([]User, error)
// ListUsersPage returns one page of users sorted by email: the users whose
// email sorts after `after` (all when empty), skipping skip of them, at most
// limit; hasMore says whether more follow. Emails are unique, so `after` is
// an exact position. It never reads more than the page. A non-empty contains
// keeps the users whose email holds it (emails are stored lower-case, so
// pass it lower-case): a scan of the email index, not of the documents.
ListUsersPage(ctx context.Context, contains, after string, skip, limit int) (users []User, hasMore bool, err error)
// AddRoles adds roles the user doesn't have yet, setting UpdatedAt.
AddRoles(ctx context.Context, userID string, roles []string, now time.Time) error
// RemoveRole removes a role from the user, setting UpdatedAt.
RemoveRole(ctx context.Context, userID, role string, now time.Time) error
// UpdateUser applies upd and sets UpdatedAt to now.
UpdateUser(ctx context.Context, id string, upd UserUpdate, now time.Time) error
// ListUnverifiedUsers returns up to limit users whose address is still
// unverified and who were created before the given time, oldest first.
ListUnverifiedUsers(ctx context.Context, createdBefore time.Time, limit int) ([]User, error)
// EraseUser turns the user into a tombstone: it deletes their sessions and
// sign-in methods, and sets email (the unique placeholder), ErasedAt,
// disabled and verified, with no roles, locale, networks or pending and
// previous addresses. Repeating it is harmless.
EraseUser(ctx context.Context, id, placeholderEmail string, now time.Time) error
// DeleteEmailTokensOfUser removes the user's email tokens.
DeleteEmailTokensOfUser(ctx context.Context, userID string) error
// DeleteEmailJobsOfUser removes the email jobs addressed to the user.
DeleteEmailJobsOfUser(ctx context.Context, userID string) error
// AddEraseCount adds n to the erase job's count under key
// ("<database>/<collection>/<operation>"), atomically.
AddEraseCount(ctx context.Context, jobID, key string, n int64) error
// PutChallenge stores a pending step. GetChallenge returns the unexpired one with that
// id (ErrNotFound if none); ClaimChallenge does too and deletes it, in one atomic step,
// so a challenge works once; CountChallengeAttempt adds an attempt and returns the new
// state; DeleteChallenge and DeleteChallengesOfUser remove them.
PutChallenge(ctx context.Context, c AuthChallenge) error
GetChallenge(ctx context.Context, id string, now time.Time) (AuthChallenge, error)
ClaimChallenge(ctx context.Context, id string, now time.Time) (AuthChallenge, error)
CountChallengeAttempt(ctx context.Context, id string, now time.Time) (AuthChallenge, error)
DeleteChallenge(ctx context.Context, id string) error
DeleteChallengesOfUser(ctx context.Context, userID string, kinds ...string) error
// ChallengeOfUser returns the newest unexpired challenge of a kind that a user has
// (ErrNotFound if none); ChallengeByToken the unexpired challenge of a kind whose link
// token has that hash; SetChallengeSecrets stores the hashes of a challenge's link token
// ("" leaves it) and code, and returns the unexpired challenge.
ChallengeOfUser(ctx context.Context, userID, kind string, now time.Time) (AuthChallenge, error)
ChallengeByToken(ctx context.Context, tokenHash, kind string, now time.Time) (AuthChallenge, error)
SetChallengeSecrets(ctx context.Context, id, tokenHash, codeHash string, now time.Time) (AuthChallenge, error)
// MFAOf returns a user's second-factor record (ErrNotFound if none); PutMFA stores it,
// replacing; DeleteMFA removes it; MFAUserIDs lists the users that have one.
MFAOf(ctx context.Context, userID string) (MFARecord, error)
PutMFA(ctx context.Context, rec MFARecord) error
DeleteMFA(ctx context.Context, userID string) error
MFAUserIDs(ctx context.Context) ([]string, error)
// AdvanceMFAStep moves the last accepted TOTP step forward to step, atomically; false
// when step is not greater than it (a replay).
AdvanceMFAStep(ctx context.Context, userID string, step int64) (bool, error)
// UseRecoveryCode removes the recovery code with that keyed hash, atomically, and says
// how many are left; ok is false when the user has no such code.
UseRecoveryCode(ctx context.Context, userID, hash string) (left int, ok bool, err error)
// ClearJobInput replaces a job's input with an empty object: what it held (a new user's
// profile) is not kept after the job has run.
ClearJobInput(ctx context.Context, jobID string) error
// ClearRevokeToken removes the sealed token a revoke job held.
ClearRevokeToken(ctx context.Context, jobID string) error
// ClearEraseEmail removes the email an erase job held.
ClearEraseEmail(ctx context.Context, jobID string) error
// ReopenJob queues a job that ended in failure again, with a fresh
// attempt count and expiry; false when it isn't a failed job.
ReopenJob(ctx context.Context, id string, expiresAt time.Time) (bool, error)
// DeleteUser removes the user with their identities and sessions.
DeleteUser(ctx context.Context, id string) error
// PasswordEpoch returns the realm's password epoch, the zero value when none was set.
// SetPasswordEpoch stores e when its ValidAfter is later than the current one and says
// whether it did: an epoch only moves forward.
PasswordEpoch(ctx context.Context) (PasswordEpoch, error)
SetPasswordEpoch(ctx context.Context, e PasswordEpoch) (bool, error)
// DeleteAllSessions revokes every session of the realm, and the devices they registered,
// and says how many sessions. CountPasswordIdentities says how many accounts have a password.
DeleteAllSessions(ctx context.Context) (int64, error)
CountPasswordIdentities(ctx context.Context) (int64, error)
// PasswordUserIDs returns, in id order, up to limit ids of users, after the id `after`,
// whose password was set before the time: the accounts an epoch at that time expires.
PasswordUserIDs(ctx context.Context, before time.Time, after string, limit int) ([]string, error)
// SetPasswordNoticeProgress keeps a notification job's place and counts.
SetPasswordNoticeProgress(ctx context.Context, jobID, after string, c PasswordNoticeCounts) error
// SetEncryptProgress keeps an encryption migration's place and counts.
SetEncryptProgress(ctx context.Context, jobID, after string, c EncryptCounts) error
// SetSchemaMigrateProgress keeps a schema migration's place, counts and failures.
SetSchemaMigrateProgress(ctx context.Context, jobID string, m SchemaMigrateJob) error
// PutIdentity creates the identity, or, when one with the same provider
// and subject exists, updates its credentials and UpdatedAt (keeping its
// ID and CreatedAt). ErrIdentityExists when the user already has another
// identity of the provider, or the provider account belongs to another user.
PutIdentity(ctx context.Context, id Identity) error
Identity(ctx context.Context, provider, subject string) (Identity, error)
// IdentityIn, IdentityOfIn and DeleteIdentityIn are the three lookups above for the identities of
// an organization's connection; the plain ones are the realm's (org "").
IdentityIn(ctx context.Context, provider, org, issuer, subject string) (Identity, error)
IdentityOfIn(ctx context.Context, userID, provider, org string) (Identity, error)
DeleteIdentityIn(ctx context.Context, userID, provider, org string) error
// ListIdentities returns a user's identities, oldest first.
ListIdentities(ctx context.Context, userID string) ([]Identity, error)
// IdentityOf returns a user's identity of a provider; ErrNotFound if none.
IdentityOf(ctx context.Context, userID, provider string) (Identity, error)
// UpdateIdentity applies upd to the identity with that id and sets UpdatedAt
// to now; ErrNotFound if none.
UpdateIdentity(ctx context.Context, id string, upd IdentityUpdate, now time.Time) error
// DeleteIdentity removes a user's identity of a provider; ErrNotFound if none.
DeleteIdentity(ctx context.Context, userID, provider string) error
// PutOAuthState stores a sign-in attempt; ClaimOAuthState deletes and returns the
// unexpired attempt with that id (ErrNotFound if none), so a state works once.
PutOAuthState(ctx context.Context, st OAuthState) error
ClaimOAuthState(ctx context.Context, id string, now time.Time) (OAuthState, error)
// PutLoginCode and ClaimLoginCode are the same for the one-time login codes.
PutLoginCode(ctx context.Context, lc LoginCode) error
ClaimLoginCode(ctx context.Context, id string, now time.Time) (LoginCode, error)
// DeleteSessions revokes every session of the user and says how many.
DeleteSessions(ctx context.Context, userID string) (int64, error)
CreateSession(ctx context.Context, s Session) error
// SessionByTokenHash returns the session and its user; ErrNotFound if
// either doesn't exist.
SessionByTokenHash(ctx context.Context, hash string) (Session, User, error)
// TouchSession records a use of the session and its new expiry.
TouchSession(ctx context.Context, id string, lastUsed, expires time.Time) error
// ListSessions returns the user's sessions, newest first.
ListSessions(ctx context.Context, userID string) ([]Session, error)
// DeleteSession revokes one session of the user; ErrNotFound if the
// user has no session with that id.
DeleteSession(ctx context.Context, userID, id string) error
// DeleteOrgSessions revokes the sessions scoped to an organization and says how many: those of
// one user when user is not empty, and those a provider opened (the first method of the session)
// when provider is not empty.
DeleteOrgSessions(ctx context.Context, org, user, provider string) (int64, error)
// DeleteOrgSessionsNotOpenedBy revokes the sessions scoped to an organization that were not
// opened through one of its own connections (ConnectionMethod), and says how many.
DeleteOrgSessionsNotOpenedBy(ctx context.Context, org string) (int64, error)
// DeleteOtherSessions revokes every session of the user except keepID
// and says how many.
DeleteOtherSessions(ctx context.Context, userID, keepID string) (int64, error)
// DeleteSessionsOfPasskey revokes the sessions a passkey opened.
DeleteSessionsOfPasskey(ctx context.Context, userID, passkeyID string) (int64, error)
// PutDevice registers a device: a new one, or, when the token's hash exists, that device
// moved to this user and session (a new id, so the earlier owner's id is dead) with the
// new token and name. It returns what is stored and whether it moved from another user.
PutDevice(ctx context.Context, d Device) (Device, bool, error)
// ListDevices returns the user's devices, most recently seen first.
ListDevices(ctx context.Context, userID string) ([]Device, error)
// DeleteDevice removes one of the user's devices; ErrNotFound if it isn't theirs.
DeleteDevice(ctx context.Context, userID, id string) error
// DeleteOldestDevices removes the user's least recently seen devices beyond keep, never
// the device keepID, and says how many.
DeleteOldestDevices(ctx context.Context, userID string, keep int, keepID string) (int64, error)
// DeleteStaleDevices removes the devices last seen before the time.
DeleteStaleDevices(ctx context.Context, before time.Time) (int64, error)
// DeleteOrphanedDevices removes the devices whose session doesn't exist or has expired.
DeleteOrphanedDevices(ctx context.Context, now time.Time) (int64, error)
// The realm's app configuration state and history (internal/appconfig).
appconfig.Store
// AppendConsentRecord adds a record to the user's append-only consent history and
// ListConsentRecords returns it, oldest first.
AppendConsentRecord(ctx context.Context, r ConsentRecord) error
ListConsentRecords(ctx context.Context, userID string) ([]ConsentRecord, error)
// ReduceConsentRecords is what an erase leaves of a user's consent records: it removes
// their IP address and user agent and replaces the user id with a pseudonym, and, when
// deleteAt isn't zero, sets the time a retention will remove them. It says how many.
// DeleteConsentRecordsOf removes them all (a realm that keeps none after an erase).
ReduceConsentRecords(ctx context.Context, userID, pseudonym string, deleteAt time.Time) (int64, error)
DeleteConsentRecordsOf(ctx context.Context, userID string) (int64, error)
// SetUserConsent sets the version of a consent the user holds ("" removes it: withdrawn).
SetUserConsent(ctx context.Context, userID, consent, version string) error
// ConsentVersionsInUse lists the distinct consent and version pairs records refer to.
ConsentVersionsInUse(ctx context.Context) ([]ConsentRef, error)
// DevicesByIDs returns the devices that exist among the ids. LiveDevicesOf returns the
// devices of the users whose registering session exists and hasn't expired, by user id,
// most recently seen first. DeleteDeviceByID removes a device whatever its owner.
DevicesByIDs(ctx context.Context, ids []string) ([]Device, error)
LiveDevicesOf(ctx context.Context, userIDs []string, now time.Time) (map[string][]Device, error)
DeleteDeviceByID(ctx context.Context, id string) error
// DeleteDevicesOfPlatform removes every device of a platform, and says how many.
DeleteDevicesOfPlatform(ctx context.Context, platform string) (int64, error)
// UsersByIDs returns the users that exist among the ids. AudienceUserIDs returns the ids
// of up to limit active users (not disabled, not erased) matching the audience, after the
// id `after`, in id order.
UsersByIDs(ctx context.Context, ids []string) ([]User, error)
AudienceUserIDs(ctx context.Context, a PushAudience, after string, limit int) ([]string, error)
// The record of a push send. AddPushSend adds the delta atomically (a finished batch or
// unit named in it counts once), sets CompletedAt when everything is done and returns the
// record. SetPushPlanned says every batch exists, and how many; SetPushPlanPosition keeps
// a planner job's place; UpdatePushRecipients replaces what a delivery unit still has to do.
CreatePushSend(ctx context.Context, p PushSend) error
PushSendByID(ctx context.Context, id string) (PushSend, error)
// PutPushOutbox stores a delivery the capture provider took; ListPushOutbox returns the
// newest ones.
PutPushOutbox(ctx context.Context, e PushOutboxEntry) error
ListPushOutbox(ctx context.Context, limit int) ([]PushOutboxEntry, error)
// ListPushSends returns sends newest first, and whether more follow.
ListPushSends(ctx context.Context, f PushSendFilter) ([]PushSend, bool, error)
AddPushSend(ctx context.Context, id string, d PushDelta, now time.Time) (PushSend, error)
SetPushPlanned(ctx context.Context, id string, batches int, now time.Time) error
SetPushPlanPosition(ctx context.Context, jobID, after string, nextBatch int) error
UpdatePushRecipients(ctx context.Context, jobID string, recipients []PushRecipient) error
// CreateAPIKey stores a key; ErrKeyNameTaken if the name exists.
CreateAPIKey(ctx context.Context, k APIKey) error
// APIKeyByHash returns the key with that hash; ErrKeyNotFound if none.
APIKeyByHash(ctx context.Context, hash string) (APIKey, error)
ListAPIKeys(ctx context.Context) ([]APIKey, error)
// DeleteAPIKey removes the named key; ErrKeyNotFound if none.
DeleteAPIKey(ctx context.Context, name string) error
// TouchAPIKey records a use of the key.
TouchAPIKey(ctx context.Context, hash string, at time.Time) error
// AppendAudit adds a record to the audit trail, which is never
// modified: records are only removed when they expire.
AppendAudit(ctx context.Context, rec AuditRecord) error
// ListAudit returns records matching f, newest first, and whether
// more follow.
ListAudit(ctx context.Context, f AuditFilter) ([]AuditRecord, bool, error)
CreateInvitation(ctx context.Context, inv Invitation) error
// ClaimInvitation atomically deletes and returns the unexpired
// invitation with that token hash; ErrNotFound if none.
ClaimInvitation(ctx context.Context, hash string, now time.Time) (Invitation, error)
// ClaimInvitationByID is ClaimInvitation for an invitation known by its
// id (one sent by email: nobody holds its own token).
ClaimInvitationByID(ctx context.Context, id string, now time.Time) (Invitation, error)
// ListInvitations returns all invitations, newest first.
ListInvitations(ctx context.Context) ([]Invitation, error)
// DeleteInvitation removes an invitation by id; ErrNotFound if none.
DeleteInvitation(ctx context.Context, id string) error
// Organizations (design/organizations.md). CreateOrg inserts the organization and its first
// member together (ErrSlugTaken when the slug is in use by one that isn't deleted).
CreateOrg(ctx context.Context, o Org, first OrgMember) error
// OrgByID returns the organization, deleted ones too; ErrNotFound if none.
OrgByID(ctx context.Context, id string) (Org, error)
// OrgBySlug returns the organization with that slug that isn't deleted; ErrNotFound if none.
OrgBySlug(ctx context.Context, slug string) (Org, error)
// OrgsByIDs returns the organizations that exist, by id.
OrgsByIDs(ctx context.Context, ids []string) (map[string]Org, error)
// UpdateOrg applies upd, sets UpdatedAt and returns the result; ErrSlugTaken, ErrNotFound.
UpdateOrg(ctx context.Context, id string, upd OrgUpdate, now time.Time) (Org, error)
// ListOrgs returns organizations, optionally of one status, newest first.
ListOrgs(ctx context.Context, status string) ([]Org, error)
// CountOrgsCreatedBy counts the organizations a user created, deleted ones included.
CountOrgsCreatedBy(ctx context.Context, userID string) (int, error)
// CountOrgMembers counts the members of each of the organizations (zero ones left out).
CountOrgMembers(ctx context.Context, orgs []string) (map[string]int, error)
// OrgMember returns a membership; ErrNotFound if none.
OrgMember(ctx context.Context, org, user string) (OrgMember, error)
// ListOrgMembers returns a page of an organization's members sorted by user id: those
// after `after`, at most limit; more says whether others follow.
ListOrgMembers(ctx context.Context, org, after string, limit int) (members []OrgMember, more bool, err error)
// OrgTeamHolders returns a page, sorted by user id, of the members of the team and the
// members holding a team role in it that counts at now; with role, only its holders.
OrgTeamHolders(ctx context.Context, org, team, role string, now time.Time, after string, limit int) (members []OrgMember, more bool, err error)
// PurgeExpiredTeamRoles removes the team role grants whose window ended before the instant,
// and says how many it removed.
PurgeExpiredTeamRoles(ctx context.Context, before time.Time) (int64, error)
// OrgTemplate returns an organization's override of a kind in a language; ErrNotFound if none.
OrgTemplate(ctx context.Context, org, kind, locale string) (OrgTemplate, error)
// ListOrgTemplates returns an organization's overrides.
ListOrgTemplates(ctx context.Context, org string) ([]OrgTemplate, error)
// PutOrgTemplate stores an override, with its versions.
PutOrgTemplate(ctx context.Context, t OrgTemplate) error
// DeleteOrgTemplate removes an override; ErrNotFound if none.
DeleteOrgTemplate(ctx context.Context, org, kind, locale string) error
// OrgMembersWithRoles returns the members holding any of the roles directly.
OrgMembersWithRoles(ctx context.Context, org string, roles []string) ([]OrgMember, error)
// OrgMembershipsOf returns up to limit memberships of a user; CountOrgMembershipsOf counts them.
OrgMembershipsOf(ctx context.Context, user string, limit int) ([]OrgMember, error)
CountOrgMembershipsOf(ctx context.Context, user string) (int, error)
// Transact runs fn so that the store writes it makes with the context it is given either
// all happen or none do. A transaction already in progress in ctx is joined, not nested.
// fn may run more than once (the database retries a transient conflict), so it must have no
// effect beyond those writes.
Transact(ctx context.Context, fn func(ctx context.Context) error) error
// PutOrgMember creates or replaces a membership (unique per organization and user).
PutOrgMember(ctx context.Context, m OrgMember) error
// NextOrgMemberSeq returns the next sequence number of the membership events of a user in an
// organization: it grows for ever, across leaving and joining again.
NextOrgMemberSeq(ctx context.Context, org, user string) (int64, error)
// DeleteOrgMember removes a membership; ErrNotFound if none.
DeleteOrgMember(ctx context.Context, org, user string) error
// Organization invitations. OrgInvitationByHash and ...ByID return ErrNotFound for none;
// UseOrgInvitation takes one use atomically (ErrNotFound when it can't: unknown, revoked,
// expired or used up) and returns the invitation.
CreateOrgInvitation(ctx context.Context, inv OrgInvitation) error
OrgInvitationByHash(ctx context.Context, hash string) (OrgInvitation, error)
OrgInvitationByID(ctx context.Context, org, id string) (OrgInvitation, error)
// The records of personal data exports (see UserExport): created when asked for, replaced as
// the job builds them. ListUserExports returns a user's, newest first.
// ListExpiredUserExports returns the ready ones whose retention ended by now, oldest first.
CreateUserExport(ctx context.Context, e UserExport) error
UserExportByID(ctx context.Context, id string) (UserExport, error)
ReplaceUserExport(ctx context.Context, e UserExport) error
ListUserExports(ctx context.Context, userID string, limit int) ([]UserExport, error)
ListExpiredUserExports(ctx context.Context, now time.Time, limit int) ([]UserExport, error)
// ListOrgInvitations returns an organization's invitations, newest first.
ListOrgInvitations(ctx context.Context, org string) ([]OrgInvitation, error)
// OrgInvitationsAddressedTo returns the invitations, of every organization, that name the
// user (by id) or the address (bound to an email), newest first. For the export of a user's data.
OrgInvitationsAddressedTo(ctx context.Context, userID, email string) ([]OrgInvitation, error)
// CountPendingOrgInvitations counts the invitations that can still be used.
CountPendingOrgInvitations(ctx context.Context, org string, now time.Time) (int, error)
UseOrgInvitation(ctx context.Context, id string, now time.Time) (OrgInvitation, error)
RevokeOrgInvitation(ctx context.Context, org, id string, now time.Time) error
// ReplaceOrgInvitationToken swaps the token hash (and the sealed token, "" for none).
ReplaceOrgInvitationToken(ctx context.Context, org, id, tokenHash, sealed string) error
DeleteOrgInvitation(ctx context.Context, org, id string) error
// Organization sign-in connections (design/sso.md §9): one per organization and provider.
// PutOrgConnection creates or replaces it, keeping Blocked, CreatedAt and the id of an
// existing one. OrgConnection and DeleteOrgConnection return ErrNotFound for none.
// OrgDomain claims (design/sso.md §10): PutOrgDomain creates or replaces one by its id and
// ErrDomainTaken when it would make a second organization hold a verified domain; the finders
// return ErrNotFound for none; DueOrgDomains are those whose next check is due; DeleteOrgDomains
// drops an organization's claims and counts them.
PutOrgDomain(ctx context.Context, d OrgDomain) error
OrgDomain(ctx context.Context, org, domain string) (OrgDomain, error)
OrgDomains(ctx context.Context, org string) ([]OrgDomain, error)
VerifiedOrgDomain(ctx context.Context, domain string) (OrgDomain, error)
DueOrgDomains(ctx context.Context, now time.Time, limit int) ([]OrgDomain, error)
DeleteOrgDomain(ctx context.Context, org, domain string) error
DeleteOrgDomains(ctx context.Context, org string) (int, error)
PutOrgConnection(ctx context.Context, c OrgConnection) error
OrgConnection(ctx context.Context, org, provider string) (OrgConnection, error)
// OrgConnections lists an organization's connections, sorted by provider.
OrgConnections(ctx context.Context, org string) ([]OrgConnection, error)
// CountDormantIdentities counts the identities of a connection (provider and organization) that an
// issuer other than the one given vouched for.
CountDormantIdentities(ctx context.Context, org, provider, issuer string) (int, error)
DeleteOrgConnection(ctx context.Context, org, provider string) error
// BlockOrgMember adds the user to Blocked in every connection of the organization (keeping the
// most recent MaxConnectionBlocked), and UnblockOrgMember takes them out of all of them.
BlockOrgMember(ctx context.Context, org, user string) error
UnblockOrgMember(ctx context.Context, org, user string) error
// ForgetUserInOrgs removes a user from the organization data (for an erase): their
// memberships (and so their teams), the invitations bound to their id or address, and
// created_by of the organizations and invitations they made. It returns the organizations
// they were a member of.
ForgetUserInOrgs(ctx context.Context, userID, email string) ([]string, error)
// ArchiveOrg ends an organization at once: its status becomes deleted (the record keeps its
// name and dates, and its slug as FormerSlug), and its memberships, teams and invitations
// are removed. ErrNotFound if none; ErrOrgNotActive if it was deleted already.
ArchiveOrg(ctx context.Context, id string, now time.Time) (Org, error)
// ReactivateOrg makes a deleted organization active again, with no members, and sets slug
// when it isn't empty (ErrSlugTaken).
ReactivateOrg(ctx context.Context, id, slug string, now time.Time) (Org, error)
// OrgTeamsByIDs returns the teams of the organization with these ids that exist.
OrgTeamsByIDs(ctx context.Context, org string, ids []string) ([]OrgTeam, error)
// CreateOrgTeam inserts a team; ErrTeamNameTaken when the organization has one of that name.
CreateOrgTeam(ctx context.Context, t OrgTeam) error
// UpdateOrgTeam replaces a team's name and roles; ErrTeamNameTaken, ErrNotFound.
UpdateOrgTeam(ctx context.Context, t OrgTeam) error
// DeleteOrgTeam removes the team and takes its id out of every membership of the
// organization; ErrNotFound if none.
DeleteOrgTeam(ctx context.Context, org, id string) error
// ListOrgTeams returns an organization's teams sorted by name.
ListOrgTeams(ctx context.Context, org string) ([]OrgTeam, error)
// OrgMembersInTeams returns the members who belong to any of the teams.
OrgMembersInTeams(ctx context.Context, org string, teams []string) ([]OrgMember, error)
// LoginAttempts returns the failure counter of key (zero if none).
LoginAttempts(ctx context.Context, key string) (Attempts, error)
// RecordLoginFailure increments key's counter atomically, setting its
// last failure to at; the counter is deleted at expires.
RecordLoginFailure(ctx context.Context, key string, at, expires time.Time) error
// ClearLoginAttempts deletes key's counter.
ClearLoginAttempts(ctx context.Context, key string) error
// AcquireLoginLock takes the lock of key for owner until the given time,
// atomically: it is free when nobody holds it or its lease ended at or
// before now. false means another owner holds it. The lock serializes the
// password checks of one account across every instance.
AcquireLoginLock(ctx context.Context, key, owner string, now, until time.Time) (bool, error)
// ReleaseLoginLock frees the lock if owner still holds it.
ReleaseLoginLock(ctx context.Context, key, owner string) error
// IncrementCounter atomically increments key's counter (creating it,
// or restarting it at 1 if its window has already ended) and returns
// the new count and when it resets. The same generic "N events per
// window" primitive login throttling uses, reused for function rate
// limits (roadmap F9), which is why it lives in the same collection.
IncrementCounter(ctx context.Context, key string, at, expires time.Time) (count int, resetAt time.Time, err error)
// RecordInvocation appends a function call record (roadmap F10).
// backd never updates or deletes them; MongoDB removes them when
// they expire.
RecordInvocation(ctx context.Context, r InvocationRecord) error
// ListInvocations returns records matching f, newest first, and
// whether more follow.
ListInvocations(ctx context.Context, f InvocationFilter) ([]InvocationRecord, bool, error)
// EnqueueJob stores a new async job (roadmap F11), queued for a worker.
EnqueueJob(ctx context.Context, j Job) error
// EnqueueJobs inserts jobs that carry their own ids, skipping those that exist; it returns
// how many were new.
EnqueueJobs(ctx context.Context, jobs []Job) (int, error)
// ClaimJob atomically claims the oldest job that's never been claimed,
// or whose lease has expired, leasing it to workerID until at plus
// the job's own timeout plus margin. found is false when there is
// none to claim.
ClaimJob(ctx context.Context, workerID string, at time.Time, margin time.Duration) (j Job, found bool, err error)
// RetryJob counts a failed attempt and queues the job again, not to be
// claimed before notBefore (it is still the same job: same id, same input).
RetryJob(ctx context.Context, id string, notBefore time.Time) error
// CompleteJob records a job's result; expiresAt starts its retention
// countdown (MongoDB removes it once past).
CompleteJob(ctx context.Context, id string, result JobResult, completedAt, expiresAt time.Time) error
// CancelJob ends a job that isn't done yet with the given result (status
// "cancelled"), clearing its lease. It reports whether it did: false when
// the job was already done (or is unknown).
CancelJob(ctx context.Context, id string, result JobResult, steps []Step, completedAt, expiresAt time.Time) (bool, error)
// ListJobs returns the jobs matching f, newest first, and whether
// more follow.
ListJobs(ctx context.Context, f JobFilter) ([]Job, bool, error)
// JournalFile records an upload; SetFileJournalStatus moves it to a new status
// (with the document that references it, if any) and sets when the record
// expires; StaleFileJournal lists uploads still writing or stored that were
// last updated before the given time.
JournalFile(ctx context.Context, e FileJournalEntry) error
SetFileJournalStatus(ctx context.Context, id, status, documentID string, at, expiresAt time.Time) error
StaleFileJournal(ctx context.Context, before, now time.Time, limit int) ([]FileJournalEntry, error)
// FileJournalEntry returns one upload's record (ErrNotFound); the others are
// the bookkeeping of pending uploads: completing one, claiming it once by its
// token hash (stored → attaching, ErrNotFound when it can't be taken), giving
// a claim back, and counting a caller's open ones.
FileJournalEntry(ctx context.Context, id string) (FileJournalEntry, error)
CompletePendingUpload(ctx context.Context, id, name, contentType, sha256sum string, size int64, uploadedAt time.Time, image string, at time.Time) error
ClaimPendingUpload(ctx context.Context, id, tokenHash, documentID string, now time.Time) (FileJournalEntry, error)
// ClaimDirectUpload is the same for a direct upload waiting for its bytes (writing →
// attaching); ReleaseUpload moves a claimed upload back to the given status.
ClaimDirectUpload(ctx context.Context, id, tokenHash string, now time.Time) (FileJournalEntry, error)
ReleaseUpload(ctx context.Context, id, status string, at time.Time) error
CountOpenPendingUploads(ctx context.Context, callerKey string, now time.Time) (int, error)
// QueueFileDeletion adds an object to delete (one per key); ClaimFileDeletions
// returns up to limit due ones and holds them until lease; CompleteFileDeletion
// removes one; RetryFileDeletion counts a failed attempt and holds it until
// notBefore.
QueueFileDeletion(ctx context.Context, d FileDeletion) error
// AddStorageUsage adds to the realm's running totals and, for a non-empty owner,
// the user's; StorageUsage reads them; FileDeletionStats describes the queue.
AddStorageUsage(ctx context.Context, owner string, bytes, files int64) error
StorageUsage(ctx context.Context, limit int) (StorageUsage, error)
// StorageUsageOf returns the realm's totals and one user's (zero for an owner of "").
StorageUsageOf(ctx context.Context, owner string) (realm, user StorageUsageTotals, err error)
FileDeletionStats(ctx context.Context) (FileDeletionStats, error)
ClaimFileDeletions(ctx context.Context, now, lease time.Time, limit int) ([]FileDeletion, error)
CompleteFileDeletion(ctx context.Context, key string) error
RetryFileDeletion(ctx context.Context, key string, notBefore time.Time) error
// RenewJobLease moves the lease of a running job's attempt to until; false
// when the job no longer runs that attempt.
RenewJobLease(ctx context.Context, id string, attempt int, until time.Time) (bool, error)
// SetCheckReport stores a collection's latest schema check report, replacing
// the previous one; ListCheckReports and GetCheckReport read them (documents
// false leaves the lists of invalid documents out).
SetCheckReport(ctx context.Context, r CheckReport) error
ListCheckReports(ctx context.Context, documents bool) ([]CheckReport, error)
GetCheckReport(ctx context.Context, database, collection string) (CheckReport, bool, error)
// ImageDeclarations returns, by "<database>/<collection>.<field>/<version>", the
// fingerprint of each declared image version as it was when a worker last looked;
// SetImageDeclaration records one.
ImageDeclarations(ctx context.Context) (map[string]string, error)
SetImageDeclaration(ctx context.Context, key, fingerprint string) error
// SetJobSteps replaces the steps of a running job's attempt; false when the
// job is not running that attempt (so a late write changes nothing).
SetJobSteps(ctx context.Context, id string, attempt int, steps []Step, omitted int) (bool, error)
// GetJob returns one job by id; found is false if there is none.
GetJob(ctx context.Context, id string) (j Job, found bool, err error)
// CreateEmailToken stores a token's hash with its purpose and user.
CreateEmailToken(ctx context.Context, t EmailToken) error
// GetEmailToken returns the token with this hash whatever its state, or
// ErrInvalidToken when there is none.
GetEmailToken(ctx context.Context, hash string) (EmailToken, error)
// RedeemEmailToken atomically marks the token with this hash and purpose
// used, if it is unused and unexpired at now, and returns it; otherwise
// ErrInvalidToken.
RedeemEmailToken(ctx context.Context, hash, purpose string, now time.Time) (EmailToken, error)
// InvalidateEmailTokens marks used every unused token of the user and
// purpose.
InvalidateEmailTokens(ctx context.Context, userID, purpose string, now time.Time) error
// ClaimIdempotency (roadmap F12) atomically inserts rec if its id
// isn't already used, or returns the existing record (running or
// done) if it is. claimed is false in the second case.
ClaimIdempotency(ctx context.Context, rec IdempotencyRecord) (existing IdempotencyRecord, claimed bool, err error)
// CompleteIdempotency stores a claimed key's outcome: result for a
// sync call, jobID for async (mutually exclusive). expiresAt starts
// its retention countdown.
CompleteIdempotency(ctx context.Context, id string, result *JobResult, jobID string, completedAt, expiresAt time.Time) error
// ReleaseIdempotency removes a claim that shouldn't be remembered
// (an infrastructure failure, not a real outcome), so a retry can
// go through cleanly instead of being stuck "running" forever.
ReleaseIdempotency(ctx context.Context, id string) error
// SetScheduleState stores a scheduled function's state, replacing any.
SetScheduleState(ctx context.Context, st ScheduleState) error
// ListScheduleStates returns every stored state.
ListScheduleStates(ctx context.Context) ([]ScheduleState, error)
// UpsertSecret creates or replaces the secret at (s.Scope(), s.Name),
// keeping its original CreatedAt on an update. A scope is the database
// name, "" for the realm, or OrgScope(id) for an organization.
UpsertSecret(ctx context.Context, s Secret) error
// CreateSecret stores a new secret, ErrSecretExists if the scope and name are taken.
CreateSecret(ctx context.Context, s Secret) error
// ReplaceKeySecret stores a rotated key if the stored one still has version ifVersion; false
// when it does not (another rotation got there first).
ReplaceKeySecret(ctx context.Context, s Secret, ifVersion int) (bool, error)
// SecretByScope returns one secret; ErrSecretNotFound if none.
SecretByScope(ctx context.Context, scope, name string) (Secret, error)
// ListSecrets returns every secret's metadata, sorted by scope
// (realm scope, "", first) then name.
ListSecrets(ctx context.Context) ([]Secret, error)
// DeleteSecret removes one; ErrSecretNotFound if none.
DeleteSecret(ctx context.Context, scope, name string) error
}
Store persists users, identities and sessions of one realm.
type TOTPSetup ¶ added in v0.8.2
type TOTPSetup struct {
SetupID string
Secret string // base32, for typing in
URI string // otpauth://
QR string // a PNG data URI of the URI
Expires time.Time
}
TOTPSetup is a secret an authenticator app is to be given.
type TeamMemberView ¶ added in v0.8.3
type TeamMemberView struct {
MemberView
// InTeam says the member belongs to the team (a holder may only hold a role in it).
InTeam bool
// Roles are the team roles the member holds in this team, in force now.
Roles []string
}
TeamMemberView is a member or role holder of one team.
type TeamRoleGrant ¶ added in v0.8.3
TeamRoleGrant is a team role held by a member: the grant of an organization role plus the team it is held in (design/team-access.md §3).
type TeamRoleOp ¶ added in v0.8.3
type TeamRoleOp int
TeamRoleOp is what a request does to a team role grant.
const ( TeamRoleGrantOp TeamRoleOp = iota // give it, for the window TeamRoleWindowOp // replace the window of a held grant TeamRoleRevokeOp // take it away )
The operations on a team role grant.
type TeamRoleWindow ¶ added in v0.8.3
TeamRoleWindow is the period a team role grant counts in; a zero end is open.
func (TeamRoleWindow) Valid ¶ added in v0.8.3
func (w TeamRoleWindow) Valid() error
Valid checks the window: it ends after it starts.
type TemplateInvalidError ¶ added in v0.8.3
type TemplateInvalidError struct{ Problems []email.OverrideProblem }
TemplateInvalidError is a template that doesn't pass the checks, with each problem.
func (*TemplateInvalidError) Error ¶ added in v0.8.3
func (e *TemplateInvalidError) Error() string
type ThrottledError ¶
ThrottledError means the caller must wait before trying again.
func (*ThrottledError) Error ¶
func (e *ThrottledError) Error() string
type User ¶
type User struct {
ID string
Email string // normalized: trimmed, lowercased
EmailVerified bool
// PendingEmail is an address the user asked to change to and hasn't
// confirmed yet; PreviousEmail is the one before the last change, kept
// so the old address can be told and can undo it.
PendingEmail string
PreviousEmail string
// ErasedAt is when an administrator erased the user: what is left is a
// tombstone, the id with an anonymized email and no way to sign in.
ErasedAt time.Time
Roles []string
Disabled bool
// Locale is the user's language: one the realm lists (see
// RealmSettings.Languages). Empty for users from before languages existed;
// those use the realm's default.
Locale string
// AdminNetworks restrict the user's admin API requests; LoginNetworks
// their login and every request with their session. Empty: no
// restriction beyond the realm's.
AdminNetworks registry.Networks
LoginNetworks registry.Networks
// Consents is the version of each consent the user has accepted and not
// withdrawn: the summary of their consent records, for rules and sign-in.
Consents map[string]string
// PasswordExpiredAt, when set, expires the user's password if it was set before it
// (design/breach-response.md §3); a new password makes the account usable again.
PasswordExpiredAt time.Time
// PasswordNotifiedAt is when the user was last sent the email that tells them to choose a
// new password; a notification run skips whoever was told after the epoch.
PasswordNotifiedAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
User is a realm user. It holds only identity data; profiles belong in application collections.
type UserExport ¶ added in v0.9.2
type UserExport struct {
ID string
UserID string
Status string
JobID string
// Admin is the administrator who asked for it ("" when the user asked for their own).
Admin string
// Ticket is the reference an administrator gave (a support ticket, a request number).
Ticket string
// Notify says the user was told an administrator made it (data-export-made). Silent is the
// opposite, with the Reason given for it; both are in the audit record too.
Notify bool
Silent bool
Reason string
// Locale is the language of the README and of the emails about it.
Locale string
CreatedAt time.Time
StartedAt time.Time
FinishedAt time.Time
// ExpiresAt is when the stored package is deleted; zero until it is ready.
ExpiresAt time.Time
// Key is where the package is stored (the realm's file storage); Size its bytes.
Key string
Size int64
// Counts is what the package holds: documents per collection part, files, and records of the
// system data, for the user to see before they download.
Counts map[string]int64
// Error is why it failed, for the administrator; the user is told it did not work.
Error string
// Downloads counts the links given out.
Downloads int
}
UserExport is one export of a user's personal data.
func (UserExport) ByAdmin ¶ added in v0.9.2
func (e UserExport) ByAdmin() bool
ByAdmin says an administrator asked for it.
type UserUpdate ¶
type UserUpdate struct {
// Email changes the address (ErrEmailTaken when another user has it).
Email *string
PendingEmail *string // set; an empty string clears it
PreviousEmail *string // set; an empty string clears it
EmailVerified *bool
Disabled *bool
Locale *string
AdminNetworks *registry.Networks // set (empty clears)
LoginNetworks *registry.Networks // set (empty clears)
// PasswordExpiredAt expires the user's password as of that time.
PasswordExpiredAt *time.Time
// PasswordNotifiedAt records that the user was told to choose a new password.
PasswordNotifiedAt *time.Time
}
UserUpdate changes the set fields of a user.
type UserUsage ¶ added in v0.8.0
type UserUsage struct {
UserID string
StorageUsageTotals
}
UserUsage is what the files of the documents a user owns add up to.
type Users ¶
type Users struct {
Store Store
Hasher *Hasher
Settings registry.RealmSettings
Now func() time.Time // defaults to time.Now
Realm string // the realm's name, for logs
Log *slog.Logger // audit records are also logged here; nil: not logged
// Cipher encrypts and decrypts secrets (roadmap F5); nil when
// BACKD_SECRETS_KEY isn't configured, in which case every secret
// resolves as missing. Cache holds decrypted values briefly, shared
// across every realm's Users (NewSecretCache); nil disables caching.
Cipher *SecretCipher
// KeyUses names where a field key is used (collection fields, for the key's listing and for
// refusing to delete it); nil when the server wires none.
KeyUses func(name string) []string
Cache *SecretCache
// Metrics counts sessions and limits; nil turns it off.
Metrics *metrics.Metrics
// Dev is BACKD_DEV: an organization may connect an OpenID Connect server on this machine.
Dev bool
// DNS reads the TXT records that prove a domain; nil: the host's resolver, or the realm's
// organizations.domains.resolvers. Tests give a fake.
DNS DomainResolver
// contains filtered or unexported fields
}
Users manages the users of one realm.
func (*Users) AbandonedUploads ¶ added in v0.8.0
AbandonedUploads returns uploads left writing, stored or attaching for longer than the grace period, and pending uploads nobody used before they expired.
func (*Users) AcceptConsents ¶ added in v0.8.2
func (s *Users) AcceptConsents(ctx context.Context, challenge string, given map[string]string, from ConsentContext) (Verified, error)
AcceptConsents trades a consent challenge and the consents accepted (name to version) for the session the sign-in was waiting for. Every consent the challenge named must be accepted at its current version; optional consents may come with them. A challenge that isn't satisfied stays valid, so the person can try again.
func (*Users) AcceptConsentsOf ¶ added in v0.8.2
func (s *Users) AcceptConsentsOf(ctx context.Context, u User, given map[string]string, from ConsentContext) (User, error)
AcceptConsentsOf records consents a signed-in user gives (method api): an app showing the prompt after a version changed, or a user opting in to an optional consent.
func (*Users) AcceptInvitation ¶ added in v0.4.0
func (s *Users) AcceptInvitation(ctx context.Context, token, password, locale string) (EmailToken, error)
AcceptInvitation uses the link of an emailed invitation: it creates the account with the chosen password and the invited address, already verified (only its owner received the link). It starts no session. The password is checked first, so a refused one leaves the link usable. Every way the link can be wrong, or the address being registered meanwhile, is ErrInvalidToken.
func (*Users) AcceptOrgInvitation ¶ added in v0.8.3
func (s *Users) AcceptOrgInvitation(ctx context.Context, p Principal, token string) (Membership, error)
AcceptOrgInvitation uses the token: the user becomes a member, or gains the roles and teams of the invitation. It returns the membership.
func (*Users) AccountExport ¶ added in v0.9.2
AccountExport gathers the system data the realm holds about a user for their personal data export (design/compliance.md §3.3): the account, the ways they sign in, sessions, push devices, the second factor, organizations, invitations addressed to them, consent history, the audit records where they are the actor or the subject, and the functions they called.
It never returns credentials: password hashes, provider tokens, session and device tokens, second factor secrets and recovery codes, and invitation tokens stay out. Records that mention other people carry only the ids; nothing of theirs is copied.
func (*Users) AddOrgTeamMember ¶ added in v0.8.3
func (s *Users) AddOrgTeamMember(ctx context.Context, userID, orgID, id, target string) (MemberView, error)
AddOrgTeamMember puts a member of the organization in a team; they gain its roles.
func (*Users) AdminAddMember ¶ added in v0.8.3
func (s *Users) AdminAddMember(ctx context.Context, orgID, userID string, roles []string) (MemberView, error)
AdminAddMember adds a member directly, as an administrator (no invitation, audited).
func (*Users) AdminAssignOwner ¶ added in v0.8.3
AdminAssignOwner gives a user the creator roles of an organization, for one left without a manager.
func (*Users) AdminCreateOrg ¶ added in v0.8.3
AdminCreateOrg creates an organization for a user, who holds the creator roles.
func (*Users) AdminCreateOrgInvitation ¶ added in v0.8.3
func (s *Users) AdminCreateOrgInvitation(ctx context.Context, orgID string, in InvitationInput) (InvitationResult, error)
AdminCreateOrgInvitation is CreateOrgInvitation for an administrator, who may give any role.
func (*Users) AdminCreateOrgTeam ¶ added in v0.8.3
func (s *Users) AdminCreateOrgTeam(ctx context.Context, orgID, name string, roles []string) (OrgTeam, error)
AdminCreateOrgTeam is CreateOrgTeam for an administrator.
func (*Users) AdminDeleteOrg ¶ added in v0.8.3
AdminDeleteOrg ends an organization as a realm administrator.
func (*Users) AdminDeleteOrgConnection ¶ added in v0.9.3
AdminDeleteOrgConnection is DeleteOrgConnection for a realm administrator.
func (*Users) AdminDeleteOrgTeam ¶ added in v0.8.3
AdminDeleteOrgTeam is DeleteOrgTeam for an administrator.
func (*Users) AdminMembers ¶ added in v0.8.3
func (s *Users) AdminMembers(ctx context.Context, orgID, after string, limit int) ([]MemberView, bool, error)
AdminMembers lists an organization's members, with emails.
func (*Users) AdminNewOrgInvitationLink ¶ added in v0.8.3
func (s *Users) AdminNewOrgInvitationLink(ctx context.Context, orgID, id string) (InvitationResult, error)
AdminNewOrgInvitationLink is NewOrgInvitationLink for an administrator.
func (*Users) AdminOrg ¶ added in v0.8.3
AdminOrg returns an organization with its status, whatever it is.
func (*Users) AdminOrgConnection ¶ added in v0.9.3
func (s *Users) AdminOrgConnection(ctx context.Context, orgID, provider string) (ConnectionView, error)
AdminOrgConnection is OrgConnection for a realm administrator.
func (*Users) AdminOrgConnections ¶ added in v0.9.3
AdminOrgConnections lists an organization's connections for a realm administrator.
func (*Users) AdminOrgInvitations ¶ added in v0.8.3
AdminOrgInvitations lists an organization's invitations.
func (*Users) AdminOrgSummaries ¶ added in v0.8.3
AdminOrgSummaries lists organizations of a status (any when empty) whose name or slug contains q, with their member counts.
func (*Users) AdminOrgTeams ¶ added in v0.8.3
AdminOrgTeams lists an organization's teams.
func (*Users) AdminOrgs ¶ added in v0.8.3
AdminOrgs lists organizations, optionally of one status, newest first.
func (*Users) AdminReactivateOrg ¶ added in v0.8.3
AdminReactivateOrg brings a deleted organization back, with no members: an owner is assigned next. Documents kept under `keep` are visible to members again; those under `delete` are gone. slug, when not empty, is the slug the organization takes (its former one may be in use).
func (*Users) AdminRemoveMember ¶ added in v0.8.3
AdminRemoveMember removes a member as an administrator.
func (*Users) AdminRemovePasskey ¶ added in v0.9.10
AdminRemovePasskey removes a passkey of any user (a lost device the user cannot remove themselves).
func (*Users) AdminResendOrgInvitation ¶ added in v0.8.3
func (s *Users) AdminResendOrgInvitation(ctx context.Context, orgID, id, locale, ip, requestID string) error
AdminResendOrgInvitation is ResendOrgInvitation for an administrator.
func (*Users) AdminRevokeOrgInvitation ¶ added in v0.8.3
AdminRevokeOrgInvitation is RevokeOrgInvitation for an administrator.
func (*Users) AdminSetClaims ¶ added in v0.8.3
func (s *Users) AdminSetClaims(ctx context.Context, orgID string, claims map[string]any) (Org, error)
AdminSetClaims replaces an organization's claims.
func (*Users) AdminSetMemberRoles ¶ added in v0.8.3
func (s *Users) AdminSetMemberRoles(ctx context.Context, orgID, target string, roles []string) (MemberView, error)
AdminSetMemberRoles is UpdateMember for an administrator.
func (*Users) AdminSetOrgConnection ¶ added in v0.9.3
func (s *Users) AdminSetOrgConnection(ctx context.Context, orgID, provider string, in ConnectionInput) (ConnectionView, error)
AdminSetOrgConnection is SetOrgConnection for a realm administrator, who may give any role.
func (*Users) AdminSetOrgSSORequired ¶ added in v0.9.3
func (s *Users) AdminSetOrgSSORequired(ctx context.Context, orgID string, on bool) (SSORequiredResult, error)
AdminSetOrgSSORequired is the administrators' way: they can turn it off whatever the state of the connections (the break glass for an organization that can't reach its provider), and on only when the organization has a working connection.
func (*Users) AdminSetOrgSlug ¶ added in v0.9.3
AdminSetOrgSlug gives an organization its slug (or changes it): how the realm's older organizations, made before slugs were required, get one.
func (*Users) AdminSetOrgTeamMember ¶ added in v0.8.3
func (s *Users) AdminSetOrgTeamMember(ctx context.Context, orgID, id, target string, add bool) (MemberView, error)
AdminSetOrgTeamMember adds or removes a member of a team as an administrator.
func (*Users) AdminTeamMembers ¶ added in v0.8.3
func (s *Users) AdminTeamMembers(ctx context.Context, orgID, teamID, role, after string, limit int) ([]TeamMemberView, bool, error)
AdminTeamMembers is TeamMembers for an administrator.
func (*Users) AdminUpdateOrgTeam ¶ added in v0.8.3
func (s *Users) AdminUpdateOrgTeam(ctx context.Context, orgID, id string, name *string, roles []string, setRoles bool) (OrgTeam, error)
AdminUpdateOrgTeam is UpdateOrgTeam for an administrator.
func (*Users) AfterOrgSignIn ¶ added in v0.9.3
func (s *Users) AfterOrgSignIn(ctx context.Context, orgID, provider string, res ProviderResult) (joined bool)
AfterOrgSignIn is what a successful sign-in through an organization's connection does to the membership (design/sso.md §8). The person joins with the connection's join roles only when this sign-in made the identity (a new person, or an explicit link): someone who is already a member stays as they are, and someone a manager removed stays out until invited again. A failure to join never fails the sign-in: the person is signed in and not joined.
func (*Users) AllowRealPreview ¶ added in v0.8.3
AllowRealPreview counts a preview with real data against the organization's hourly limit.
func (*Users) AllowsIssuer ¶ added in v0.9.13
AllowsIssuer says whether an organization may connect an OpenID Connect server with this issuer.
func (*Users) ApplyRoleSeeds ¶
ApplyRoleSeeds adds the roles realm.yaml assigns to existing users. It never removes roles. Users who don't exist yet get theirs when created. It returns how many users were updated.
func (*Users) Audit ¶
Audit appends a record to the realm's audit trail and writes it to the log. A record that can't be stored is logged as an error; the action it describes has already happened, so it isn't undone.
func (*Users) AuditAs ¶
AuditAs is Audit with an explicit actor (when not empty), for events whose actor isn't the caller yet, such as a login.
func (*Users) AuditTrail ¶
func (s *Users) AuditTrail(ctx context.Context, f AuditFilter) ([]AuditRecord, bool, error)
AuditTrail returns records matching f, newest first, and whether more follow.
func (*Users) Authenticate ¶
Authenticate resolves a session token to its user. It extends the session's idle timeout, writing at most once per minute.
func (*Users) AuthenticateIgnoringConsents ¶ added in v0.8.2
AuthenticateIgnoringConsents is Authenticate without the consent deadline: for the few routes a person needs to accept what is missing, or to leave (see consents_signin.go).
func (*Users) AuthenticateKey ¶
AuthenticateKey resolves an API key. It records the use at most once a minute.
func (*Users) BeginEnrollment ¶ added in v0.8.2
BeginEnrollment starts the TOTP setup of a user whose sign-in is waiting for one (their role requires MFA): the same secret and QR as BeginTOTPSetup, asked for with the challenge the first factor gave instead of a session.
func (*Users) BeginPasskeyEnrollment ¶ added in v0.9.10
BeginPasskeyEnrollment gives the options for adding the passkey a sign-in is waiting for, to a person who has none (the enroll challenge of a strategy with a passkey step).
func (*Users) BeginPasskeyReauth ¶ added in v0.9.10
BeginPasskeyReauth gives the options for proving who the signed-in user is with a passkey.
func (*Users) BeginPasskeyRegistration ¶ added in v0.9.10
func (s *Users) BeginPasskeyRegistration(ctx context.Context, u User) (options []byte, ceremony string, err error)
BeginPasskeyRegistration starts adding a passkey for the user. The caller has checked that the session may (reauth, not through a connection). It returns the options for the browser and the id of the ceremony to send back.
func (*Users) BeginPasskeySignIn ¶ added in v0.9.10
func (s *Users) BeginPasskeySignIn(ctx context.Context, strategy, org, ip string) (PasskeyOptions, error)
BeginPasskeySignIn starts a sign-in with a passkey as the first method of a strategy. org is the organization route it was asked on ("" for the realm's own door). It needs no user and answers the same whether or not anyone has a passkey.
func (*Users) BeginPasskeyStep ¶ added in v0.9.10
BeginPasskeyStep gives the options for the passkey a sign-in challenge waits for (a later step of the strategy): only this user's passkeys are allowed, since the first step already said who they are.
func (*Users) BeginTOTPSetup ¶ added in v0.8.2
BeginTOTPSetup makes a TOTP secret for the user, held for 15 minutes until a first code from the app proves it was received. A new setup replaces any pending one.
func (*Users) CallbackCaller ¶
CallbackCaller resolves a verified token into the caller it acts as, checking the user and key still exist and may act: a user disabled or a key revoked during the invocation loses access at once.
func (*Users) CanEditTemplate ¶ added in v0.8.3
CanEditTemplate checks that the caller may edit the organization's template of a kind in a language: the capability email.overrides.permission names, a customizable kind, a language of the realm.
func (*Users) CancelJob ¶ added in v0.8.0
CancelJob ends a queued or running function job: it is done, with the result "cancelled", at once. A worker running it notices and stops the run (what the function already did stays done). ErrJobFinished if it ended first, ErrNotFound if there is no such job.
func (*Users) ChangeEmailAsAdmin ¶ added in v0.4.0
ChangeEmailAsAdmin changes a user's address at once, as an administrator vouching for it: the new address counts as verified, every session of the user ends, the old address gets the message with the link to undo it and the new one is told. It needs the realm to send email (the notifications).
func (*Users) ChangePassword ¶
ChangePassword replaces the caller's password and ends all of their other sessions. The caller has checked that the user proved who they are just now (CheckReauth).
func (*Users) CheckConnectionAuthority ¶ added in v0.9.3
func (s *Users) CheckConnectionAuthority(ctx context.Context, c OrgConnection) error
CheckConnectionAuthority makes sure the roles a connection gives on joining are still within reach of whoever set it: a manager who lost a role doesn't leave a powerful default behind. A connection whose last setter could no longer give those roles by the granting rules is disabled (audited) and ErrConnectionUnusable is returned. A connection with no join roles, and connections set by a realm administrator, are always fine.
func (*Users) CheckOrgDomains ¶ added in v0.9.13
CheckOrgDomains runs the checks that are due: the re-check of verified and lapsed domains, and the growing-interval checks of claims not proved yet. It is bounded to limit claims a call (the worker calls it every minute) and returns how many it checked.
func (*Users) CheckReauth ¶ added in v0.8.2
CheckReauth says whether token is a re-authentication of this session (ErrReauthRequired otherwise). A user who gives no proof (ReauthMethodsOf is empty) always passes.
func (*Users) CheckReport ¶ added in v0.8.0
CheckReport returns one collection's latest report; ErrNotFound if it was never checked.
func (*Users) CheckReports ¶ added in v0.8.0
CheckReports returns the latest report of every collection checked, sorted by database and collection. With documents false the lists of invalid documents are left out.
func (*Users) ChooseStrategy ¶ added in v0.9.10
ChooseStrategy resolves the strategy of a first-step call before anything about the person is looked at: first is the method of the call (password, magic_link or a provider's name).
func (*Users) ClaimDirectUpload ¶ added in v0.8.0
ClaimDirectUpload takes a direct upload to verify and complete it, once: held as attaching until it is done or released. ErrNotFound when the token doesn't match, the upload isn't one that waits for its bytes, or it expired.
func (*Users) ClaimFileDeletions ¶ added in v0.8.0
ClaimFileDeletions returns up to limit deletions that are due, holding them for FileDeletionLease so no other worker takes them meanwhile.
func (*Users) ClaimIdempotency ¶
func (s *Users) ClaimIdempotency(ctx context.Context, rec IdempotencyRecord) (IdempotencyRecord, bool, error)
ClaimIdempotency atomically claims a key for a new call, or returns the existing record (running or done) if one already exists.
func (*Users) ClaimJob ¶
ClaimJob atomically claims the oldest claimable job: never claimed, or whose lease has expired (a dead worker's jobs are picked up again), leasing it to workerID for the function's own timeout plus a margin.
func (*Users) ClaimOrgDomain ¶ added in v0.9.13
func (s *Users) ClaimOrgDomain(ctx context.Context, userID, orgID, domain string) (DomainView, error)
ClaimOrgDomain starts a claim: it issues the challenge to publish.
func (*Users) ClaimPendingUpload ¶ added in v0.8.0
func (s *Users) ClaimPendingUpload(ctx context.Context, id, token, documentID string) (FileJournalEntry, error)
ClaimPendingUpload takes a completed, unexpired pending upload whose token matches, once: it is held as attaching to the document until it is attached or released. ErrNotFound when there is none to take.
func (*Users) Clock ¶ added in v0.4.0
Clock is the service's current time (its Now, or the real one).
func (*Users) CompleteEnrollment ¶ added in v0.8.2
func (s *Users) CompleteEnrollment(ctx context.Context, challenge, setupID, code string) (Verified, []string, error)
CompleteEnrollment confirms the TOTP setup of a waiting sign-in with its first code, and finishes the sign-in: the outcome is the session the first factor was waiting for, with the second one recorded, and the recovery codes, shown once. Five wrong codes end the challenge.
func (*Users) CompleteIdempotency ¶
func (s *Users) CompleteIdempotency(ctx context.Context, id string, result *JobResult, jobID string) error
CompleteIdempotency stores a claimed key's outcome.
func (*Users) CompleteJob ¶
CompleteJob records a job's result and starts its retention countdown.
func (*Users) CompletePasskeyEnrollment ¶ added in v0.9.10
func (s *Users) CompletePasskeyEnrollment(ctx context.Context, challenge string, credential []byte, name string) (Verified, error)
CompletePasskeyEnrollment stores the passkey and ends the sign-in that waited for it: the answer is the session (or the next step), and a passkey step makes no recovery codes. Five wrong answers end the challenge.
func (*Users) CompletePendingUpload ¶ added in v0.8.0
func (s *Users) CompletePendingUpload(ctx context.Context, id, name, contentType, sha256sum string, size int64, uploadedAt time.Time, image string) error
CompletePendingUpload records what was stored: the upload is now ready to be attached.
func (*Users) ConfirmEmailChange ¶ added in v0.4.0
ConfirmEmailChange uses the link sent to the new address: the address changes (and counts as verified: the owner just read that mailbox), every session of the user ends, and the old address is told, with a link to undo it. Every way the token can be wrong, or the address having been taken meanwhile, is ErrInvalidToken.
func (*Users) ConfirmTOTP ¶ added in v0.8.2
func (s *Users) ConfirmTOTP(ctx context.Context, u User, keepSession, setupID, code string) ([]string, error)
ConfirmTOTP turns TOTP on for the user with the first code of the setup, and returns the recovery codes: shown once, kept only as keyed hashes. Every other session of the user ends, so a session from before can't pass a rule that asks for MFA; keepSession is the one that stays ("" for none). A wrong code is an *InvalidCodeError; five end the setup.
func (*Users) ConsentHistory ¶ added in v0.8.2
ConsentHistory returns the user's consent records, oldest first.
func (*Users) ConsentPseudonym ¶ added in v0.8.2
ConsentPseudonym is HMAC-SHA-256 over the normalized address under the realm's key: it lets a later dispute from that address be matched to the records without keeping the address. "" when the realm has no secrets key (nothing can be keyed).
func (*Users) Create ¶
Create adds a user, as an administrator, with the address already verified. With password nil the user has no password identity and can't sign in with a password until one is set.
func (*Users) CreateAPIKey ¶
func (s *Users) CreateAPIKey(ctx context.Context, name string, opts KeyOptions) (APIKey, string, error)
CreateAPIKey creates a key named name with opts. The key itself is returned only here.
func (*Users) CreateInvitation ¶
func (s *Users) CreateInvitation(ctx context.Context, email string, ttl time.Duration, createdBy string) (Invitation, string, error)
CreateInvitation creates an invitation valid for ttl (0: the default), optionally bound to email. The token is returned only here.
func (*Users) CreateKey ¶ added in v0.9.1
CreateKey stores a new realm-scope field key: a generated one (value empty), or the 32 bytes given in base64url. A name already taken, by a key or by any secret, is refused. The value of a generated key is returned here and nowhere else.
func (*Users) CreateOrg ¶ added in v0.8.3
CreateOrg creates an organization with the caller as a member holding the creator roles.
func (*Users) CreateOrgInvitation ¶ added in v0.8.3
func (s *Users) CreateOrgInvitation(ctx context.Context, userID, orgID string, in InvitationInput) (InvitationResult, error)
CreateOrgInvitation invites to an organization; it needs manage: members, and gives only what the caller may give.
func (*Users) CreateOrgTeam ¶ added in v0.8.3
func (s *Users) CreateOrgTeam(ctx context.Context, userID, orgID, name string, roles []string) (OrgTeam, error)
CreateOrgTeam makes a team. It needs manage: teams, and gives only roles the caller may.
func (*Users) CreateResetLink ¶ added in v0.9.1
func (s *Users) CreateResetLink(ctx context.Context, userID, redirectTo string) (token string, expires time.Time, err error)
CreateResetLink makes a one-time password reset token for the user, to be handed to them out of band when their mailbox can't be reached (design/breach-response.md §5). It is the token a reset email carries: using it sets the password, ends the user's sessions and sends password-changed. Nothing is sent. The token is returned once; the audit record names the administrator and the user, never the token. redirectTo must already be checked against the realm's allowed redirects.
func (*Users) CustomizableKinds ¶ added in v0.8.3
CustomizableKinds are the kinds the realm lets companies customize, with the placeholders each needs.
func (*Users) DeactivateAccount ¶ added in v0.4.0
DeactivateAccount handles a user deleting their own account: it is disabled and its sessions end. The caller has checked that the user proved who they are just now (CheckReauth). Nothing is erased: that is an administrator's action (Erase).
func (*Users) Delete ¶
Delete removes the user, their identities and sessions. Documents they own are kept.
func (*Users) DeleteKey ¶ added in v0.9.1
DeleteKey removes a key that nothing uses; ErrSecretNotFound if there is no such key.
func (*Users) DeleteOrg ¶ added in v0.8.3
DeleteOrg ends an organization for the caller, who needs manage: org (the HTTP layer asks for a fresh proof of identity before). Access ends at once; a job then applies the collections' policies to its documents.
func (*Users) DeleteOrgConnection ¶ added in v0.9.3
DeleteOrgConnection removes a connection and its client secret for a member who holds manage: sso (the HTTP layer asks for a fresh proof first).
func (*Users) DeleteOrgSecret ¶ added in v0.9.3
DeleteOrgSecret removes an organization's secret; ErrSecretNotFound if none.
func (*Users) DeleteOrgTeam ¶ added in v0.8.3
DeleteOrgTeam removes a team from the organization and from every membership; the roles it carried go with it, and the organization keeps a manager.
func (*Users) DeleteOrgTemplate ¶ added in v0.8.3
DeleteOrgTemplate returns a kind in a language to the realm's own file.
func (*Users) DeleteSecret ¶
DeleteSecret removes the value at scope and name; ErrSecretNotFound if none. Functions that declare it start answering secret_missing again.
func (*Users) Devices ¶ added in v0.8.2
Devices lists a user's devices, most recently seen first, without tokens' meaning to the caller (the sealed value is in each one: the HTTP layer never returns it).
func (*Users) DisableMFA ¶ added in v0.8.2
DisableMFA removes the user's second factor and recovery codes; refused while a role of the user requires one.
func (*Users) DiscoverOrgs ¶ added in v0.9.13
DiscoverOrgs answers "which organization is this address?" (design/sso.md §10.5): the one whose verified, discoverable domain it is on, if that organization has a connection people can use. Every other case (an unknown address, a domain nobody proved, one that does not let itself be found, an organization with no working connection) answers the same: nothing, and the same reads are made, so neither the answer nor its time says which. The person is never told whether an account exists.
func (*Users) EnqueueCompletionJob ¶ added in v0.8.0
func (s *Users) EnqueueCompletionJob(ctx context.Context, finished Job, target string, timeoutMS int64, input json.RawMessage) (Job, bool, error)
EnqueueCompletionJob queues the notification of a job's end (on_complete): a job of function target in the same database, with input as its input, run with no caller (it has whatever its own function.yaml gives it). Its id comes from the finished job, so a second attempt to queue it for the same job does nothing; it returns false then. timeoutMS is the target's timeout.
func (*Users) EnqueueImageJob ¶ added in v0.8.1
func (s *Users) EnqueueImageJob(ctx context.Context, database string, e ImageJob, requestID string) error
EnqueueImageJob queues the making of a file's pending versions. A file has at most one such job at a time: asking again while one is queued or running is not an error.
func (*Users) EnqueueImageOp ¶ added in v0.8.1
func (s *Users) EnqueueImageOp(ctx context.Context, database string, e ImageJob, requestID string) (Job, error)
EnqueueImageOp queues the making of one version for a function that waits for it. It returns ErrJobExclusive while another job of the file is queued or running: the caller waits and asks again.
func (*Users) EnqueueJob ¶
EnqueueJob stores a new job, queued for a worker to claim, and returns it with its id and timestamps filled in.
func (*Users) EnqueueJobID ¶ added in v0.8.2
EnqueueJobID is EnqueueJob for a job that has its id already: a job with that id existing is not an error (created is false), so work that runs again doesn't make it twice.
func (*Users) EnqueueJobs ¶ added in v0.8.5
EnqueueJobs stores jobs that carry an id of their own — derived from what they are for, so that the same work queued twice is one job — and returns how many were new. The rest are replays and are skipped.
func (*Users) EnqueueKeyedJob ¶ added in v0.8.5
EnqueueKeyedJob stores a job whose id says what it is for (j.ID must be set): queuing the same work twice is one job, and the second call is not an error. It returns whether the job is new.
func (*Users) EnqueueScheduledJob ¶
func (s *Users) EnqueueScheduledJob(ctx context.Context, j Job, scheduledAt time.Time, skipOverlap bool) (Job, bool, error)
EnqueueScheduledJob enqueues the run of a scheduled function for scheduledAt, under an id derived from the function and that time, so however many workers try, exactly one job is created (roadmap F18). It returns the job, and false when the run already exists.
With skipOverlap, a function that still has an unfinished job (queued, waiting for a retry, or running) doesn't get a new run: the scheduled time is recorded as a job that is done at once with the result "skipped", so the job list shows it and no worker claims it.
func (*Users) EnterOrg ¶ added in v0.9.3
EnterOrg is what a sign-in through a provider does about the organization it is for, after the person is known: the invitation it carried (known by its hash) is used when it is theirs and for this organization, and the answer says whether the person is a member now. A failing invitation never fails the sign-in; it just does not join anyone.
func (*Users) Erase ¶ added in v0.4.0
Erase starts erasing a user, as an administrator: it queues the erase job (which holds the id and the email the policies match by), then turns the user into a tombstone and deletes their email tokens and email jobs at once. A worker applies the collections' policies. Repeating it for a user whose erase job failed queues that job again; for one whose job is still going it returns the job; otherwise it is ErrAlreadyErased.
func (*Users) EraseJobFor ¶ added in v0.4.0
EraseJobFor returns the latest erase job of a user.
func (*Users) ExpireAllPasswords ¶ added in v0.9.1
func (s *Users) ExpireAllPasswords(ctx context.Context, reason string, keepSessions bool) (ExpireResult, error)
ExpireAllPasswords moves the realm's password epoch to now: every password set before it stops opening its account, and a restore of older system data doesn't bring them back. Sessions end too, unless keepSessions (a planned rotation rather than a leak). The epoch only moves forward. The reason goes to the audit trail.
func (*Users) ExpirePassword ¶ added in v0.9.1
ExpirePassword expires one user's password: it stops opening the account until the user resets it or an administrator sets a new one. Sessions are left alone.
func (*Users) ExportAuthDocs ¶ added in v0.9.1
func (s *Users) ExportAuthDocs(ctx context.Context, collection, afterID string, limit int, ek *SecretCipher, anon *AuthAnonymize) (out []map[string]any, unavailable int, last string, read int, err error)
ExportAuthDocs reads a page of a portable collection for an export package. Fields sealed with the realm's cipher are opened and sealed again under ek, the export key; a value that can't be opened (no cipher here, or sealed under another key) is left out and counted in unavailable. last is the id of the last document read and read how many there were, whatever was left out, so the next page can continue after it. Fields in PortableReset are emptied.
func (*Users) FileAdded ¶ added in v0.8.0
FileAdded counts a file a document now references, for the realm and, when the document has an owner, for them.
func (*Users) FileDeletionStats ¶ added in v0.8.0
func (s *Users) FileDeletionStats(ctx context.Context) (FileDeletionStats, error)
FileDeletionStats describes what waits to be deleted.
func (*Users) FileRemoved ¶ added in v0.8.0
FileRemoved counts a file no document references any more.
func (*Users) FindOrgs ¶ added in v0.9.3
FindOrgs queues the email that tells the owner of an address which organizations it belongs to, with a link to each one's sign-in page. It answers nothing about the address: one with no account, one without memberships and one that is sent the email all do the same work and end the same way. It needs the realm's organizations.signin_link and email.
func (*Users) FinishFileDeletion ¶ added in v0.8.0
FinishFileDeletion removes a deletion that was carried out.
func (*Users) FinishPasskeyRegistration ¶ added in v0.9.10
func (s *Users) FinishPasskeyRegistration(ctx context.Context, u User, ceremony string, credential []byte, name string) (PasskeyInfo, error)
FinishPasskeyRegistration checks the browser's answer and stores the passkey under name. It does not end other sessions and changes nothing about how the user signs in otherwise; it makes no recovery codes. The user is told by email, and it is audited.
func (*Users) Identify ¶
Identify resolves a bearer credential (a session token or an API key) to its caller. An empty credential is the anonymous caller.
func (*Users) Identities ¶ added in v0.8.2
Identities returns the user's sign-in methods, oldest first.
func (*Users) IdentityDormant ¶ added in v0.9.13
IdentityDormant says whether an identity belongs to an issuer its provider no longer has: the operator or a manager changed the provider's issuer (or an organization its tenant), so it matches no sign-in. A provider that is not configured any more leaves its identities orphaned, which is another thing.
func (*Users) ImageDeclarations ¶ added in v0.8.1
ImageDeclarations returns the fingerprints recorded for the declared image versions.
func (*Users) ImportAuthDocs ¶ added in v0.9.1
func (s *Users) ImportAuthDocs(ctx context.Context, collection string, docs []map[string]any, mode string, write bool) ([]PortableResult, error)
ImportAuthDocs validates (write false) or writes documents of a portable collection. Sealed fields arrive as {"$plain": value} and are sealed under this realm's cipher; a document holding one when this realm has no cipher is invalid.
func (*Users) InvitationByID ¶ added in v0.4.0
InvitationByID returns an unexpired invitation by id.
func (*Users) Invitations ¶
func (s *Users) Invitations(ctx context.Context) ([]Invitation, error)
Invitations lists the realm's unexpired invitations, newest first.
func (*Users) Invocations ¶
func (s *Users) Invocations(ctx context.Context, f InvocationFilter) ([]InvocationRecord, bool, error)
Invocations returns invocation records matching f, newest first, and whether more follow.
func (*Users) IssueLoginCode ¶ added in v0.8.2
func (s *Users) IssueLoginCode(ctx context.Context, userID, method, challenge string, newUser bool, profile map[string]string) (string, error)
IssueLoginCode makes the one-time code that lets the app, holding the PKCE verifier of challenge, get a session for the user; method is the first factor that proved them.
func (*Users) IssueLoginCodeFor ¶ added in v0.9.10
func (s *Users) IssueLoginCodeFor(ctx context.Context, userID, method, strategy, challenge string, newUser bool, profile map[string]string, org string) (string, error)
IssueLoginCodeFor is IssueLoginCodeIn for a sign-in that follows the named strategy.
func (*Users) IssueLoginCodeIn ¶ added in v0.9.3
func (s *Users) IssueLoginCodeIn(ctx context.Context, userID, method, challenge string, newUser bool, profile map[string]string, org string) (string, error)
IssueLoginCodeIn is IssueLoginCode for a person an organization's connection signed in: the session the code becomes records the organization.
func (*Users) JournalDirectUpload ¶ added in v0.8.0
func (s *Users) JournalDirectUpload(ctx context.Context, e FileJournalEntry, ttl time.Duration) error
JournalDirectUpload records a direct upload that is starting: the client will send the bytes to the bucket and complete it before it expires after ttl. A pending one (e.Pending) is attached later by a write; the others belong to a document.
func (*Users) JournalPendingUpload ¶ added in v0.8.0
func (s *Users) JournalPendingUpload(ctx context.Context, e FileJournalEntry, ttl time.Duration) error
JournalPendingUpload records a pending upload that is starting; unused, it expires after ttl.
func (*Users) JournalUpload ¶ added in v0.8.0
func (s *Users) JournalUpload(ctx context.Context, e FileJournalEntry) error
JournalUpload records an upload that is starting.
func (*Users) KeyCreatedBySession ¶ added in v0.8.2
KeyCreatedBySession tells the signed-in administrator who made an API key that they did, by email: a key outlives the session, so a stolen session making one is noticed.
func (*Users) KeyMaterial ¶ added in v0.9.1
KeyMaterial returns a field key's value for the data keys it wraps; it implements fieldcrypt.Ring.Keys. The value is opened from the sealed store and never leaves the process.
func (*Users) KeyUsedBy ¶ added in v0.9.1
KeyUsedBy lists where a key is used, as "database/collection.path" entries.
func (*Users) LatestSchemaMigration ¶ added in v0.9.11
func (s *Users) LatestSchemaMigration(ctx context.Context, database, collection string) (Job, bool, error)
LatestSchemaMigration is the latest finished migration of the collection (dry runs included), or false when none is kept.
func (*Users) ListAPIKeys ¶
ListAPIKeys returns the realm's API keys, sorted by name.
func (*Users) ListOrgDomains ¶ added in v0.9.13
ListOrgDomains returns the organization's claims, sorted by domain.
func (*Users) ListPage ¶ added in v0.5.0
func (s *Users) ListPage(ctx context.Context, contains, after string, skip, limit int) ([]User, bool, error)
ListPage is List for one page, sorted by email; see Store.ListUsersPage.
func (*Users) ListPasskeys ¶ added in v0.9.10
ListPasskeys lists the user's passkeys, oldest first.
func (*Users) ListSecrets ¶
func (s *Users) ListSecrets(ctx context.Context) ([]SecretMeta, error)
ListSecrets returns every secret's metadata (never a value), sorted by database then name (realm-scope secrets, database "", first).
func (*Users) LocaleOf ¶ added in v0.4.0
LocaleOf is the language of a user: theirs, or the realm's default for users from before languages existed.
func (*Users) Login ¶
Login checks an email and password and starts a session. Every failure returns ErrInvalidCredentials after the same amount of hashing work, so neither the answer nor its timing reveals whether the email exists. Repeated failures for the email or from the client ip (may be empty) are throttled with a *ThrottledError.
func (*Users) MFAStatusOf ¶ added in v0.8.2
MFAStatusOf reports a user's second-factor state.
func (*Users) MagicLinkByToken ¶ added in v0.8.2
MagicLinkByToken finds the request a link token belongs to, without using it up: opening a link in a mail scanner must not spoil it.
func (*Users) MagicLinkDestination ¶ added in v0.8.2
func (s *Users) MagicLinkDestination(c AuthChallenge) string
MagicLinkDestination is where a request's link sends the browser: its redirect_to, else the realm's sign_in.app_url, else "" (then the code is the way).
func (*Users) MagicLinkEmailFor ¶ added in v0.8.2
func (s *Users) MagicLinkEmailFor(ctx context.Context, challengeID string) (AuthChallenge, string, error)
MagicLinkEmailFor is what the worker needs to write a request's email: the address it goes to and, for a request that has a user, who they are.
func (*Users) MakeMagicLinkSecrets ¶ added in v0.8.2
func (s *Users) MakeMagicLinkSecrets(ctx context.Context, challengeID string) (token, code string, expires time.Time, err error)
MakeMagicLinkSecrets makes the link token and the code of a request when its email is written, keeps their hashes only, and returns them with when they stop working. A retried job gets new ones, and the earlier pair stops working.
func (*Users) MakeReauthCode ¶ added in v0.8.2
MakeReauthCode is what the worker calls when it writes the email: it makes a fresh code, keeps its hash on the challenge and returns the code and when it stops working. A job that is tried again gets a new code, and the earlier one stops working.
func (*Users) MaxSessionExpiry ¶ added in v0.5.0
MaxSessionExpiry is the latest a session started at created can last for this user: the absolute limit, whatever the idle timeout slides to.
func (*Users) Members ¶ added in v0.8.3
func (s *Users) Members(ctx context.Context, userID, orgID, after string, limit int) ([]MemberView, bool, error)
Members lists an organization's members to a member, a page at a time sorted by user id.
func (*Users) MembersWithoutSSO ¶ added in v0.9.3
func (s *Users) MembersWithoutSSO(ctx context.Context, userID, orgID, after string, limit int) ([]MemberView, bool, error)
MembersWithoutSSO lists the members who have no identity on a connection of the organization: the people who can't come in once it requires its connection. It is Members with that filter, for the managers who can turn the requirement on (manage: org).
func (*Users) MembershipOf ¶ added in v0.8.3
MembershipOf returns the caller's membership of an organization, or ErrNotOrgMember for a non-member, an unknown organization and a deleted one alike.
func (*Users) MyOrgs ¶ added in v0.8.3
MyOrgs lists the organizations a user belongs to, with their effective roles. Deleted organizations aren't listed.
func (*Users) NetworksInConfig ¶
NetworksInConfig reports whether realm.yaml sets network restrictions for email; seeding would then overwrite changes made elsewhere.
func (*Users) NewEmailToken ¶ added in v0.4.0
func (s *Users) NewEmailToken(ctx context.Context, purpose, userID, redirectTo string, ttl time.Duration) (token string, expiresAt time.Time, err error)
NewEmailToken creates a token of 256 random bits for userID and purpose, valid for ttl, stores its hash, and returns the token itself. Whoever receives it must not store it.
func (*Users) NewEmailTokenFor ¶ added in v0.4.0
func (s *Users) NewEmailTokenFor(ctx context.Context, t EmailToken, ttl time.Duration) (token string, expiresAt time.Time, err error)
NewEmailTokenFor is NewEmailToken for a token that also carries an address or an invitation: t's Hash, CreatedAt and ExpiresAt are filled in.
func (*Users) NewOrgInvitationLink ¶ added in v0.8.3
func (s *Users) NewOrgInvitationLink(ctx context.Context, userID, orgID, id string) (InvitationResult, error)
NewOrgInvitationLink issues a new token for an invitation that is still pending and invalidates the old one: a lost link can't be shown again.
func (*Users) NextAccessChange ¶ added in v0.9.2
NextAccessChange is the next moment after now at which what the user's organization and team role grants give them changes by the clock alone: the earliest `from` or `until` of any of their grants that is still ahead. Zero when no grant has a boundary ahead. Nothing runs at that moment; a realtime stream that wants to show the change at the second asks again then (design/team-access.md §5). It reads the memberships as a request does.
func (*Users) NotifyConsentUpdated ¶ added in v0.8.2
NotifyConsentUpdated queues the consent-updated email for every user who holds an older version of the consent than the current one (and, for a required consent, who holds none). It never runs by itself: publishing a version sends nothing. The email limits apply, so a large realm may need more than one run; users already told are not told again until the version changes, because the run only goes by what each user holds.
func (*Users) NotifyPasswordBatch ¶ added in v0.9.1
func (s *Users) NotifyPasswordBatch(ctx context.Context, pj PasswordNoticeJob) (after string, c PasswordNoticeCounts, retryAfter time.Duration, err error)
NotifyPasswordBatch looks at the next users of a notification run, in id order, and writes to those who are due: it returns the id it reached ("" when the users are done) and what it did. A user is skipped when disabled, erased, without a verified address, or told after the epoch already; one the email limits hold back is counted as deferred and left for a later pass. The epoch's expiry is what selects the users, so an account that chose a new password since drops out by itself.
func (*Users) NotifyTemplateFailed ¶ added in v0.8.3
NotifyTemplateFailed tells the managers of an organization that a template of theirs couldn't be used when a message was sent: by email, at most once a day for each kind. It logs what fails and never returns an error: the message that failed goes out in the realm's text.
func (*Users) OnBehalfOf ¶
OnBehalfOf makes an API key caller act as the user with id: that user's rules and ownership apply. It returns ErrNotFound for unknown users.
func (*Users) OpenOrgSession ¶ added in v0.9.3
func (s *Users) OpenOrgSession(ctx context.Context, p Principal, orgID string) (Principal, string, error)
OpenOrgSession gives a signed-in person a second session, scoped to an organization they belong to: the one a person gets after creating another organization. It carries how the caller proved themselves.
func (*Users) OpenPendingUploads ¶ added in v0.8.0
OpenPendingUploads counts the unused pending uploads a caller holds.
func (*Users) OrgActive ¶ added in v0.8.3
OrgActive reports whether an active (or orphaned) organization with the id exists.
func (*Users) OrgByRef ¶ added in v0.9.3
OrgByRef finds the organization a person means by what they gave: its id or its slug (case and surrounding spaces do not matter). Only organizations a person can sign in to are found, active ones and orphaned ones (their members keep access); everything else is ErrNotFound.
func (*Users) OrgConnection ¶ added in v0.9.3
func (s *Users) OrgConnection(ctx context.Context, userID, orgID, provider string) (ConnectionView, error)
OrgConnection returns one connection for a member who holds manage: sso; ErrNotFound if none.
func (*Users) OrgConnectionAllowed ¶ added in v0.9.3
func (s *Users) OrgConnectionAllowed(ctx context.Context, userID, orgID, provider string) (registry.OrgCaps, error)
OrgConnectionAllowed says whether the caller may manage the organization's connection with provider: the realm offers it, they are a member, and their roles hold manage: sso. The HTTP layer asks before it asks for a fresh proof of identity.
func (*Users) OrgConnections ¶ added in v0.9.3
OrgConnections lists an organization's connections for a member who holds manage: sso.
func (*Users) OrgDomainsAllowed ¶ added in v0.9.13
OrgDomainsAllowed says whether the caller may manage the organization's domains; the HTTP layer asks before it asks for a fresh proof of identity. userID "" is an administrator.
func (*Users) OrgInvitationEmail ¶ added in v0.8.3
OrgInvitationEmail reads the invitation an email job names ("<org>/<id>") and opens its sealed token.
func (*Users) OrgInvitations ¶ added in v0.8.3
OrgInvitations lists an organization's invitations, newest first, to someone who may manage members. Tokens are never shown.
func (*Users) OrgNeedsMFA ¶ added in v0.8.3
OrgNeedsMFA reports whether the user is a member of an organization that requires a second factor: what the HTTP layer asks before it serves a session without one.
func (*Users) OrgSSORequired ¶ added in v0.9.3
OrgSSORequired says whether the organization named (id or slug) requires its connection, and its id. An unknown, deleted or inactive organization is not required to anything.
func (*Users) OrgSecret ¶ added in v0.9.3
func (s *Users) OrgSecret(ctx context.Context, orgID, name string) (value string, ok bool, err error)
OrgSecret returns the decrypted value of an organization's secret, for the sign-in code of that organization and nothing else (no handler hands it out, and function.yaml has no way to name it). ok is false when none is stored.
func (*Users) OrgTeamExists ¶ added in v0.8.3
OrgTeamExists reports whether the organization has a team with the id.
func (*Users) OrgTemplateFor ¶ added in v0.8.3
OrgTemplateFor returns the organization's override of a kind for the language, for rendering a message: nothing when there is none, the kind isn't customizable or the organization is gone.
func (*Users) OrgTemplateOf ¶ added in v0.8.3
func (s *Users) OrgTemplateOf(ctx context.Context, userID, orgID, kind, locale string) (OrgTemplate, error)
OrgTemplateOf returns one override; ErrNotFound when the organization has none.
func (*Users) OrgTemplates ¶ added in v0.8.3
OrgTemplates lists an organization's overrides to someone who may edit them.
func (*Users) OrgsEnabled ¶ added in v0.8.3
OrgsEnabled reports whether the realm has organizations.
func (*Users) OrgsManagedBy ¶ added in v0.8.3
OrgsManagedBy lists the organizations in which the user holds a role that manages the organization (manage: org), and whether they are the only one.
func (*Users) PasskeyCount ¶ added in v0.9.10
PasskeyCount is how many passkeys the user has (0 in a realm without passkeys).
func (*Users) PasskeyService ¶ added in v0.9.10
PasskeyService returns the passkey ceremonies for the realm, built from auth.passkeys, the store and the shared challenge table.
func (*Users) PasswordExpiredFor ¶ added in v0.9.1
PasswordExpiredFor says whether the user's password is expired now: they have one, and it was set before the realm's epoch or their own expiry. A user with no password isn't.
func (*Users) PasswordState ¶ added in v0.9.1
func (s *Users) PasswordState(ctx context.Context) (PasswordStatus, error)
PasswordState reports the realm's epoch and the number of accounts with a password, what an administrator confirms before expiring every password.
func (*Users) PeekEmailToken ¶ added in v0.4.0
PeekEmailToken checks a token for purpose without using it, so a page can show its form before the person acts. Every failure is ErrInvalidToken.
func (*Users) PendingUpload ¶ added in v0.8.0
PendingUpload returns a pending upload's record, or ErrNotFound.
func (*Users) PlanPushAudience ¶ added in v0.8.2
PlanPushAudience pages an audience into batches. It records its position in the job, so a planner that runs again continues where it stopped; the batches' ids make a repeat harmless.
func (*Users) PlanPushBatch ¶ added in v0.8.2
func (s *Users) PlanPushBatch(ctx context.Context, batchID, sendID string, users []string, messages map[string]push.Message, requestID string) (PushCounts, error)
PlanPushBatch applies the limits, resolves the devices and makes the delivery units of one batch of users. Unit ids derive from the batch's, so a batch that runs again continues where it was and makes nothing twice; the batch's totals are added once, when it ends.
func (*Users) PlanPushBatchRequiring ¶ added in v0.8.2
func (s *Users) PlanPushBatchRequiring(ctx context.Context, batchID, sendID string, users []string, messages map[string]push.Message, requestID, requiresConsent string) (PushCounts, error)
PlanPushBatchRequiring is PlanPushBatch for a send that requires a consent: users who don't hold it are counted as no_consent and get nothing (before the limits are applied, so they don't count against them).
func (*Users) PreviewOrgInvitation ¶ added in v0.8.3
func (s *Users) PreviewOrgInvitation(ctx context.Context, p Principal, token string) (OrgInvitationPreview, error)
PreviewOrgInvitation says what accepting a token would do, without doing it.
func (*Users) PreviewOrgInvitationOf ¶ added in v0.9.3
func (s *Users) PreviewOrgInvitationOf(ctx context.Context, orgRef, token string) (OrgInvitationPreview, error)
PreviewOrgInvitationOf says what a token offers to someone who hasn't signed in: the organization it is for must be the one named (an id or a slug). Anything else, an invitation of another organization included, is ErrInvalidOrgInvitation. The binding is not checked: it is checked when the invitation is used.
func (*Users) ProviderSecrets ¶ added in v0.9.13
func (s *Users) ProviderSecrets(ctx context.Context, p *registry.Provider) (map[string]string, bool, error)
ProviderSecrets reads the secrets the provider needs, by name; ok is false when one is not set.
func (*Users) PurgeUnverified ¶ added in v0.4.0
PurgeUnverified deletes accounts that never verified their address and are older than account.purge_unverified_after, and returns how many. Accounts with roles are never purged. Documents the accounts created stay, as with any deletion of a user.
func (*Users) PushSendByID ¶ added in v0.8.2
PushSendByID returns a send's record.
func (*Users) QueueEmail ¶ added in v0.4.0
QueueEmail applies the limits and queues an email job. The job holds the kind, the user, the locale and the redirect: no address, no message and no token. A worker creates the token, renders the message and calls the delivery function. It returns ErrEmailNotConfigured in a realm without email, and *EmailLimitedError when a limit is reached: callers without a signed-in user skip the send silently, so the answer reveals nothing; callers with one answer 429. Without a UserID nothing is queued, but the limits are counted all the same, so a request about an address that has no account does the same work as one that has.
func (*Users) QueueFileDeletion ¶ added in v0.8.0
QueueFileDeletion queues an object for deletion, in the realm's public storage when public; queueing the same key twice is one deletion.
func (*Users) QueueTemplateTest ¶ added in v0.8.3
func (s *Users) QueueTemplateTest(ctx context.Context, userID, orgID, kind, locale string, draft *email.Override, requestID string) error
QueueTemplateTest sends a draft (or the saved version, when draft is nil) of a template to the requesting user's own address, with "[TEST]" in the subject. At most OrgTemplateTestsPerHour per organization.
func (*Users) RateLimit ¶
RateLimit increments key's counter and returns *ThrottledError if the resulting count is over limit within window: shared across every backd instance (roadmap F9), unlike concurrency limits (F8), because the counter lives in Store, not in process memory. Reuses the same "N events per window" primitive as login throttling (Store's IncrementCounter), under its own key namespace so the two never collide.
func (*Users) ReauthMethodsOf ¶ added in v0.8.2
ReauthMethodsOf says which proofs a user gives: the second factor's when they have one (a password alone is not enough then), else the password, else a code sent by email. A user with none of them (no password, no second factor, and a realm that sends no email) has no way to prove anything more than their session, and sensitive actions don't ask.
func (*Users) Reauthenticate ¶ added in v0.8.2
func (s *Users) Reauthenticate(ctx context.Context, p Principal, method, proof, ip string) (ReauthGrant, error)
Reauthenticate checks one proof of the signed-in user and gives a token bound to their session, good for the realm's reauth.ttl and for any number of actions in it. proof is the code, or for ReauthPassword the password. Wrong proofs count against the same limits as signing in.
func (*Users) RecordConsent ¶ added in v0.8.2
func (s *Users) RecordConsent(ctx context.Context, userID string, in ConsentInput) (ConsentRecord, error)
RecordConsent appends a record for the user and updates their summary. Accepting needs a version the realm has a text for in the person's language; the record keeps that text's hash, so the proof names the exact words.
func (*Users) RecordConsentFor ¶ added in v0.8.2
func (s *Users) RecordConsentFor(ctx context.Context, userID string, in ConsentInput) (ConsentRecord, error)
RecordConsentFor records a consent given or withdrawn outside the app (on paper, by phone) by an administrator, with the reference that proves it. Audited.
func (*Users) RecordInvocation ¶
func (s *Users) RecordInvocation(ctx context.Context, rec InvocationRecord)
RecordInvocation stores one function call. A record that can't be stored is logged as an error; the call already happened and isn't undone by a failed write, the same philosophy as Audit.
func (*Users) RedeemEmailToken ¶ added in v0.4.0
RedeemEmailToken uses a token for purpose: it hashes it, finds it, checks purpose, expiry and use, and marks it used in one atomic step, so of two parallel redemptions exactly one succeeds. A success also invalidates the user's other outstanding tokens of the same purpose. Every failure is ErrInvalidToken.
func (*Users) RedeemLoginCode ¶ added in v0.8.2
RedeemLoginCode trades a login code and the PKCE verifier for a session. The code is used up whether or not the verifier fits, so a stolen code can't be tried again. Every failure is ErrInvalidCredentials, and the answer is the same for an unknown, expired or used code.
func (*Users) ReduceConsentRecords ¶ added in v0.8.2
ReduceConsentRecords is what an erase leaves of a person's consent records (design/compliance.md §8): the IP address and the user agent go, the user id becomes an HMAC of the normalized address under a realm secret, and what proves consent stays (names, versions, text hashes, actions, methods, times) until `compliance.consent_retention` has passed, when the database removes them. With a retention of 0 they go at once. Safe to repeat. It returns how many records it touched.
func (*Users) RegenerateRecoveryCodes ¶ added in v0.8.2
RegenerateRecoveryCodes replaces every recovery code of the user and returns the new ones, shown once.
func (*Users) RegisterDevice ¶ added in v0.8.2
RegisterDevice registers or refreshes a device of the signed-in user and returns it. A token that exists moves to this user and session; above the cap the least recently seen device goes.
func (*Users) ReleaseDirectUpload ¶ added in v0.8.0
ReleaseDirectUpload gives a claimed direct upload back, to wait for its bytes again.
func (*Users) ReleaseIdempotency ¶
ReleaseIdempotency removes a claim that shouldn't be remembered (the executor was unreachable or busy — nothing about the call's own outcome to replay), so a retry can go through cleanly.
func (*Users) ReleasePendingUpload ¶ added in v0.8.0
ReleasePendingUpload gives a claimed pending upload back, when the write that claimed it didn't happen.
func (*Users) RemoveDevice ¶ added in v0.8.2
RemoveDevice removes one of the user's devices; ErrNotFound when it isn't theirs. An administrator's removal (by != "") is audited.
func (*Users) RemoveDevicesOfPlatform ¶ added in v0.8.2
RemoveDevicesOfPlatform removes every device of a platform, for an administrator: rotating a realm's VAPID key makes every web subscription useless (browsers made them under the old key), so they go at once and apps subscribe again at their next launch. It is audited.
func (*Users) RemoveMember ¶ added in v0.8.3
RemoveMember removes a member; it needs manage: members, and the member can't hold more than the caller.
func (*Users) RemoveOrgConnections ¶ added in v0.9.3
RemoveOrgConnections removes every sign-in connection of an organization and every secret kept for it, and returns how many connections there were. It is what the cleanup of a deleted organization does, and it can be repeated: a second run finds nothing.
func (*Users) RemoveOrgDomain ¶ added in v0.9.13
RemoveOrgDomain releases a claim (a verified one frees the domain for another organization).
func (*Users) RemoveOrgDomains ¶ added in v0.9.13
RemoveOrgDomains releases every claim of an organization: what the cleanup of a deleted one does. It can be repeated.
func (*Users) RemoveOrgTeamMember ¶ added in v0.8.3
func (s *Users) RemoveOrgTeamMember(ctx context.Context, userID, orgID, id, target string) (MemberView, error)
RemoveOrgTeamMember takes a member out of a team.
func (*Users) RemovePasskey ¶ added in v0.9.10
RemovePasskey removes one of the user's passkeys. It refuses (ErrLastSignInMethod) the user's last way to sign in, ends the sessions that passkey opened, tells the user and audits it.
func (*Users) RemovePassword ¶ added in v0.8.2
RemovePassword removes the user's password, so that they sign in with a link or a provider only. It refuses when nothing else would be left (ErrLastSignInMethod), and ends every other session: whoever knew the password may have a session. The caller has checked a fresh proof of identity.
func (*Users) RemoveRole ¶
RemoveRole takes a role away from a user. An assignment seeded in realm.yaml comes back at the next seeding.
func (*Users) RenamePasskey ¶ added in v0.9.10
RenamePasskey renames one of the user's passkeys.
func (*Users) RenewJobLease ¶ added in v0.8.0
func (s *Users) RenewJobLease(ctx context.Context, id string, attempt int, d time.Duration) (bool, error)
RenewJobLease keeps a running job's lease for another d, for the worker's attempt; false when it no longer runs that attempt.
func (*Users) ReportRoles ¶
func (s *Users) ReportRoles(ctx context.Context) (RoleReport, error)
ReportRoles compares the stored assignments with realm.yaml.
func (*Users) RequestEmailChange ¶ added in v0.4.0
func (s *Users) RequestEmailChange(ctx context.Context, p Principal, newAddress, redirectTo, ip, requestID string) error
RequestEmailChange starts a change of the signed-in user's own address: it needs the current password, remembers the new address as pending and sends a confirmation link to it. Nothing changes until that link is used. An address someone else already has is answered like any other (the request is accepted and nothing is sent), so this can't be used to find out who is registered. A reached email limit is an *EmailLimitedError: the caller is signed in, so it may be told.
func (*Users) RequestMagicLink ¶ added in v0.8.2
RequestMagicLink makes a request and asks for its email, returning the request id the asking app keeps to redeem the code. It answers the same, in about the same work, for every address: a known one, one without an account (a message says so) and one that can't sign in (nothing is sent), so it says nothing about who is registered. An email limit that is reached changes nothing for the caller either: the message is skipped.
func (*Users) RequestPasswordReset ¶ added in v0.4.0
func (s *Users) RequestPasswordReset(ctx context.Context, address, redirectTo, ip, requestID string) error
RequestPasswordReset asks for a reset email. It answers nothing about the account: an unknown or disabled address does the same work as a known one, minus the queued job. Requests are counted per address and per client (a *ThrottledError once past the limit, for every address alike), and the email limits apply on top.
func (*Users) RequestReauthCode ¶ added in v0.8.2
RequestReauthCode makes a code and emails it to a user whose proof is one (no second factor, no password): the code is made when the message is, kept only as a hash, and good for 10 minutes and 5 attempts. A new request replaces the earlier code.
func (*Users) RequestUserExport ¶ added in v0.9.2
func (s *Users) RequestUserExport(ctx context.Context, userID string, req ExportRequest) (UserExport, error)
RequestUserExport queues the export of a user's data.
func (*Users) RerunJob ¶ added in v0.8.0
RerunJob queues a new job for a finished function job: the same function, input and caller, as a job of its own (RerunOf says which). timeoutMS is the function's timeout now, for the new job's lease.
func (*Users) ResendOrgInvitation ¶ added in v0.8.3
func (s *Users) ResendOrgInvitation(ctx context.Context, userID, orgID, id, locale, ip, requestID string) error
ResendOrgInvitation sends the email of an invitation bound to an address again.
func (*Users) ResendVerification ¶ added in v0.4.0
func (s *Users) ResendVerification(ctx context.Context, address, redirectTo, ip, requestID string) error
ResendVerification asks again for the verification email of an address. It answers nothing about the account: an unknown, disabled or already verified address does the same work, minus the queued job, and every limit counts the same.
func (*Users) ResetMFA ¶ added in v0.8.2
ResetMFA removes a user's second factor and recovery codes and ends all of their sessions, on an administrator's say-so (or an operator's, with direct access): the user is asked to set one up again at their next sign-in when a role requires it, and is told by email. actorID is the administrator's user id (""), who can't reset themselves; ErrMFANotEnabled when the user has none.
func (*Users) ResetPassword ¶ added in v0.4.0
ResetPassword uses a reset token to set a new password. The password is checked first, so a refused one (*PolicyError) leaves the token usable. Success ends every session of the user, marks the address verified (the token proves the person reads that mailbox) and sends password-changed. An account that was not verified yet is claimed first (claimUnverified): its passkeys, second factor and linked providers go with the old password. It never starts a session. Every way the token can be wrong is ErrInvalidToken.
func (*Users) ResolveOrgContext ¶ added in v0.8.3
ResolveOrgContext returns org when it can be the company context of a request about address: the organization exists and isn't deleted, and the address belongs to one of its members or has a pending invitation by email to it. Anything else, an unknown organization and a stranger's address alike, returns "": the caller treats the request as if it had no `org`, so the answer and the work are the same and nothing says who belongs where.
func (*Users) ResolveProviderLogin ¶ added in v0.8.2
func (s *Users) ResolveProviderLogin(ctx context.Context, in ProviderLogin) (ProviderResult, error)
ResolveProviderLogin decides who a provider's person is under the rules of design/sso.md §8.1: the engine's decision, carried out on the realm's accounts. It starts no session. The sign-in handlers run it inside the engine; this is the same decision for callers that already hold the verified login.
func (*Users) ResolveSecrets ¶
func (s *Users) ResolveSecrets(ctx context.Context, refs []registry.SecretRef, database string) (values map[string]string, missing []string, err error)
ResolveSecrets decrypts the values a function declared (refs), for database (its own). It returns values keyed exactly as declared (SecretRef.String(): NAME or realm.NAME) and, separately, the refs with no stored value, so the caller can answer secret_missing. Decrypted values are cached for a short time, so a rotation or a changed value applies within a minute without restarting anything.
func (*Users) RetryFileDeletion ¶ added in v0.8.0
RetryFileDeletion keeps a deletion that failed, to be claimed again after wait.
func (*Users) RetryJob ¶ added in v0.4.0
RetryJob puts a job whose attempt failed back in the queue, to be claimed again once delay has passed.
func (*Users) RevertEmailChange ¶ added in v0.4.0
RevertEmailChange uses the link sent to the old address: it restores that address, ends every session of the user and makes their password unusable, since whoever changed the address may know it, and sends a password reset link to the restored address. Every way the token can be wrong is ErrInvalidToken.
func (*Users) RevokeAPIKey ¶
RevokeAPIKey deletes a key; it stops working at once.
func (*Users) RevokeAllSessions ¶ added in v0.9.1
RevokeAllSessions ends every session of the realm and says how many; passwords are not touched.
func (*Users) RevokeInvitation ¶
RevokeInvitation deletes an invitation; ErrNotFound if none has that id.
func (*Users) RevokeOrgInvitation ¶ added in v0.8.3
RevokeOrgInvitation ends an invitation.
func (*Users) RevokeSession ¶
RevokeSession ends one of the caller's sessions; ErrNotFound if the caller has no session with that id.
func (*Users) RevokeUserSession ¶ added in v0.7.0
RevokeUserSession ends one session of a user, on an administrator's say-so; ErrNotFound if the user has no session with that id.
func (*Users) RotateKey ¶ added in v0.9.1
func (s *Users) RotateKey(ctx context.Context, name, value string, resume bool, by string) (RotatedKey, error)
RotateKey replaces a field key's value and re-wraps every data key it wrapped, so no document is rewritten (design/field-encryption.md §5.3). value is the new key in base64url, or empty to generate one; resume continues a rotation that stopped before it finished, with the value that rotation chose. While it runs the previous value stays, so every data key stays readable; it is dropped only when none is wrapped by it any more.
func (*Users) RuleOrgs ¶ added in v0.8.3
func (s *Users) RuleOrgs(ctx context.Context, userID string, mfa bool, scope string) (map[string]*rules.UserOrg, error)
RuleOrgs returns the membership of a user in the organization a session is scoped to, if it counts, in the form access rules read it: the roles the user holds there (direct, default and through teams), the teams and the organization's claims. A session reaches one organization, so the map has one entry or none (an operator's session, which is scoped to none, has none). Loaded when a rule asks, never cached.
func (*Users) SaveAppleToken ¶ added in v0.8.2
SaveAppleToken keeps Apple's refresh token on the user's Apple identity, sealed, unless the provider is configured with revoke_on_delete: false (then nothing is stored).
func (*Users) SaveCheckReport ¶ added in v0.8.0
func (s *Users) SaveCheckReport(ctx context.Context, r CheckReport) error
SaveCheckReport stores r as the collection's latest report, replacing the last.
func (*Users) SaveOrgTemplate ¶ added in v0.8.3
func (s *Users) SaveOrgTemplate(ctx context.Context, userID, orgID, kind, locale string, o email.Override) (OrgTemplate, []string, error)
SaveOrgTemplate stores the organization's version of a kind in a language after checking it. The previous one becomes a version; the last OrgTemplateVersions are kept.
func (*Users) ScheduleStates ¶ added in v0.8.0
ScheduleStates returns the state of every function that has ever been paused, keyed by "<database>/<function>".
func (*Users) SealToken ¶ added in v0.8.2
SealToken encrypts a token for storage with the realm's secrets cipher. The result names the key it was sealed under, so a rotated key is noticed.
func (*Users) SendInvitation ¶ added in v0.4.0
func (s *Users) SendInvitation(ctx context.Context, address string, ttl time.Duration, createdBy, redirectTo, locale, ip, requestID string) (Invitation, error)
SendInvitation is CreateInvitation for an invitation that backd emails to the address it is bound to: the person gets a link to a page where they choose a password. Nobody holds the invitation's own token, so no token is returned; the link's token is made by a worker when it sends the message, and only its hash is stored. A reached email limit removes the invitation again and is an *EmailLimitedError.
func (*Users) SetDisabled ¶
SetDisabled disables or re-enables the user. Disabling revokes all of their sessions.
func (*Users) SetEmailVerified ¶
SetEmailVerified marks the user's email as verified or not.
func (*Users) SetImageDeclaration ¶ added in v0.8.1
SetImageDeclaration records a declared version's fingerprint.
func (*Users) SetJobSteps ¶ added in v0.8.0
func (s *Users) SetJobSteps(ctx context.Context, id string, attempt int, steps []Step, omitted int) (bool, error)
SetJobSteps stores the steps the attempt numbered attempt reported, replacing what the job held. It does nothing (false) when the job is not running that attempt any more: finished, cancelled, or claimed again by another worker.
func (*Users) SetLocale ¶ added in v0.4.0
SetLocale changes a user's language to one the realm lists (ignoring case; es-mx sets es-MX). Any other value is an *InvalidLocaleError naming the allowed ones: unlike sign-up, an explicit change isn't silently mapped.
func (*Users) SetNetworks ¶
func (s *Users) SetNetworks(ctx context.Context, email string, admin, login registry.Networks) (User, error)
SetNetworks replaces the user's network restrictions: admin limits their admin API requests (within the realm's allowed networks), login their login and session use. Empty lists remove the restriction. Settings realm.yaml doesn't hold live only in the database.
func (*Users) SetOrgConnection ¶ added in v0.9.3
func (s *Users) SetOrgConnection(ctx context.Context, userID, orgID, provider string, in ConnectionInput) (ConnectionView, error)
SetOrgConnection creates or replaces a connection for a member who holds manage: sso (the HTTP layer asks for a fresh proof of identity before). The roles it gives on joining follow the granting rules: nothing the caller couldn't give themselves.
func (*Users) SetOrgRequireMFA ¶ added in v0.8.3
func (s *Users) SetOrgRequireMFA(ctx context.Context, p Principal, orgID string, on bool) (Membership, error)
SetOrgRequireMFA turns an organization's second-factor requirement on or off. It needs manage: org (and the caller has proved who they are just now, which the HTTP layer checks). Turning it on needs the realm to allow it and the caller's own session to have a second factor, since without one their access would end at once.
func (*Users) SetOrgSSORequired ¶ added in v0.9.3
func (s *Users) SetOrgSSORequired(ctx context.Context, p Principal, orgID string, on bool) (SSORequiredResult, error)
SetOrgSSORequired turns sso_required on or off for the organization of the caller's session. It needs manage: org (the HTTP layer has asked for a fresh proof). Turning it on needs a working connection and that the caller signed in through one, so nobody locks themselves out; it then ends the sessions that were not opened through a connection. Turning it off needs neither.
func (*Users) SetOrgSecret ¶ added in v0.9.3
SetOrgSecret does the same for an organization's scope. Nothing reads these values back except the sign-in code of that organization: there is no way to list or fetch one.
func (*Users) SetOrgSessionMaxAge ¶ added in v0.9.3
func (s *Users) SetOrgSessionMaxAge(ctx context.Context, userID, orgID string, d time.Duration) (Membership, error)
SetOrgSessionMaxAge sets how long the sessions opened in the organization last (0 removes the limit: the realm's applies). It needs manage: org. A session's expiry is fixed when it is opened, so this changes the sessions opened from now on.
func (*Users) SetPassword ¶
SetPassword sets or replaces the user's password and revokes all of their sessions.
func (*Users) SetSchedulePaused ¶ added in v0.8.0
func (s *Users) SetSchedulePaused(ctx context.Context, database, function string, paused bool, by string) (ScheduleState, error)
SetSchedulePaused pauses or resumes a scheduled function's runs. Asking for the state it already has changes nothing.
func (*Users) SetSchemaMigrateProgress ¶ added in v0.9.11
func (s *Users) SetSchemaMigrateProgress(ctx context.Context, jobID string, m SchemaMigrateJob) error
SetSchemaMigrateProgress keeps the place and counts of a running migration.
func (*Users) SetSecret ¶
SetSecret creates or replaces the value at scope (database, or "" for the realm) and name, encrypting it with Cipher. by is the actor for UpdatedBy (see Caller.Actor).
func (*Users) SetTeamRole ¶ added in v0.8.3
func (s *Users) SetTeamRole(ctx context.Context, caller, orgID, teamID, target, role string, op TeamRoleOp, w TeamRoleWindow) (TeamMemberView, error)
SetTeamRole gives, re-windows or revokes a team role of a member in a team. caller is the user making the request, who needs manage: teams or a team role of that team that grants role; "" stands for an administrator or a function, who may do it in any active organization.
func (*Users) SetUploadStatus ¶ added in v0.8.0
SetUploadStatus moves an upload through its states (JournalStored, then JournalAttached or JournalFailed).
func (*Users) SignIn ¶ added in v0.8.2
SignIn is Login for callers that can answer a second step: the outcome is a session, or a challenge the user trades for one with VerifyMFA. In a realm with organizations it is the operators' door alone.
func (*Users) SignInLinks ¶ added in v0.9.3
SignInLinks lists the organizations a user can sign in to, by name, each with the link to its sign-in page (organizations.signin_link with the slug, or the id when it has none, and the id).
func (*Users) SignInMethods ¶ added in v0.8.2
SignInMethods lists the ways the user can sign in now: "password", "magic_link", "passkey" (when the realm has a strategy that starts with one and the user has one) and the provider names, in that order.
func (*Users) SignInToOrg ¶ added in v0.9.3
SignInToOrg checks an email and password for an organization: the person must be one of its members, or hold a valid invitation to it. A wrong password, an unknown address, an unknown or inactive organization and a person who does not belong are all ErrInvalidCredentials after the same work, and count the same toward the sign-in limits. The session, or the second step, is scoped to the organization.
func (*Users) SignInWith ¶ added in v0.9.10
func (s *Users) SignInWith(ctx context.Context, strategy, email, password, ip string) (Redeemed, error)
SignInWith is SignIn with the strategy the caller names ("" when it names none, which is allowed while only one strategy starts with the password). A strategy that does not exist or starts with another method is ErrUnknownStrategy, before anything about the person is looked at.
func (*Users) SignInWithPasskey ¶ added in v0.9.10
SignInWithPasskey verifies the assertion and goes on in the strategy engine: a session, the consent challenge, or the challenge for the strategy's next step. Every failure is ErrInvalidPasskey (or a *ThrottledError / *MFALockedError for a limit).
func (*Users) SignUp ¶ added in v0.4.0
func (s *Users) SignUp(ctx context.Context, r SignupRequest) (SignupResult, error)
SignUp creates the account like Signup, and in a realm with email asks for the verification email. The realm may also require the address to be verified before any session: then there is none (Pending).
func (*Users) SignUpToOrg ¶ added in v0.9.3
func (s *Users) SignUpToOrg(ctx context.Context, r OrgSignupRequest) (SignupResult, error)
SignUpToOrg creates an account for someone an organization invited and signs them in to it. Whatever is wrong with the invitation, the organization or the address it is bound to, the answer is ErrInvalidOrgInvitation or ErrInvitationNotForYou, after the token has proved itself. An invitation bound to the address was sent to it, so the account is born verified.
func (*Users) SignUpWithOrg ¶ added in v0.9.3
func (s *Users) SignUpWithOrg(ctx context.Context, r NewOrgSignupRequest) (SignupResult, Membership, error)
SignUpWithOrg makes an account and an organization for someone new, with the person as its creator, and signs them in to it. The realm's sign-up decides who may: anyone when it is open, whoever holds an invitation of the realm (SignupRequest.Invitation) when it is invite-only, and nobody when it is closed. This is how a company starts, and organizations.create does not apply to the first one (a new account cannot satisfy user.email_verified); max_created_per_user does. The organization is returned when it was made; the answer for a registered address, when the realm verifies addresses, is the same as for a new one and makes nothing.
func (*Users) Signup ¶
func (s *Users) Signup(ctx context.Context, email, password, invitation string, locales ...string) (Principal, string, error)
Signup creates a user with a password and signs them in. Realms with `signup: open` accept anyone; `signup: invite` needs a valid invitation token (used up by a successful sign-up); `signup: closed` refuses.
locales are the languages the person asked for, most wanted first (the request's locale, then Accept-Language); the user gets the best one the realm lists, or its default, silently.
func (*Users) StartAssignOrg ¶ added in v0.8.3
func (s *Users) StartAssignOrg(ctx context.Context, database string, e AssignOrgJob, requestedBy, requestID string) (Job, error)
StartAssignOrg queues the assignment of an organization to the documents of a collection that have none. A collection has at most one at a time.
func (*Users) StartEncryptMigration ¶ added in v0.9.1
func (s *Users) StartEncryptMigration(ctx context.Context, ej EncryptJob, requestedBy, requestID string) (Job, error)
StartEncryptMigration queues the migration of a collection. It is safe to start again after a cancel or a failure: it goes on from the beginning, and what is already migrated is skipped.
func (*Users) StartPasswordNotice ¶ added in v0.9.1
func (s *Users) StartPasswordNotice(ctx context.Context, requestedBy, requestID string) (Job, error)
StartPasswordNotice queues the job that emails every user whose password the realm's epoch expired, a reset link each. It is safe to start again after a cancel or a failure: users already told are skipped. ErrEmailNotConfigured in a realm without email, ErrNoPasswordEpoch before any expiry, and *ErrPasswordNoticeRunning when one is running.
func (*Users) StartProviderSession ¶ added in v0.8.2
func (s *Users) StartProviderSession(ctx context.Context, u User, provider string, newUser bool, profile map[string]string) (Redeemed, error)
StartProviderSession starts a session for a user a provider login resolved (the native flow, which has no login code to redeem).
func (*Users) StartProviderSessionFor ¶ added in v0.9.10
func (s *Users) StartProviderSessionFor(ctx context.Context, u User, provider, strategy string, newUser bool, profile map[string]string, org string) (Redeemed, error)
StartProviderSessionFor is StartProviderSessionIn for a sign-in that follows the named strategy.
func (*Users) StartProviderSessionIn ¶ added in v0.9.3
func (s *Users) StartProviderSessionIn(ctx context.Context, u User, provider string, newUser bool, profile map[string]string, org string) (Redeemed, error)
StartProviderSessionIn is StartProviderSession for a person an organization's connection signed in: the session records the organization.
func (*Users) StartPushSend ¶ added in v0.8.2
func (s *Users) StartPushSend(ctx context.Context, in PushSendInput, requestID string) (PushStarted, error)
StartPushSend records a send and starts it. A send of one batch or less is planned here, so its answer has the limits applied; a larger one is left to jobs.
func (*Users) StartRegeneration ¶ added in v0.8.1
func (s *Users) StartRegeneration(ctx context.Context, database string, e ImageJob, requestedBy, requestID string) (Job, error)
StartRegeneration queues the making again of the versions of a file field that no longer match what it declares (a scan job; see ImageJob.Scan). A field has at most one at a time.
func (*Users) StartSchemaCheck ¶ added in v0.8.0
func (s *Users) StartSchemaCheck(ctx context.Context, scope CheckJob, requestedBy, requestID string) (Job, error)
StartSchemaCheck queues a schema check of collections (each "<database>/<collection>"), or *ErrCheckRunning when one is already queued or running in the realm. scope is what was asked for (database and collection, either may be "").
func (*Users) StartSchemaMigration ¶ added in v0.9.11
func (s *Users) StartSchemaMigration(ctx context.Context, j SchemaMigrateJob, requestedBy, requestID string) (job Job, created bool, err error)
StartSchemaMigration queues the migration of a collection to j.Target. When one for the same target is already queued or running (another worker started it, or an administrator did), that job is returned and created is false: starting is idempotent. One for an earlier target is cancelled and replaced, because the new one starts from the first document and also migrates what the old one had not reached. A dry run never replaces a running job.
func (*Users) StorageUsage ¶ added in v0.8.0
StorageUsage returns the running totals: the realm's and the limit users holding the most.
func (*Users) StorageUsageOf ¶ added in v0.8.1
func (s *Users) StorageUsageOf(ctx context.Context, owner string) (realm, user StorageUsageTotals, err error)
StorageUsageOf returns the realm's totals and those of one user, for the quotas.
func (*Users) SweepDevices ¶ added in v0.8.2
SweepDevices removes the devices not seen for push.devices.stale_after and those whose session ended without anyone calling anything (it expired). Running it in every worker is harmless.
func (*Users) SweepTeamRoles ¶ added in v0.8.3
SweepTeamRoles removes the team role grants that ended more than TeamRoleHistory ago. Running it in every worker is harmless.
func (*Users) SyncAuditEntries ¶ added in v0.9.12
SyncAuditEntries logs which audit entries the realm has switched away from their default and, when that set changed since the last start, records AuditEntriesChanged. The last set is read from the latest such record, so nothing else is stored; with no record (or after it expired) the comparison is against the defaults, so a realm that never touched `audit.entries` records nothing.
func (*Users) TeamMembers ¶ added in v0.8.3
func (s *Users) TeamMembers(ctx context.Context, userID, orgID, teamID, role, after string, limit int) ([]TeamMemberView, bool, error)
TeamMembers lists the members and role holders of a team to a member of the organization, honoring windows. With role, only the holders of that role in force now.
func (*Users) Unlink ¶ added in v0.8.2
Unlink removes the user's sign-in method of a provider, never the last one: ErrLastSignInMethod. ErrNotFound when the user has none of that provider. by says who did it for the audit ("self" or "admin").
func (*Users) UnlinkIn ¶ added in v0.9.3
UnlinkIn is Unlink for the identity a person has through an organization's connection.
func (*Users) UpdateMember ¶ added in v0.8.3
func (s *Users) UpdateMember(ctx context.Context, userID, orgID, target string, roles []string) (MemberView, error)
UpdateMember replaces a member's direct roles with the given names.
func (*Users) UpdateOrg ¶ added in v0.8.3
func (s *Users) UpdateOrg(ctx context.Context, userID, orgID string, name, slug *string) (Membership, error)
UpdateOrg renames an organization or changes its slug; it needs manage: org.
func (*Users) UpdateOrgDomain ¶ added in v0.9.13
func (s *Users) UpdateOrgDomain(ctx context.Context, userID, orgID, domain string, in DomainUpdate) (DomainView, error)
UpdateOrgDomain sets the switches of a claim.
func (*Users) UpdateOrgTeam ¶ added in v0.8.3
func (s *Users) UpdateOrgTeam(ctx context.Context, userID, orgID, id string, name *string, roles []string, setRoles bool) (OrgTeam, error)
UpdateOrgTeam renames a team or changes its roles; the roles it gains or loses follow the granting rules, and the organization keeps a manager.
func (*Users) UpdatePassword ¶ added in v0.9.4
func (s *Users) UpdatePassword(ctx context.Context, in PasswordUpdate) error
UpdatePassword replaces a user's password when they prove the current one, expired or not. It is the way out of a password an administrator expired for the user alone: the realm-wide expiry of a leak is refused (the old password may be in the leak), and the user resets it with the email instead. An account with a second factor must also give a code. Success ends every session of the user and starts none: they sign in again, second factor included. Wrong proofs count against the same limits as signing in.
func (*Users) UploadEntry ¶ added in v0.8.0
UploadEntry returns an upload's record whatever kind it is, or ErrNotFound.
func (*Users) UseMagicLink ¶ added in v0.8.2
func (s *Users) UseMagicLink(ctx context.Context, token, ip string) (code, destination string, err error)
UseMagicLink is what opening the link does, once the person pressed the button: it uses up the request and signs the user in as far as a login code, which the browser carries to the asking app (bound to its PKCE challenge). It returns the code. Errors are those of a provider sign-in: a *RefusedError for an account that can't sign in, ErrSignupClosed.
func (*Users) UserExport ¶ added in v0.9.2
UserExport returns one of a user's exports, or ErrNotFound (another user's is not found).
func (*Users) UserExports ¶ added in v0.9.2
UserExports lists a user's exports, newest first.
func (*Users) UserSessions ¶ added in v0.7.0
UserSessions lists a user's unexpired sessions, newest first (an administrator's view of someone else's).
func (*Users) UsersWithoutRequiredMFA ¶ added in v0.8.2
UsersWithoutRequiredMFA lists, up to limit, the users whose role requires a second factor and who have none, oldest first by address, and says how many there are in all. Erased and disabled users are not counted: they can't sign in.
func (*Users) ValidateConsents ¶ added in v0.8.2
ValidateConsents checks that the consents a request names exist with a text, without asking for the required ones: for requests that carry them for later (a magic link, a provider sign-in), where whether an account is made isn't known yet.
func (*Users) VerificationNeedsPassword ¶ added in v0.9.14
func (s *Users) VerificationNeedsPassword(ctx context.Context, t EmailToken) bool
VerificationNeedsPassword says whether using the verification token t takes the account's password: the account is not verified yet and has one. A page asks for it then.
func (*Users) VerifiedDomainOf ¶ added in v0.9.13
VerifiedDomainOf returns the organization that holds the domain as verified ("" for none): what the features that rely on a proved domain ask.
func (*Users) VerifyEmail ¶ added in v0.4.0
VerifyEmail uses a verification token: it marks the address verified and, if the realm wants it, asks for the welcome email. It never starts a session. Every way the token can be wrong is ErrInvalidToken.
The link proves that whoever opens it reads the mailbox, not that they made the account: anyone can sign up with someone else's address, and the message goes to its owner. So the account's password is asked for (ErrPasswordRequired without one, ErrInvalidCredentials for a wrong one, counted like a failed login; the token stays usable), and only the person who signed up can verify it. An account with no password can't prove that: it is claimed (claimUnverified), like at a magic link, so nothing set before the mailbox was proved works afterwards. A verified account's token needs nothing.
func (*Users) VerifyMFA ¶ added in v0.8.2
func (s *Users) VerifyMFA(ctx context.Context, challenge, method, code, ip string) (Verified, error)
VerifyMFA trades a challenge and a second-factor code for the session the first factor was waiting for. method is MethodTOTP or MethodRecovery. ip is the caller's address, for the login throttle. The answer to an unknown, used, expired or exhausted challenge is always ErrInvalidChallenge.
func (*Users) VerifyMFAPasskey ¶ added in v0.9.10
func (s *Users) VerifyMFAPasskey(ctx context.Context, challenge string, credential []byte, ip string) (Verified, error)
VerifyMFAPasskey is VerifyMFA for a step that asks for a passkey: credential is the JSON of the assertion, made with the options of BeginPasskeyStep. A wrong ceremony is an *InvalidCodeError and counts like a wrong code.
func (*Users) VerifyMagicLinkCode ¶ added in v0.8.2
func (s *Users) VerifyMagicLinkCode(ctx context.Context, requestID, code, verifier, ip string) (Redeemed, error)
VerifyMagicLinkCode is the code typed in the asking app: with the request id and the verifier of its PKCE challenge it signs the user in like the link would, answering a session or the MFA challenge. Five wrong codes end the request.
func (*Users) VerifyOrgDomain ¶ added in v0.9.13
func (s *Users) VerifyOrgDomain(ctx context.Context, userID, orgID, domain string) (DomainView, error)
VerifyOrgDomain checks the record now. A proved domain becomes verified unless another organization holds it (ErrDomainTaken); one that is not proved stays as it is and the view says why.
func (*Users) WithdrawConsent ¶ added in v0.8.2
func (s *Users) WithdrawConsent(ctx context.Context, u User, consent string, from ConsentContext) (User, error)
WithdrawConsent records the withdrawal of an optional consent by the user. A required consent can't be withdrawn without deleting the account (ErrConsentRequiredForAccount).
type WithheldRole ¶ added in v0.8.3
type WithheldRole struct {
Role string
// Team is the team of a team role; "" for an organization role.
Team string
// Caps are what an organization role would let its holder manage; Grants are the team roles
// a team role would let its holder give.
Caps registry.OrgCaps
Grants []string
}
WithheldRole is a role that doesn't count for a session without a second factor.
Source Files
¶
- accountexport.go
- apikeys.go
- apple.go
- audit.go
- auth.go
- callback.go
- concurrency.go
- consents.go
- consents_signin.go
- core.go
- devices.go
- email.go
- emailchange.go
- emailtoken.go
- encryptjob.go
- erase.go
- files.go
- idempotency.go
- identities.go
- invitations.go
- invocations.go
- jobs.go
- keysecret.go
- magiclink.go
- mfa.go
- mfa_manage.go
- oauth.go
- onsignup.go
- orgcontext.go
- orgdelete.go
- orgdomains.go
- orghooks.go
- orginvitations.go
- orgroles.go
- orgs.go
- orgsignin.go
- orgsso.go
- orgssorequired.go
- orgteamroles.go
- orgteams.go
- orgtemplates.go
- passkeys.go
- passkeys_manage.go
- passkeys_signin.go
- passkeys_steps.go
- password.go
- passwordexpiry.go
- passwordnotice.go
- passwordupdate.go
- portable.go
- push.go
- ratelimit.go
- reauth.go
- reset.go
- resetlink.go
- roles.go
- schedules.go
- schemacheck.go
- schemamigrate.go
- secrets.go
- sessions.go
- signinaudit.go
- ssohost.go
- throttle.go
- userexport.go
- users.go
- verify.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authtest provides an in-memory auth.Store for tests.
|
Package authtest provides an in-memory auth.Store for tests. |
|
Package passkey is the WebAuthn side of passkeys (design/passkeys.md §14): the ceremonies of registering a credential and signing in with one, and the credential model with its store.
|
Package passkey is the WebAuthn side of passkeys (design/passkeys.md §14): the ceremonies of registering a credential and signing in with one, and the credential model with its store. |
|
passkeytest
Package passkeytest has what tests of passkeys need: an in-memory store and ceremony keeper, and a software authenticator that plays the browser's and the authenticator's side of the ceremonies.
|
Package passkeytest has what tests of passkeys need: an in-memory store and ceremony keeper, and a software authenticator that plays the browser's and the authenticator's side of the ceremonies. |