access

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package access holds the use cases of the access context: members, the instance admin, API tokens and the authentication of their callers.

Index

Constants

View Source
const AuthRetentionBatch = 1000

AuthRetentionBatch is how many rows one transaction of the purge deletes, so a backlog never holds locks or a transaction open for long.

View Source
const DefaultBackgroundLimit = 256

DefaultBackgroundLimit is how many jobs run at once unless the runner is given another limit.

View Source
const MailBound = time.Minute

MailBound bounds a mail sent in the background, from the commit of the change causing it.

Variables

View Source
var ErrExternalIDTaken = apperrors.Conflict("external_id_taken", "another member of the provider holds this external ID")

ErrExternalIDTaken refuses an external ID another member of the provider holds.

View Source
var ErrGrantNotFound = apperrors.NotFound("not_found", "no grant of the project has this identifier")

ErrGrantNotFound answers an identifier no grant of the project has.

View Source
var ErrInstanceAdminExists = apperrors.Conflict("instance_admin_exists", "an instance admin already exists")

ErrInstanceAdminExists refuses a bootstrap once the instance has an instance admin: from then on, they add the others.

View Source
var ErrInvalidCredentials = apperrors.Unauthenticated("invalid_credentials", "the email or password is wrong")

ErrInvalidCredentials refuses a sign-in whatever went wrong with the email or the password, so nobody learns from it which emails exist, nor whether the password of a member who may not sign in was right.

View Source
var ErrMemberNotFound = apperrors.NotFound("not_found", "no member has this identifier")

ErrMemberNotFound answers an identifier no member has.

View Source
var ErrNoMemberWithEmail = apperrors.NotFound("not_found", "no member has this email")

ErrNoMemberWithEmail refuses a command naming an email no member has.

View Source
var ErrNoSession = errors.New("access: not a session cookie")

ErrNoSession answers a cookie that is not one the server issued: it is no credential at all, dropped before any lookup.

View Source
var ErrNotFound = errors.New("access: not found")

ErrNotFound is what a store answers for an entity it does not hold.

View Source
var ErrNotInvited = errors.New("access: the member is not invited")

ErrNotInvited refuses activating a member who is no longer invited: they accepted their invitation, or were deactivated, since they were read.

View Source
var ErrProvisionedMemberNotFound = errors.New("access: no such provisioned member")

ErrProvisionedMemberNotFound answers a member the provider does not provision, whether it exists elsewhere or not.

View Source
var ErrSMTPNotConfigured = apperrors.NotFound("not_found", "no SMTP server is configured")

ErrSMTPNotConfigured is the instance having no SMTP server to read or remove.

View Source
var ErrSessionNotFound = apperrors.NotFound("not_found", "no live session of the member has this identifier")

ErrSessionNotFound answers a session that is not a live one of the member addressed: another member's, one that has ended, or none at all.

View Source
var ErrTokenNotFound = apperrors.NotFound("not_found", "no unrevoked token of the member has this identifier")

ErrTokenNotFound answers a token that is not an unrevoked one of the member addressed: another member's, one revoked already, or none at all.

View Source
var ErrWrongCurrentPassword = apperrors.Invalid("invalid_credentials", "the current password is wrong",
	apperrors.Violation{Pointer: "/current_password", Code: "invalid_credentials", Detail: "the current password is wrong"})

ErrWrongCurrentPassword refuses a password change whose current password is wrong, with the code a wrong sign-in gets, as a violation of the field that holds it. It is no 401: the caller is signed in and stays so, and a 401 would send the console to its sign-in page.

Functions

func ActorOf

func ActorOf(caller access.Caller) governance.Actor

ActorOf returns the actor audit entries name for a change caller makes: the token presented, with the member it acts for, or the member signed in. A caller without a credential has no actor: the zero one, which no audit entry accepts.

Types

type AcceptInvitation

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

AcceptInvitation lets an invited person set their first password, and signs them in.

func NewAcceptInvitation

func NewAcceptInvitation(d AcceptInvitationDeps) *AcceptInvitation

NewAcceptInvitation returns the handler.

func (*AcceptInvitation) Handle

Handle sets the member's first password, makes them active, consumes their invitations and opens a session, recording member.invitation_accepted and auth.signed_in. An invitation that still grants a role in a project makes the grant, by hand and by the member who invited, and records grant.created in the project's log for that member. The attempt counts as a failure of its source before the secret is looked up, so a source hammering acceptance is throttled with its sign-ins; a throttled source is refused rate_limited before anything else. A secret that opens no invitation keeps its failure and is answered invitation_gone; one that does takes it back, whatever happens next. A password the auth settings refuse the member's email is refused, local_login_disabled or sso_required naming the provider, and the invitation stays open for that provider. The password policy applies (weak_password), before any hash.

type AcceptInvitationCommand

type AcceptInvitationCommand struct {
	Secret   secret.String
	Password secret.String
	// ClientIP and UserAgent describe the device signing in.
	ClientIP  netip.Addr
	UserAgent string
	RequestID string
}

AcceptInvitationCommand is one attempt at accepting an invitation.

type AcceptInvitationDeps

type AcceptInvitationDeps struct {
	Tx    Transactor
	Store AcceptStore
	// Settings give the password policy's minimum length and the timeouts
	// the session opens with.
	Settings AuthSettingsReader
	Hasher   PasswordHasher
	Audit    AuditLog
	Clock    clock.Clock
	IDs      *id.Source
	// Random draws session cookies, which are signed with Key.
	Random io.Reader
	Key    []byte
}

AcceptInvitationDeps are what accepting an invitation works with.

type AcceptStore

type AcceptStore interface {
	InvitationReader
	InvitationStore
	// LockMember returns the member, locked until the unit of work ends;
	// ErrNotFound when none has the identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// LockInvitationByHash returns the invitation, locked until the unit of
	// work ends, and its member; ErrNotFound when none has the hash.
	LockInvitationByHash(ctx context.Context, hash access.InvitationHash) (access.Invitation, access.Member, error)
	SaveMember(ctx context.Context, m access.Member, at time.Time) error

	SetPasswordHash(ctx context.Context, member access.MemberID, hash string, at time.Time) error
	RecordSignIn(ctx context.Context, member access.MemberID, at time.Time) error

	CreateSession(ctx context.Context, s access.Session) error
	// ReserveSourceAttempt counts a as a failure of its source alone,
	// before what it presents is checked, and returns what it found.
	ReserveSourceAttempt(ctx context.Context, a access.Attempt) (access.Reservation, error)
	// ReleaseAttempt takes back the failure r reserved.
	ReleaseAttempt(ctx context.Context, r access.Reservation) error
	// contains filtered or unexported methods
}

AcceptStore is what accepting an invitation needs.

type AdoptCommand added in v0.3.0

type AdoptCommand struct {
	Provider    ProviderRef
	Member      access.MemberID
	Email       string
	DisplayName string
	ExternalID  string
	Request     governance.Request
}

AdoptCommand makes a member the instance already holds a member of provider.

type AfterCommit added in v0.3.0

type AfterCommit interface {
	// AfterCommit calls fn with the context the unit of work was given,
	// without the unit of work itself: it has ended, and fn's statements
	// run on their own.
	AfterCommit(ctx context.Context, fn func(committed context.Context))
}

AfterCommit runs a function once the unit of work a context carries has committed, and never if it rolls back.

type AttemptStore

type AttemptStore interface {
	// ReserveAttempt counts a as a failure before its password is verified,
	// in one atomic step, and returns what it found: from a source known to
	// the email's member, it is counted under the email and that source
	// rather than the email alone.
	ReserveAttempt(ctx context.Context, a access.Attempt) (access.Reservation, error)
	// ClearAttempt takes back the failure r reserved, and ends the
	// consecutive failures it was counted under, once the password proved
	// right.
	ClearAttempt(ctx context.Context, r access.Reservation) error
	// ReleaseAttempt takes back the failure r reserved when the attempt
	// guessed nothing: its password could not be verified, or proved right.
	ReleaseAttempt(ctx context.Context, r access.Reservation) error
}

AttemptStore counts the failed attempts at a password, per email and per source, which lock an email and throttle a source.

type AuditLog

type AuditLog interface {
	Record(ctx context.Context, e governance.Entry) error
}

AuditLog records the audit entry of a change, in the unit of work of the change.

type AuthPurged

type AuthPurged struct {
	Sessions            int
	EmailFailures       int
	SourceFailures      int
	KnownSourceFailures int
	KnownSources        int
	Invitations         int
	PasswordResets      int
}

AuthPurged counts the rows one purge deleted.

type AuthRetentionStore

type AuthRetentionStore interface {
	// TryLockAuthRetention takes, until the transaction ends, the lock that
	// lets one replica purge at a time; false when another holds it.
	TryLockAuthRetention(ctx context.Context) (bool, error)
	// PurgeSessions deletes at most limit sessions the cutoffs end.
	PurgeSessions(ctx context.Context, cut access.SessionCutoffs, limit int) (int, error)
	// PurgeEmailFailures deletes at most limit emails' failures that no lock
	// holds and whose last failure is past the cutoff.
	PurgeEmailFailures(ctx context.Context, cut access.FailureCutoffs, limit int) (int, error)
	// PurgeSourceFailures deletes at most limit sources' failures whose
	// window is over.
	PurgeSourceFailures(ctx context.Context, cut access.FailureCutoffs, limit int) (int, error)
	// PurgeKnownSourceFailures deletes at most limit failures of emails from
	// their members' known sources that no lock holds and whose last
	// failure is past the cutoff.
	PurgeKnownSourceFailures(ctx context.Context, cut access.FailureCutoffs, limit int) (int, error)
	// PurgeKnownSources deletes at most limit sources their members last
	// signed in from at or before the cutoff, which are no longer known.
	PurgeKnownSources(ctx context.Context, cut access.FailureCutoffs, limit int) (int, error)
	// PurgeInvitations deletes at most limit invitations that ended at or
	// before the cutoff, except each member's latest.
	PurgeInvitations(ctx context.Context, cut access.InvitationCutoffs, limit int) (int, error)
	// PurgePasswordResets deletes at most limit password resets that ended
	// at or before the cutoff.
	PurgePasswordResets(ctx context.Context, cut access.PasswordResetCutoffs, limit int) (int, error)
}

AuthRetentionStore deletes what signing in leaves behind once it can no longer matter.

type AuthSettingsCache

type AuthSettingsCache interface {
	// Forget drops the copy, so the replica's next read sees a change it
	// just made.
	Forget()
}

AuthSettingsCache is a replica's copy of the settings.

type AuthSettingsReader

type AuthSettingsReader interface {
	AuthSettings(ctx context.Context) (access.AuthSettings, error)
}

AuthSettingsReader reads the auth settings in force.

type AuthSettingsStore

type AuthSettingsStore interface {
	// LockAuthSettings returns the settings and locks them until the
	// transaction ends.
	LockAuthSettings(ctx context.Context) (access.AuthSettings, error)
	// SaveAuthSettings stores the settings and announces the change to
	// every replica once the transaction commits.
	SaveAuthSettings(ctx context.Context, s access.AuthSettings) error
	// RevokeRefusedSessions ends, at at, every session not ended yet that
	// the settings s no longer let sign its member in (see
	// AuthSettings.SessionRefusal), and returns how many it ended.
	RevokeRefusedSessions(ctx context.Context, s access.AuthSettings, at time.Time) (int, error)
}

AuthSettingsStore keeps the auth settings.

type AuthenticateSession

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

AuthenticateSession resolves a session cookie into the member signed in.

func NewAuthenticateSession

func NewAuthenticateSession(store SessionStore, settings AuthSettingsReader, c clock.Clock, key []byte) *AuthenticateSession

NewAuthenticateSession returns the handler, which checks cookies' tags under key and judges sessions by the timeouts settings holds.

func (*AuthenticateSession) Handle

func (h *AuthenticateSession) Handle(ctx context.Context, cookie string) (access.Caller, error)

Handle returns the caller signed in to the session cookie names: ErrNoSession for a cookie the server did not issue, found without a lookup, and session_expired for a session that no longer signs anyone in. A live session's last request is written at most once a minute.

type AuthenticateToken

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

AuthenticateToken resolves the value of an API token presented as Bearer into the caller presenting it.

func NewAuthenticateToken

func NewAuthenticateToken(store TokenStore, uses *TokenUses, c clock.Clock) *AuthenticateToken

NewAuthenticateToken returns the handler, which notes each token's use in uses.

func (*AuthenticateToken) Handle

func (h *AuthenticateToken) Handle(ctx context.Context, value string, ip netip.Addr) (access.Caller, error)

Handle returns the caller presenting value from the address ip, or the refusal a script tells apart: invalid_token for a value that is malformed or unknown alike, token_revoked, token_expired. A token accepted has its use noted.

type Background added in v0.3.0

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

Background runs work that outlives the request that caused it, such as a mail or the part of a request that must not be felt by whoever asked, and is awaited when the replica stops, so what the requests caused leaves with it.

func NewBackground added in v0.3.0

func NewBackground(logger *slog.Logger, opts ...BackgroundOption) *Background

NewBackground returns the runner, which logs a job's panic to logger.

func (*Background) Go added in v0.3.0

func (b *Background) Go(ctx context.Context, name string, bound time.Duration, fn func(ctx context.Context)) bool

Go runs fn in a goroutine of its own, bounded by bound, with the values of ctx but not its cancellation: the request that started it ends first. A job started while the limit of jobs is running is dropped, logged and counted, and Go reports false: shedding the work is what keeps a flood from exhausting the database connections the jobs hold.

func (*Background) Wait added in v0.3.0

func (b *Background) Wait(ctx context.Context)

Wait returns once every job started so far, and every job those start while they run, has ended, or ctx ends. A replica stopping calls it after its requests are done.

type BackgroundOption added in v0.3.0

type BackgroundOption func(*Background)

BackgroundOption adjusts a runner.

func WithBackgroundLimit added in v0.3.0

func WithBackgroundLimit(n int) BackgroundOption

WithBackgroundLimit sets the most jobs running at once; n below one leaves the default.

func WithDroppedCounter added in v0.3.0

func WithDroppedCounter(count func(name string)) BackgroundOption

WithDroppedCounter calls count with the name of every job dropped for want of room.

type Bootstrap

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

Bootstrap creates the first instance admin of a fresh instance, with a password and a personal access token, so a platform engineer gets in without the console.

func NewBootstrap

func NewBootstrap(tx Transactor, store BootstrapStore, hasher PasswordHasher, audit AuditLog, c clock.Clock, ids *id.Source, random io.Reader) *Bootstrap

NewBootstrap returns the handler. random is the source token values and generated passwords are drawn from.

func (*Bootstrap) Handle

Handle creates the instance admin and their token, carrying every scope and no expiry: whoever runs bootstrap holds the database's credentials already, so the token gives them nothing they lack.

type BootstrapCommand

type BootstrapCommand struct {
	Email string
	// DisplayName is "" to name the member after their email's local part.
	DisplayName string
	// Password is the instance admin's password, or zero to have one
	// generated: unattended provisioning need not invent one.
	Password secret.String
	// Request names who bootstraps, for the audit entries.
	Request governance.Request
}

BootstrapCommand names the first instance admin.

type BootstrapResult

type BootstrapResult struct {
	Member access.Member
	Token  secret.String
	// GeneratedPassword is the password generated for a command that gave
	// none, shown once; zero when the command gave one.
	GeneratedPassword secret.String
}

BootstrapResult is the instance admin created and their token's value, which is shown once and never stored.

type BootstrapStore

type BootstrapStore interface {
	InstanceAdmins
	// AuthSettingsReader gives the password policy's minimum length.
	AuthSettingsReader
	// LockBootstrap serializes bootstraps until the unit of work ends, so two
	// running at once cannot both find no instance admin.
	LockBootstrap(ctx context.Context) error
	CreateMember(ctx context.Context, m access.Member, passwordHash string) error
	CreateToken(ctx context.Context, t access.APIToken) error
}

BootstrapStore is what bootstrapping needs of the stored members and tokens.

type ChangeMyPassword

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

ChangeMyPassword lets a signed-in member set a new password.

func NewChangeMyPassword

func NewChangeMyPassword(d ChangeMyPasswordDeps) *ChangeMyPassword

NewChangeMyPassword returns the handler.

func (*ChangeMyPassword) Handle

Handle sets the caller's new password, revokes every other live session of theirs and consumes their open invitations and password resets, in one unit of work, and records password.changed with how many sessions it revoked. The session the caller is signed in to stays.

The new password is held to the policy (weak_password at /new_password) before the current one is checked, so a weak one costs no attempt. The current one is checked as a sign-in checks a password, counting against the member's email and the source, or, from a source the member signed in from lately, against the email from that source alone: a right one takes the failure back, a wrong one keeps it and is refused invalid_credentials, so a session left open on a shared device cannot be used to guess the password, and the email, or its known source, locks after the same failures a sign-in locks it after, recording auth.locked_out.

type ChangeMyPasswordCommand

type ChangeMyPasswordCommand struct {
	Caller          access.Caller
	CurrentPassword secret.String
	NewPassword     secret.String
	// ClientIP is the source of the attempt, which a wrong current password
	// counts against.
	ClientIP netip.Addr
	Request  governance.Request
}

ChangeMyPasswordCommand is one attempt at changing one's password.

type ChangeMyPasswordDeps

type ChangeMyPasswordDeps struct {
	Tx    Transactor
	Store PasswordChangeStore
	// Settings give the password policy's minimum length and the timeouts
	// that tell the live sessions from the ended ones.
	Settings AuthSettingsReader
	Hasher   PasswordVerifier
	Audit    AuditLog
	Clock    clock.Clock
	IDs      *id.Source
}

ChangeMyPasswordDeps are what changing one's password works with.

type CompletePasswordReset added in v0.3.0

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

CompletePasswordReset lets a member set a new password with a password reset, and signs them in.

func NewCompletePasswordReset added in v0.3.0

func NewCompletePasswordReset(d CompletePasswordResetDeps) *CompletePasswordReset

NewCompletePasswordReset returns the handler.

func (*CompletePasswordReset) Handle added in v0.3.0

Handle sets the member's new password, clears the lockout of their email, revokes every session of theirs, ends every open password reset and invitation of theirs, this one included, and opens a session, in one unit of work, recording password.reset and auth.signed_in. The attempt counts as a failure of its source before the secret is looked up, so a source hammering completion is throttled with its sign-ins; a throttled source is refused rate_limited before anything else. A secret that opens no password reset keeps its failure and is answered reset_gone; one that does takes it back, whatever happens next. A password the auth settings refuse the member's email is refused, local_login_disabled or sso_required naming the provider, and the reset stays open. The password policy applies (weak_password), before any hash.

type CompletePasswordResetCommand added in v0.3.0

type CompletePasswordResetCommand struct {
	Secret   secret.String
	Password secret.String
	// ClientIP and UserAgent describe the device signing in.
	ClientIP  netip.Addr
	UserAgent string
	RequestID string
}

CompletePasswordResetCommand is one attempt at completing a password reset.

type CompletePasswordResetDeps added in v0.3.0

type CompletePasswordResetDeps struct {
	Tx    Transactor
	Store CompletePasswordResetStore
	// Settings give the password policy's minimum length and the timeouts
	// the session opens with.
	Settings AuthSettingsReader
	Hasher   PasswordHasher
	Audit    AuditLog
	Clock    clock.Clock
	IDs      *id.Source
	// Random draws session cookies, which are signed with Key.
	Random io.Reader
	Key    []byte
}

CompletePasswordResetDeps are what completing a password reset works with.

type CompletePasswordResetStore added in v0.3.0

type CompletePasswordResetStore interface {
	PasswordResetReader
	PasswordResetStore
	InvitationStore
	// LockMember returns the member, locked until the unit of work ends;
	// ErrNotFound when none has the identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// LockPasswordResetByHash returns the password reset, locked until the
	// unit of work ends, and its member; ErrNotFound when none has the hash.
	LockPasswordResetByHash(ctx context.Context, hash access.PasswordResetHash) (access.PasswordReset, access.Member, error)
	SetPasswordHash(ctx context.Context, member access.MemberID, hash string, at time.Time) error
	// RevokeMemberSessions ends every session of member not ended yet, and
	// returns how many it ended.
	RevokeMemberSessions(ctx context.Context, member access.MemberID, at time.Time) (int, error)
	// ClearSignInFailures ends the consecutive failed sign-ins counted
	// under email, which lifts any lockout of it.
	ClearSignInFailures(ctx context.Context, email string) error
	RecordSignIn(ctx context.Context, member access.MemberID, at time.Time) error

	CreateSession(ctx context.Context, s access.Session) error
	// ReserveSourceAttempt counts a as a failure of its source alone,
	// before what it presents is checked, and returns what it found.
	ReserveSourceAttempt(ctx context.Context, a access.Attempt) (access.Reservation, error)
	// ReleaseAttempt takes back the failure r reserved.
	ReleaseAttempt(ctx context.Context, r access.Reservation) error
	// contains filtered or unexported methods
}

CompletePasswordResetStore is what completing a password reset needs.

type ConfigureSMTP added in v0.3.0

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

ConfigureSMTP sets the SMTP server the instance mails through.

func NewConfigureSMTP added in v0.3.0

func NewConfigureSMTP(d ConfigureSMTPDeps) *ConfigureSMTP

NewConfigureSMTP returns the handler.

func (*ConfigureSMTP) Handle added in v0.3.0

Handle checks the change, seals a new password, replaces the settings and records smtp.updated with the settings before and after, the password only as password_set. An omitted password stays as stored while the host, port, security and username stay as they are, and is refused otherwise; a change dropping the username drops the password with it. A change leaving the settings as they are stores and records nothing. It refuses base_url_required before anything else while the instance has no public address.

type ConfigureSMTPDeps added in v0.3.0

type ConfigureSMTPDeps struct {
	Tx    Transactor
	Store SMTPStore
	Cache SMTPCache
	// Sealer seals the password.
	Sealer Sealer
	Audit  AuditLog
	Clock  clock.Clock
	IDs    *id.Source
	// BaseURLSet is whether the instance knows its public address
	// (FLAGNETIC_BASE_URL): without it no mailed link could be followed.
	BaseURLSet bool
}

ConfigureSMTPDeps are what ConfigureSMTP needs.

type CountProjectMembers

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

CountProjectMembers answers how many members work in projects.

func NewCountProjectMembers

func NewCountProjectMembers(store ProjectMemberDirectory) *CountProjectMembers

NewCountProjectMembers returns the query.

func (*CountProjectMembers) Handle

Handle returns how many active members hold a grant in each of projects, whatever their number, at the cost of one query; a project none holds is absent.

type CreateGrant

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

CreateGrant grants a member a role in a project.

func NewCreateGrant

func NewCreateGrant(tx Transactor, store GrantStore, audit AuditLog, c clock.Clock, ids *id.Source) *CreateGrant

NewCreateGrant returns the handler.

func (*CreateGrant) Handle

Handle makes the grant and records grant.created in the project. A role holding a permission the caller lacks in the project is refused role_not_allowed, an unknown member or role invalid_grant, a deactivated member member_deactivated, a grant the member holds already already_granted.

type CreateGrantCommand

type CreateGrantCommand struct {
	Caller  access.Caller
	Project ProjectRef
	Member  access.MemberID
	Role    access.RoleName
	Request governance.Request
}

CreateGrantCommand grants Member the role Role in Project.

type CreateInstanceAdmin

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

CreateInstanceAdmin adds an instance admin with a password from the command line, for a second admin or one who lost their way in.

func NewCreateInstanceAdmin

func NewCreateInstanceAdmin(tx Transactor, store MemberStore, hasher PasswordHasher, audit AuditLog, c clock.Clock,
	ids *id.Source, random io.Reader,
) *CreateInstanceAdmin

NewCreateInstanceAdmin returns the handler. random is the source generated passwords are drawn from.

func (*CreateInstanceAdmin) Handle

Handle creates the active instance admin. A password the command gives is refused weak_password before it is hashed; an email the instance holds is refused already_exists.

type CreateInstanceAdminCommand

type CreateInstanceAdminCommand struct {
	Email string
	// DisplayName is "" to name the member after their email's local part.
	DisplayName string
	// Password is checked against the password policy, or zero to have one
	// generated.
	Password secret.String
	Request  governance.Request
}

CreateInstanceAdminCommand names the instance admin to create.

type CreateInstanceAdminResult

type CreateInstanceAdminResult struct {
	Member            access.Member
	GeneratedPassword secret.String
}

CreateInstanceAdminResult is the instance admin created and the password generated for a command that gave none, shown once.

type CreatePersonalToken

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

CreatePersonalToken creates a personal access token for the member signed in.

func NewCreatePersonalToken

func NewCreatePersonalToken(tx Transactor, store PersonalTokenStore, settings AuthSettingsReader, audit AuditLog, c clock.Clock,
	ids *id.Source, random io.Reader,
) *CreatePersonalToken

NewCreatePersonalToken returns the handler; random draws token values.

func (*CreatePersonalToken) Handle

Handle creates the token and records api_token.created with its hint. Only a session creates one, so a leaked token can neither multiply itself nor outlive its revocation; its scopes are those the session's member holds, and its expiry is within what the auth settings allow. The member is locked and read again before the token is stored, the order deactivating takes: a token created while the member is deactivated would survive the revocation of their tokens and live again on reactivation, so a member no longer active is refused session_expired.

type CreatePersonalTokenCommand

type CreatePersonalTokenCommand struct {
	Caller    access.Caller
	Name      string
	Scopes    []access.Scope
	ExpiresAt *time.Time
	Request   governance.Request
}

CreatePersonalTokenCommand is a member asking for a personal access token.

type CreateProjectToken

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

CreateProjectToken creates a token belonging to a project, for a pipeline.

func NewCreateProjectToken

func NewCreateProjectToken(tx Transactor, store ProjectTokenStore, settings AuthSettingsReader, audit AuditLog, c clock.Clock,
	ids *id.Source, random io.Reader,
) *CreateProjectToken

NewCreateProjectToken returns the handler; random draws token values.

func (*CreateProjectToken) Handle

Handle creates the token and records api_token.created in its project, with its hint. Only a session creates one, so no token can mint another; a session holds every scope a project token may carry, which never includes instance:admin, so only its role is capped, by what the caller may hand out in the project; its expiry is within what the auth settings allow. It acts for no member and survives its creator.

type CreateProjectTokenCommand

type CreateProjectTokenCommand struct {
	Caller    access.Caller
	Project   ProjectRef
	Name      string
	Role      access.RoleName
	Scopes    []access.Scope
	ExpiresAt *time.Time
	Request   governance.Request
}

CreateProjectTokenCommand asks for a token of Project holding Role.

type CreatedToken

type CreatedToken struct {
	Token access.APIToken
	Value secret.String
}

CreatedToken is a token just created, with its value, shown this once.

type DeactivateMember

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

DeactivateMember offboards a member.

func NewDeactivateMember

func NewDeactivateMember(tx Transactor, store DeactivationStore, audit AuditLog, c clock.Clock, ids *id.Source) *DeactivateMember

NewDeactivateMember returns the handler.

func (*DeactivateMember) Handle

Handle deactivates the member and, in the same unit of work, revokes every session and personal access token they hold and consumes their open invitations and password resets, recording member.deactivated with how many sessions and tokens it revoked. The invitations they issued lose their grants, recorded as invitation.grant_revoked, and still activate whoever accepts them. A deactivated member is left as they are; the last active instance admin is refused last_instance_admin.

type DeactivationStore

type DeactivationStore interface {
	MemberChanger
	// RevokeMemberSessions ends every session of member not ended yet, and
	// returns how many it ended.
	RevokeMemberSessions(ctx context.Context, member access.MemberID, at time.Time) (int, error)
	// RevokePersonalTokens revokes every personal access token of member
	// not revoked yet, and returns how many it revoked. The project tokens
	// the member created belong to their projects and stay.
	RevokePersonalTokens(ctx context.Context, member access.MemberID, at time.Time) (int, error)
	InvitationStore
	PasswordResetStore
	InvitationGrantStore
}

DeactivationStore is what offboarding a member needs.

type DeleteGrant

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

DeleteGrant removes one grant, leaving the member's others.

func NewDeleteGrant

func NewDeleteGrant(tx Transactor, store GrantStore, audit AuditLog, c clock.Clock, ids *id.Source) *DeleteGrant

NewDeleteGrant returns the handler.

func (*DeleteGrant) Handle

func (h *DeleteGrant) Handle(ctx context.Context, cmd DeleteGrantCommand) error

Handle removes the grant and records grant.deleted in the project. The grant of a role holding a permission the caller lacks in the project is refused role_not_allowed, so nobody narrows access beyond their own reach; the grant of an auth provider's group mapping is refused sso_sourced, since the directory owns it; an unknown grant is ErrGrantNotFound. Removing the last owner grant is allowed: an instance admin can always step in. A member left without grant.manage in the project loses the grant of each invitation they issued to it, recorded as invitation.grant_revoked.

type DeleteGrantCommand

type DeleteGrantCommand struct {
	Project ProjectRef
	Grant   access.GrantID
	Request governance.Request
}

DeleteGrantCommand removes the grant Grant of Project.

type DisabledWebhook added in v0.3.0

type DisabledWebhook struct {
	// ID is the subscription's identifier, as its address in the console
	// spells it.
	ID   string
	Name string
	// Project is the subscription's project, zero for the instance's.
	Project workspace.ProjectID
	// Reason is the subscription's disabled reason.
	Reason string
}

DisabledWebhook is a subscription the platform disabled.

type EnforcementProvider added in v0.3.0

type EnforcementProvider struct {
	Enabled bool
	// Domains are the email domains the provider vouches for, lowercase.
	Domains []string
}

EnforcementProvider is an auth provider as enforcing a domain to it asks: whether it is enabled and the domains it vouches for.

type EnforcementProviders added in v0.3.0

type EnforcementProviders interface {
	// EnforcementProvider returns the provider with the slug; false when
	// none has it.
	EnforcementProvider(ctx context.Context, slug string) (EnforcementProvider, bool, error)
}

EnforcementProviders is what the access context asks of the identity context about the auth providers enforced domains name.

type GetAuthSettings

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

GetAuthSettings answers the auth settings in force.

func NewGetAuthSettings

func NewGetAuthSettings(settings AuthSettingsReader) *GetAuthSettings

NewGetAuthSettings returns the query.

func (*GetAuthSettings) Handle

Handle returns the settings.

type GetInvitation

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

GetInvitation answers what an invitation's link opens, before anyone is signed in.

func NewGetInvitation

func NewGetInvitation(store InvitationReader, settings AuthSettingsReader, c clock.Clock) *GetInvitation

NewGetInvitation returns the query; settings tell whether a password may accept the invitation.

func (*GetInvitation) Handle

Handle returns the invitation the secret opens; invitation_gone when it opens none that can be accepted, whatever the reason.

type GetMember

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

GetMember answers one member.

func NewGetMember

func NewGetMember(store MemberDirectory) *GetMember

NewGetMember returns the query.

func (*GetMember) Handle

func (h *GetMember) Handle(ctx context.Context, member access.MemberID) (MemberView, error)

Handle returns the member; ErrMemberNotFound when none has the identifier.

type GetPasswordReset added in v0.3.0

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

GetPasswordReset answers what a password reset's link opens, before anyone is signed in.

func NewGetPasswordReset added in v0.3.0

func NewGetPasswordReset(store PasswordResetReader, c clock.Clock) *GetPasswordReset

NewGetPasswordReset returns the query.

func (*GetPasswordReset) Handle added in v0.3.0

Handle returns the password reset the secret opens; reset_gone when it opens none that can be completed, whatever the reason.

type GetSMTP added in v0.3.0

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

GetSMTP answers the SMTP settings in force.

func NewGetSMTP added in v0.3.0

func NewGetSMTP(settings SMTPReader) *GetSMTP

NewGetSMTP returns the query.

func (*GetSMTP) Handle added in v0.3.0

func (h *GetSMTP) Handle(ctx context.Context) (access.SMTPSettings, error)

Handle returns the settings, ErrSMTPNotConfigured when there are none.

type GetSignInRules added in v0.3.0

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

GetSignInRules answers how the sign-in page offers to sign in.

func NewGetSignInRules added in v0.3.0

func NewGetSignInRules(settings AuthSettingsReader, smtp SMTPReader) *GetSignInRules

NewGetSignInRules returns the query.

func (*GetSignInRules) Handle added in v0.3.0

func (q *GetSignInRules) Handle(ctx context.Context, email string) (SignInRules, error)

Handle returns the rules for email, "" for anybody. They are judged from the email's domain alone, so they never tell whether a member holds it. A reset by mail is available when the instance has an SMTP server, lets members ask, and accepts a password from the email: local login is on and its domain is not enforced. A reset that could not be completed is never offered.

type GrantReader

type GrantReader interface {
	// MemberGrants returns the grants member holds in project, oldest
	// first.
	MemberGrants(ctx context.Context, member access.MemberID, project workspace.ProjectID) ([]access.Grant, error)
	// GrantedProjects returns the projects member holds a grant in.
	GrantedProjects(ctx context.Context, member access.MemberID) ([]workspace.ProjectID, error)
}

GrantReader reads the grants members hold.

type GrantStore

type GrantStore interface {
	InvitationGrantStore
	// LockMember returns the member, locked until the unit of work ends,
	// and whether they hold a password; ErrNotFound when none has the
	// identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// MemberByID returns the member with the identifier; ErrNotFound when
	// none has it.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
	// ProjectGrants returns every grant of project, oldest first.
	ProjectGrants(ctx context.Context, project workspace.ProjectID) ([]access.Grant, error)
	// CreateGrant stores g; one the member holds already from the same
	// source is refused already_granted.
	CreateGrant(ctx context.Context, g access.Grant) error
	// LockGrant returns the grant of project with the identifier, locked
	// until the unit of work ends; ErrNotFound when the project holds none.
	LockGrant(ctx context.Context, project workspace.ProjectID, grant access.GrantID) (access.Grant, error)
	// DeleteGrant removes the grant of project with the identifier.
	DeleteGrant(ctx context.Context, project workspace.ProjectID, grant access.GrantID) (access.Grant, error)
}

GrantStore keeps the grants of projects.

type GrantingInvitation added in v0.3.0

type GrantingInvitation struct {
	Invitation access.Invitation
	Member     access.Member
}

GrantingInvitation is an invitation that grants a role in a project, with the member it invites.

type IdentityDirectory added in v0.3.0

type IdentityDirectory interface {
	// MemberIdentities returns the identities member holds, whether or not
	// their auth provider is enabled.
	MemberIdentities(ctx context.Context, member access.MemberID) ([]access.IdentityMethod, error)
}

IdentityDirectory is what the access context asks of the identity context about the identities members hold.

type InstanceAdminExists

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

InstanceAdminExists answers whether the instance has an instance admin, so provisioning that bootstraps on every deploy learns there is nothing to do before it prepares anything.

func NewInstanceAdminExists

func NewInstanceAdminExists(store InstanceAdmins) *InstanceAdminExists

NewInstanceAdminExists returns the handler.

func (*InstanceAdminExists) Handle

func (h *InstanceAdminExists) Handle(ctx context.Context) (bool, error)

Handle reports whether an instance admin exists.

type InstanceAdmins

type InstanceAdmins interface {
	// AnyInstanceAdmin reports whether an instance admin exists, whatever
	// their status.
	AnyInstanceAdmin(ctx context.Context) (bool, error)
}

InstanceAdmins tells whether the instance has an instance admin.

type InvitationDetails added in v0.3.0

type InvitationDetails struct {
	// ProjectKey and ProjectName name the project the invitation grants a
	// role in; "" when it grants none.
	ProjectKey  string
	ProjectName string
	// InvitedBy is the display name of whoever issued the invitation.
	InvitedBy string
	// InviterLocale is the language whoever issued the invitation chose, ""
	// when they chose none or none issued it.
	InviterLocale string
}

InvitationDetails are what an invitation's page shows besides its member.

type InvitationDetailsReader added in v0.3.0

type InvitationDetailsReader interface {
	// InvitationDetails returns what the page of the invitation shows
	// besides its member; ErrNotFound when none has the identifier.
	InvitationDetails(ctx context.Context, invitation access.InvitationID) (InvitationDetails, error)
}

InvitationDetailsReader reads what an invitation's mail and page name besides its member.

type InvitationGrantStore added in v0.3.0

type InvitationGrantStore interface {
	// PendingInvitation returns the latest invitation of member not consumed
	// yet, expired or not, locked until the unit of work ends; ErrNotFound
	// when the member has none.
	PendingInvitation(ctx context.Context, member access.MemberID) (access.Invitation, error)
	// GrantingInvitations returns the invitations issued by inviter, not
	// consumed yet, that grant a role in project, or in any project when it
	// is zero, each with its member, locked until the unit of work ends.
	GrantingInvitations(ctx context.Context, inviter access.MemberID, project workspace.ProjectID) ([]GrantingInvitation, error)
	// DropInvitationGrant clears the project and role of the invitation,
	// which still activates its member.
	DropInvitationGrant(ctx context.Context, invitation access.InvitationID) error
	// MemberGrants returns the grants member holds in project, oldest
	// first.
	MemberGrants(ctx context.Context, member access.MemberID, project workspace.ProjectID) ([]access.Grant, error)
}

InvitationGrantStore is what judging whether invitations may still grant what they carry needs.

type InvitationGrantView added in v0.3.0

type InvitationGrantView struct {
	ProjectKey  string
	ProjectName string
	Role        access.RoleName
}

InvitationGrantView is the role in a project an invitation grants.

type InvitationMailData added in v0.3.0

type InvitationMailData struct {
	// URL is the link that opens the invitation, carrying its secret.
	URL string
	// ExpiresAt is when the link stops working.
	ExpiresAt time.Time
	// InvitedBy is the display name of the member who issued the invitation,
	// "" when none did.
	InvitedBy string
	// Project is the name of the project accepting the invitation grants
	// Role in; both are empty when it grants none.
	Project string
	Role    access.RoleName
	// Provider is the display name of the auth provider the invitee's email
	// domain is enforced to, "" when it is not: the mail then offers signing
	// in through it alone and no password.
	Provider string
}

InvitationMailData is what the invitation mail's template reads.

type InvitationMailer added in v0.3.0

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

InvitationMailer mails an invitation to the person it invites whenever the instance can: it has an SMTP server, and knows the address its console is served at, without which the link could only carry whatever address the request claimed to come to. A mailed invitation's link is never shown to whoever issued it, so accepting proves the person holds the address.

func NewInvitationMailer added in v0.3.0

func NewInvitationMailer(postman *Postman, smtp SMTPReader, details InvitationDetailsReader, settings AuthSettingsReader,
	providers ProviderNamer, consoleURL string,
) *InvitationMailer

NewInvitationMailer returns the mailer; settings and providers tell which provider an enforced domain's invitation offers, and consoleURL is the address the console is served at, "" when the instance has none.

type InvitationReader

type InvitationReader interface {
	// InvitationByHash returns the invitation and its member; ErrNotFound
	// when no invitation has the hash.
	InvitationByHash(ctx context.Context, hash access.InvitationHash) (access.Invitation, access.Member, error)
	InvitationDetailsReader
}

InvitationReader finds invitations by the hash of their secret.

type InvitationStore

type InvitationStore interface {
	CreateInvitation(ctx context.Context, inv access.Invitation) error
	// ConsumeInvitations ends every open invitation of member, and returns
	// how many it ended.
	ConsumeInvitations(ctx context.Context, member access.MemberID, at time.Time) (int, error)
}

InvitationStore keeps invitations.

type InvitationView

type InvitationView struct {
	// MaskedEmail is the member's email with most of its local part hidden.
	MaskedEmail string
	// Email is the member's email, which the page never shows: the auth
	// providers that may accept the invitation are those vouching for it.
	Email       string
	DisplayName string
	ExpiresAt   time.Time
	// Grant is the role in a project accepting makes the member hold; nil
	// when the invitation grants nothing, or no longer does.
	Grant *InvitationGrantView
	// InvitedBy is the display name of the member who issued the invitation;
	// "" when none did.
	InvitedBy string
	// PasswordAllowed is whether the invitation can be accepted with a
	// password: local login is on and the email's domain is not enforced.
	PasswordAllowed bool
	// EnforcedProvider is the slug of the auth provider the invited email's
	// domain is enforced to, the only way to accept; "" when it is not.
	EnforcedProvider string
}

InvitationView is what the page an invitation opens shows.

type InviteMember

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

InviteMember invites someone to the instance by email.

func NewInviteMember

func NewInviteMember(tx Transactor, store InviteStore, audit AuditLog, c clock.Clock, ids *id.Source, random io.Reader,
	mailer *InvitationMailer,
) *InviteMember

NewInviteMember returns the handler; random draws invitation secrets and mailer mails them when the instance can.

func (*InviteMember) Handle

Handle creates an invited member and their invitation, recording member.invited, and mails it when the instance can; an email the instance holds is refused already_exists. An instance admin may hold every permission in a project, so the invitation may carry any role of it; a role that is none of the built-in ones is refused invalid_grant.

type InviteMemberCommand

type InviteMemberCommand struct {
	// Caller is the instance admin inviting.
	Caller      access.Caller
	Email       string
	DisplayName string
	// Grant is the role in a project the person is invited with, if any.
	Grant   *access.InvitationGrant
	Request governance.Request
}

InviteMemberCommand names the person to invite.

type InviteStore

type InviteStore interface {
	InvitationStore
	MemberDirectory
	CreateMember(ctx context.Context, m access.Member, passwordHash string) error
}

InviteStore is what inviting someone needs.

type InviteToProject added in v0.3.0

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

InviteToProject invites a person to the instance with a role in a project.

func NewInviteToProject added in v0.3.0

func NewInviteToProject(tx Transactor, store InviteToProjectStore, audit AuditLog, c clock.Clock, ids *id.Source, random io.Reader,
	mailer *InvitationMailer,
) *InviteToProject

NewInviteToProject returns the handler; random draws invitation secrets and mailer mails them when the instance can.

func (*InviteToProject) Handle added in v0.3.0

Handle invites the person to the instance with the role, which accepting the invitation grants them in the project, recording member.invited in the project's log, and mails the invitation, naming the project, the role and the caller, when the instance can. A role holding a permission the caller lacks in the project is refused role_not_allowed. A person the instance holds is refused already_exists, except a member invited who has a pending invitation to this project that the caller issued, or any such when the caller is an instance admin, who is invited again with the new role: a fresh invitation then replaces theirs, recorded as member.invitation_reissued; inviting the address again less than a minute after the last invitation is refused too_many_requests, as each one mails it; an instance that cannot mail has no such interval.

type InviteToProjectCommand added in v0.3.0

type InviteToProjectCommand struct {
	// Caller is the member inviting, who holds grant.manage in Project.
	Caller      access.Caller
	Project     ProjectRef
	Email       string
	DisplayName string
	Role        access.RoleName
	Request     governance.Request
}

InviteToProjectCommand names the person to invite and the role to invite them with.

type InviteToProjectStore added in v0.3.0

type InviteToProjectStore interface {
	InviteStore
	// LockMemberByEmail returns the member whose email is email whatever its
	// case, locked until the unit of work ends; ErrNotFound when there is
	// none.
	LockMemberByEmail(ctx context.Context, email string) (access.Member, error)
	// PendingInvitation returns the latest invitation of member not consumed
	// yet, locked until the unit of work ends; ErrNotFound when the member
	// has none.
	PendingInvitation(ctx context.Context, member access.MemberID) (access.Invitation, error)
}

InviteToProjectStore is what inviting someone to a project needs.

type InvitedMember

type InvitedMember struct {
	Member     MemberView
	Invitation *IssuedInvitation
}

InvitedMember is a member with the invitation just issued to them, if one was.

type IssuePasswordReset added in v0.3.0

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

IssuePasswordReset hands an instance admin a password reset to pass on to an active member.

func NewIssuePasswordReset added in v0.3.0

func NewIssuePasswordReset(tx Transactor, store IssuePasswordResetStore, audit AuditLog, c clock.Clock, ids *id.Source, random io.Reader,
) *IssuePasswordReset

NewIssuePasswordReset returns the handler; random draws reset secrets.

func (*IssuePasswordReset) Handle added in v0.3.0

Handle issues a password reset for the member, recording password.reset_issued without its secret, which the answer carries and nothing else does. An unknown member is not found; one still invited is refused member_not_active, as there is no password to reset until they accept their invitation, and one deactivated member_deactivated. The member's earlier password resets stay open.

type IssuePasswordResetCommand added in v0.3.0

type IssuePasswordResetCommand struct {
	// Caller is the instance admin issuing.
	Caller  access.Caller
	Member  access.MemberID
	Request governance.Request
}

IssuePasswordResetCommand names the member to issue a password reset for.

type IssuePasswordResetStore added in v0.3.0

type IssuePasswordResetStore interface {
	PasswordResetStore
	// LockMember returns the member, locked until the unit of work ends,
	// and whether they hold a password; ErrNotFound when none has the
	// identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
}

IssuePasswordResetStore is what issuing a password reset needs.

type IssuedInvitation

type IssuedInvitation struct {
	access.Invitation
	// Secret is the invitation's secret; empty when the invitation is
	// mailed, as only the mail carries it.
	Secret secret.String
	// Mailed reports whether the link is mailed to the person invited.
	Mailed bool
}

IssuedInvitation is an invitation just issued, with its secret, shown once to whoever issued it unless it is mailed.

type IssuedPasswordReset added in v0.3.0

type IssuedPasswordReset struct {
	access.PasswordReset
	Secret secret.String
}

IssuedPasswordReset is a password reset just issued, with its secret, shown once to whoever issued it.

type ListGrants

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

ListGrants answers the grants of a project.

func NewListGrants

func NewListGrants(store GrantStore) *ListGrants

NewListGrants returns the query.

func (*ListGrants) Handle

func (h *ListGrants) Handle(ctx context.Context, project workspace.ProjectID) ([]access.Grant, error)

Handle returns every grant of project, oldest first.

type ListMembers

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

ListMembers answers the instance's members.

func NewListMembers

func NewListMembers(store MemberDirectory) *ListMembers

NewListMembers returns the query.

func (*ListMembers) Handle

func (h *ListMembers) Handle(ctx context.Context, f MemberFilter) ([]MemberView, error)

Handle returns the members f selects, ordered by email.

type ListPersonalTokens

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

ListPersonalTokens answers a member's personal access tokens.

func NewListPersonalTokens

func NewListPersonalTokens(store PersonalTokenStore) *ListPersonalTokens

NewListPersonalTokens returns the query.

func (*ListPersonalTokens) Handle

func (h *ListPersonalTokens) Handle(ctx context.Context, caller access.Caller, member access.MemberID) ([]access.APIToken, error)

Handle returns the personal access tokens of member, the caller's own when member is zero, the newest first; an unknown member is ErrMemberNotFound.

type ListProjectInvitations added in v0.3.0

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

ListProjectInvitations answers who is invited to a project.

func NewListProjectInvitations added in v0.3.0

func NewListProjectInvitations(store ProjectInvitationDirectory) *ListProjectInvitations

NewListProjectInvitations returns the query.

func (*ListProjectInvitations) Handle added in v0.3.0

Handle returns the members invited to project with the role their pending invitation grants there. A member is listed by their pending invitation alone, as only it can still be accepted: an earlier one granting a role here was replaced, and one whose grant was dropped grants nothing.

type ListProjectMembers

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

ListProjectMembers answers who holds grants in a project.

func NewListProjectMembers

func NewListProjectMembers(store ProjectMemberDirectory) *ListProjectMembers

NewListProjectMembers returns the query.

func (*ListProjectMembers) Handle

Handle returns the members holding grants in project with their grants.

type ListProjectTokens

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

ListProjectTokens answers the tokens of a project.

func NewListProjectTokens

func NewListProjectTokens(store ProjectTokenStore) *ListProjectTokens

NewListProjectTokens returns the query.

func (*ListProjectTokens) Handle

Handle returns every token of project, the newest first.

type ListSessions

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

ListSessions answers the devices a member is signed in on.

func NewListSessions

func NewListSessions(store MemberSessionStore, settings AuthSettingsReader, c clock.Clock) *ListSessions

NewListSessions returns the query.

func (*ListSessions) Handle

func (h *ListSessions) Handle(ctx context.Context, caller access.Caller, member access.MemberID) ([]SessionView, error)

Handle returns the live sessions of member, the caller's own when member is zero, the newest first; the one caller is signed in to is marked current. An unknown member is ErrMemberNotFound.

type Mail added in v0.3.0

type Mail struct {
	Kind access.MailKind
	// To is the recipient.
	To MailRecipient
	// Locale is the language the mail is written in, one of access.MailLocales.
	Locale string
	// Data is what the kind's template reads: the type its kind documents.
	Data any
	// RequestID is the request that caused the mail, for the log, "" when
	// none did.
	RequestID string
	// At is when the mail is written, its Date header.
	At time.Time
}

Mail is one mail to one recipient, before it is written: the kind and the language choose the template, Data fills it.

type MailCounter added in v0.3.0

type MailCounter interface {
	// Count counts one mail of kind with result: "sent", the class of the
	// failure (an access.MailFailure), or "error" when it failed before the
	// exchange with the server began.
	Count(kind access.MailKind, result string)
}

MailCounter counts the mails sent.

type MailError added in v0.3.0

type MailError struct {
	Failure access.MailFailure
	Err     error
}

MailError is a failed send. It never carries the password or the mail.

func (*MailError) Error added in v0.3.0

func (e *MailError) Error() string

func (*MailError) Unwrap added in v0.3.0

func (e *MailError) Unwrap() error

Unwrap returns the cause.

type MailRecipient added in v0.3.0

type MailRecipient struct {
	Name  string
	Email string
}

MailRecipient is who a mail is for.

type MailServer added in v0.3.0

type MailServer struct {
	Host     string
	Port     int
	Security access.SMTPSecurity
	Username string
	Password secret.String
	// From is the sender, one address, optionally with a display name.
	From string
}

MailServer is an SMTP server to send through, its password in the clear.

type Mailer added in v0.3.0

type Mailer interface {
	Send(ctx context.Context, server MailServer, m Mail) error
}

Mailer writes a mail and sends it through a server, returning a *MailError naming the failed step's class when the exchange fails.

type MemberChanger

type MemberChanger interface {
	MemberDirectory
	// LockInstanceAdmins serializes, until the unit of work ends, every
	// change that could leave the instance without an active instance
	// admin, so two of them made at once each see the other's outcome.
	LockInstanceAdmins(ctx context.Context) error
	// LockMember returns the member, locked until the unit of work ends,
	// and whether they hold a password; ErrNotFound when none has the
	// identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// OtherActiveInstanceAdmins counts the active instance admins other
	// than member.
	OtherActiveInstanceAdmins(ctx context.Context, member access.MemberID) (int, error)
	// SaveMember stores m's email, display name, status, instance admin
	// switch and locale; an email another member holds is refused
	// already_exists.
	SaveMember(ctx context.Context, m access.Member, at time.Time) error
}

MemberChanger changes a member under the lock that keeps the instance an active instance admin.

type MemberDirectory

type MemberDirectory interface {
	// Members returns the members f selects, ordered by email, with their
	// project counts read in the same query.
	Members(ctx context.Context, f MemberFilter) ([]MemberView, error)
	// MemberView returns one member; ErrNotFound when none has the
	// identifier.
	MemberView(ctx context.Context, member access.MemberID) (MemberView, error)
}

MemberDirectory reads members as an instance admin sees them.

type MemberFilter

type MemberFilter struct {
	Status access.MemberStatus
	Q      string
}

MemberFilter narrows the members listed: to one status when Status is not "", to those whose email or display name holds Q whatever its case when Q is not "".

type MemberSessionStore

type MemberSessionStore interface {
	// MemberByID returns the member with the identifier; ErrNotFound when
	// none has it.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
	// MemberSessions returns the sessions of member not yet revoked, the
	// newest first.
	MemberSessions(ctx context.Context, member access.MemberID) ([]access.Session, error)
}

MemberSessionStore reads a member's sessions.

type MemberStore

type MemberStore interface {
	CreateMember(ctx context.Context, m access.Member, passwordHash string) error
	// AuthSettingsReader gives the password policy's minimum length.
	AuthSettingsReader
}

MemberStore creates members.

type MemberView

type MemberView struct {
	access.Member
	// LastSignInAt is when the member last signed in; nil until they do.
	LastSignInAt *time.Time
	// ProjectCount is how many projects the member holds a grant in.
	ProjectCount int
}

MemberView is a member as an instance admin sees them.

type Opener added in v0.3.0

type Opener interface {
	Open(purpose secret.Purpose, sealed string, binding secret.Binding) ([]byte, error)
}

Opener opens a value sealed under the instance's secret key.

type Ownership

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

Ownership answers whether a member may be named owner of a flag in a project: someone the project's members can ask before deleting it.

func NewOwnership

func NewOwnership(store OwnershipReader) *Ownership

NewOwnership returns the handler.

func (*Ownership) MayOwn

func (h *Ownership) MayOwn(ctx context.Context, project workspace.ProjectID, member access.MemberID) (bool, error)

MayOwn reports whether member is active and either an instance admin or holds a grant in project. An unknown member may not.

type OwnershipReader

type OwnershipReader interface {
	GrantReader
	// MemberByID returns the member, or ErrNotFound.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
}

OwnershipReader reads what decides whether a member may own a flag.

type PasswordChangeStore

type PasswordChangeStore interface {
	SetPasswordHash(ctx context.Context, member access.MemberID, hash string, at time.Time) error
	MemberSessions(ctx context.Context, member access.MemberID) ([]access.Session, error)
	RevokeSessions(ctx context.Context, sessions []access.SessionID, at time.Time) ([]access.SessionID, error)
	ConsumeInvitations(ctx context.Context, member access.MemberID, at time.Time) (int, error)
	ConsumePasswordResets(ctx context.Context, member access.MemberID, at time.Time) (int, error)
	// contains filtered or unexported methods
}

PasswordChangeStore is what changing one's password needs.

type PasswordHasher

type PasswordHasher interface {
	Hash(ctx context.Context, password secret.String) (string, error)
}

PasswordHasher turns a password into the string stored for it.

type PasswordRemovalStore added in v0.3.0

type PasswordRemovalStore interface {
	WaysInStore
	ClearPasswordHash(ctx context.Context, member access.MemberID, at time.Time) error
	ConsumeInvitations(ctx context.Context, member access.MemberID, at time.Time) (int, error)
	ConsumePasswordResets(ctx context.Context, member access.MemberID, at time.Time) (int, error)
}

PasswordRemovalStore is what removing a password needs.

type PasswordResetMailData added in v0.3.0

type PasswordResetMailData struct {
	// URL is the link that opens the reset, carrying its secret.
	URL string
	// ExpiresAt is when the link stops working.
	ExpiresAt time.Time
}

PasswordResetMailData is what the password reset mail's template reads.

type PasswordResetReader added in v0.3.0

type PasswordResetReader interface {
	// PasswordResetByHash returns the password reset and its member;
	// ErrNotFound when no password reset has the hash.
	PasswordResetByHash(ctx context.Context, hash access.PasswordResetHash) (access.PasswordReset, access.Member, error)
}

PasswordResetReader finds password resets by the hash of their secret.

type PasswordResetStore added in v0.3.0

type PasswordResetStore interface {
	CreatePasswordReset(ctx context.Context, reset access.PasswordReset) error
	// ConsumePasswordResets ends every open password reset of member, and
	// returns how many it ended.
	ConsumePasswordResets(ctx context.Context, member access.MemberID, at time.Time) (int, error)
}

PasswordResetStore keeps password resets.

type PasswordResetView added in v0.3.0

type PasswordResetView struct {
	// MaskedEmail is the member's email with most of its local part hidden.
	MaskedEmail string
	DisplayName string
	ExpiresAt   time.Time
}

PasswordResetView is what the page a password reset opens shows.

type PasswordVerifier

type PasswordVerifier interface {
	PasswordHasher
	// Verify reports whether password matches encoded, and whether encoded
	// was made under parameters other than the current ones. An empty
	// encoded is verified against a hash no password matches, at the same
	// cost, so an unknown email takes as long as a wrong password.
	Verify(ctx context.Context, password secret.String, encoded string) (ok, outdated bool, err error)
}

PasswordVerifier checks a password against the string stored for it.

type PersonalTokenStore

type PersonalTokenStore interface {
	// MemberByID returns the member with the identifier; ErrNotFound when
	// none has it.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
	// LockMember returns the member, locked until the unit of work ends, and
	// whether they hold a password; ErrNotFound when none has the identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// PersonalTokens returns every personal access token of member, revoked
	// and expired ones included, the newest first.
	PersonalTokens(ctx context.Context, member access.MemberID) ([]access.APIToken, error)
	CreateToken(ctx context.Context, t access.APIToken) error
	// RevokePersonalToken revokes the personal access token of member with
	// the identifier at at and returns it as revoked; ErrNotFound unless
	// member holds it unrevoked.
	RevokePersonalToken(ctx context.Context, member access.MemberID, token access.APITokenID, at time.Time) (access.APIToken, error)
}

PersonalTokenStore keeps members' personal access tokens.

type Postman added in v0.3.0

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

Postman sends the instance's mail. A use case queues a mail inside its unit of work and the mail goes out only once that has committed, in the background, so a slow or failing relay never delays or undoes the change that caused it. A mail in flight when the replica dies is lost: every mail has a cheap human retry.

func NewPostman added in v0.3.0

func NewPostman(d PostmanDeps) *Postman

NewPostman returns the service.

func (*Postman) Deliver added in v0.3.0

func (p *Postman) Deliver(ctx context.Context, m Mail) error

Deliver sends m now, through the SMTP server in force, and returns what came of it: ErrSMTPNotConfigured while there is none, a *MailError when the exchange failed. It counts the mail.

func (*Postman) Locale added in v0.3.0

func (p *Postman) Locale(preferred ...string) string

Locale returns the language a mail is written in: the first of preferred that mail is written in, else the instance's default.

func (*Postman) Queue added in v0.3.0

func (p *Postman) Queue(ctx context.Context, m Mail)

Queue sends m once the unit of work ctx carries has committed, in a goroutine bounded by MailBound, with m.At and m.RequestID filled in when the caller left them out. Nothing is sent while the instance has no SMTP server. A failure is logged with the request ID, the kind and the failure class, never the link, and counted; it fails nothing.

func (*Postman) Wait added in v0.3.0

func (p *Postman) Wait(ctx context.Context)

Wait returns once every mail queued so far has been sent or has failed, or ctx ends: it waits on the background the mails are sent in, with whatever else runs there.

type PostmanDeps added in v0.3.0

type PostmanDeps struct {
	Settings SMTPReader
	Opener   Opener
	Mailer   Mailer
	Counter  MailCounter
	After    AfterCommit
	Clock    clock.Clock
	Logger   *slog.Logger
	// Background runs the sends; the replica waits on it when it stops.
	Background *Background
	// DefaultLocale is the language of a mail whose recipient has not chosen
	// one (FLAGNETIC_DEFAULT_LOCALE).
	DefaultLocale string
}

PostmanDeps are what a Postman needs.

type ProjectHoldings

type ProjectHoldings struct {
	// Grants are those the caller's member holds there; none for a project
	// token, which acts for no member.
	Grants []access.Grant
	// Permissions are the caller's effective permissions there, in catalog
	// order.
	Permissions []access.Permission
}

ProjectHoldings are what a caller holds in a project.

type ProjectInvitation added in v0.3.0

type ProjectInvitation struct {
	Member access.Member
	Role   access.RoleName
	// InvitedBy is the member who issued the invitation; zero when none did.
	InvitedBy access.MemberID
	ExpiresAt time.Time
}

ProjectInvitation is a member invited with a role in a project, which their pending invitation grants once accepted.

type ProjectInvitationDirectory added in v0.3.0

type ProjectInvitationDirectory interface {
	// ProjectInvitations returns the invited members whose pending
	// invitation, expired or not, grants a role in project, ordered by
	// email, each with that invitation, read in one query.
	ProjectInvitations(ctx context.Context, project workspace.ProjectID) ([]ProjectInvitation, error)
}

ProjectInvitationDirectory reads who is invited to projects.

type ProjectMember

type ProjectMember struct {
	Member access.Member
	Grants []access.Grant
}

ProjectMember is a member holding grants in a project, with those grants.

type ProjectMemberDirectory

type ProjectMemberDirectory interface {
	// ProjectMembers returns the members holding grants in project, ordered
	// by email, each with their grants there oldest first, read in one
	// query.
	ProjectMembers(ctx context.Context, project workspace.ProjectID) ([]ProjectMember, error)
	// ProjectMemberCounts returns how many active members hold a grant in
	// each of projects, read in one query; a project none holds is absent.
	ProjectMemberCounts(ctx context.Context, projects []workspace.ProjectID) (map[workspace.ProjectID]int, error)
}

ProjectMemberDirectory reads who holds grants in projects.

type ProjectPermissions

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

ProjectPermissions answers what a caller holds in a project: the permission seam judges every operation in a project by it, and the console shows or disables actions by it.

func NewProjectPermissions

func NewProjectPermissions(grants GrantReader) *ProjectPermissions

NewProjectPermissions returns the handler.

func (*ProjectPermissions) Handle

Handle returns the grants of the caller's member in project and the caller's effective permissions there: an instance admin holds every permission, a member the union of their grants' roles, narrowed by the scopes of a token; a project token its role's in its own project.

type ProjectRef

type ProjectRef struct {
	ID workspace.ProjectID
	// Held are the caller's effective permissions in the project, which
	// cap the roles they may hand out.
	Held []access.Permission
}

ProjectRef is the project a command addresses, as the request found it, with what the caller holds there.

type ProjectTokenStore

type ProjectTokenStore interface {
	// ProjectTokens returns every project token of project, revoked and
	// expired ones included, the newest first.
	ProjectTokens(ctx context.Context, project workspace.ProjectID) ([]access.APIToken, error)
	CreateToken(ctx context.Context, t access.APIToken) error
	// RevokeProjectToken revokes the project token of project with the
	// identifier at at and returns it as revoked; ErrNotFound unless the
	// project holds it unrevoked.
	RevokeProjectToken(ctx context.Context, project workspace.ProjectID, token access.APITokenID, at time.Time) (access.APIToken, error)
}

ProjectTokenStore keeps projects' tokens.

type PromoteMember

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

PromoteMember makes a member an instance admin from the command line.

func NewPromoteMember

func NewPromoteMember(tx Transactor, store PromoteStore, audit AuditLog, c clock.Clock, ids *id.Source) *PromoteMember

NewPromoteMember returns the handler.

func (*PromoteMember) Handle

func (h *PromoteMember) Handle(ctx context.Context, email string, req governance.Request) (bool, error)

Handle makes the member with email an instance admin and reports whether they were not one already; promoting an instance admin changes and records nothing.

type PromoteStore

type PromoteStore interface {
	// LockMemberByEmail returns the member whose email is email whatever
	// its case, locked until the unit of work ends; ErrNotFound when none.
	LockMemberByEmail(ctx context.Context, email string) (access.Member, error)
	SetInstanceAdmin(ctx context.Context, member access.MemberID, instanceAdmin bool, at time.Time) error
}

PromoteStore finds a member to promote and makes them an instance admin.

type ProviderAccess added in v0.3.0

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

ProviderAccess makes the grants and the instance admin an auth provider's group mappings give a member, and takes away those it no longer gives. It acts in the unit of work its context carries, so the identity context makes it part of a sign-in or of replacing the mappings.

func NewProviderAccess added in v0.3.0

func NewProviderAccess(store ProviderAccessStore, audit AuditLog, c clock.Clock, ids *id.Source) *ProviderAccess

NewProviderAccess returns the service.

func (*ProviderAccess) KnownRole added in v0.3.0

func (*ProviderAccess) KnownRole(name string) bool

KnownRole reports whether name is one of the built-in roles.

func (*ProviderAccess) Replace added in v0.3.0

Replace makes the grants of the provider's mappings to the member those the command lists, removing the provider's others, and makes them instance admin or no longer, when the provider is the one that made them. Grants of other sources, and an instance admin made by hand or by another provider, are left alone, so each source owns what it granted. A deactivated member keeps none of the provider's grants and gains none. The last active instance admin is never demoted: that is reported, not refused. Every change is recorded for the command's actor, the provider by default. A member who loses grant.manage in a project loses the grant of each invitation they issued to it.

type ProviderAccessCommand added in v0.3.0

type ProviderAccessCommand struct {
	Provider ProviderRef
	Member   access.MemberID
	// Grants are the roles in projects the mappings give, each once.
	Grants        []ProviderRole
	InstanceAdmin bool
	// Actor is who the audit trail names for the changes; the provider when
	// it is the zero actor. A SCIM group change names the SCIM token.
	Actor     governance.Actor
	RequestID string
}

ProviderAccessCommand is the access the provider's mappings give a member now.

type ProviderAccessResult added in v0.3.0

type ProviderAccessResult struct {
	// Granted counts the grants made and the promotions to instance admin,
	// Revoked the grants removed and the demotions.
	Granted, Revoked int
	// KeptInstanceAdmin is whether the member stayed instance admin although
	// the mappings no longer give it, because they are the last active
	// instance admin.
	KeptInstanceAdmin bool
}

ProviderAccessResult is what replacing a member's access changed.

type ProviderAccessStore added in v0.3.0

type ProviderAccessStore interface {
	MemberChanger
	GrantStore
	// ProviderGrants returns the grants the group mappings of the provider
	// with this slug made to member, in every project.
	ProviderGrants(ctx context.Context, member access.MemberID, provider string) ([]access.Grant, error)
}

ProviderAccessStore is what replacing the access an auth provider's group mappings made needs.

type ProviderNamer added in v0.4.0

type ProviderNamer interface {
	// ProviderDisplayName returns the display name of the provider with the
	// slug, and whether one has that slug.
	ProviderDisplayName(ctx context.Context, slug string) (name string, found bool, err error)
}

ProviderNamer names the auth provider an enforced domain sends its members to.

type ProviderRef added in v0.3.0

type ProviderRef struct {
	ID   string
	Slug string
}

ProviderRef names an auth provider: its identifier, which the audit trail names as the actor, and its slug, which grants and members keep.

type ProviderRole added in v0.3.0

type ProviderRole struct {
	Project workspace.ProjectID
	Role    access.RoleName
}

ProviderRole is a role in a project.

type ProvisionCommand added in v0.3.0

type ProvisionCommand struct {
	Provider    ProviderRef
	Email       string
	DisplayName string
	// ExternalID is the provider's identifier of the person, "" for none.
	ExternalID string
	Request    governance.Request
}

ProvisionCommand creates an active member without a password in provider.

type ProvisionedCondition added in v0.3.0

type ProvisionedCondition struct {
	Field ProvisionedField
	Value string
}

ProvisionedCondition is one equality a lookup of provisioned members needs.

type ProvisionedField added in v0.3.0

type ProvisionedField string

ProvisionedField is a member attribute a directory looks members up by.

const (
	// FieldEmail is the member's email, compared whatever its case.
	FieldEmail ProvisionedField = "email"
	// FieldExternalID is the provider's own identifier, compared exactly.
	FieldExternalID ProvisionedField = "external_id"
	// FieldDisplayName is the member's name, compared whatever its case.
	FieldDisplayName ProvisionedField = "display_name"
	// FieldID is the member's identifier.
	FieldID ProvisionedField = "id"
)

The attributes a directory looks provisioned members up by.

type ProvisionedMemberStore added in v0.3.0

type ProvisionedMemberStore interface {
	MemberChanger
	DeactivationStore
	// MemberByID returns the member; ErrNotFound when none has the identifier.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
	// MemberByEmail returns the member whose email is email whatever its
	// case, with their password hash; ErrNotFound when none.
	MemberByEmail(ctx context.Context, email string) (access.Member, string, error)
	// CreateProvisionedMember stores m, a member of a provider, without a
	// password; an email another member holds is refused already_exists, an
	// external ID another member of the provider holds ErrExternalIDTaken.
	CreateProvisionedMember(ctx context.Context, m access.Member, at time.Time) error
	// SaveProvisionedMember stores m's email, display name, status, provider
	// and external ID, refusing as CreateProvisionedMember does.
	SaveProvisionedMember(ctx context.Context, m access.Member, at time.Time) error
	// ProvisionedMembers returns the page of provider's members that satisfy
	// every condition, ordered by email, from the 1-based startIndex, count
	// at most (none when 0), and how many satisfy them in all.
	ProvisionedMembers(ctx context.Context, provider string, conds []ProvisionedCondition, startIndex, count int) ([]access.Member, int, error)
	// ClearPasswordHash removes the password of member.
	ClearPasswordHash(ctx context.Context, member access.MemberID, at time.Time) error
	// ProviderProvisionedMembers reports whether the provider holds a member.
	ProviderProvisionedMembers(ctx context.Context, provider string) (bool, error)
}

ProvisionedMemberStore is what provisioning needs of the stored members.

type Provisioning added in v0.3.0

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

Provisioning is what the identity context asks of the access context to let an identity provider create, adopt, update and deprovision members through SCIM. Each method acts in the unit of work its context carries, so the identity context makes a request's changes in one transaction; members of another provider are never found.

func NewProvisioning added in v0.3.0

func NewProvisioning(tx Transactor, store ProvisionedMemberStore, audit AuditLog, c clock.Clock, ids *id.Source) *Provisioning

NewProvisioning returns the service.

func (*Provisioning) Adopt added in v0.3.0

func (p *Provisioning) Adopt(ctx context.Context, cmd AdoptCommand) (access.Member, error)

Adopt makes the member one of provider's, their email, name and external ID the directory's from now on, and records member.adopted.

func (*Provisioning) Get added in v0.3.0

func (p *Provisioning) Get(ctx context.Context, provider string, member access.MemberID) (access.Member, error)

Get returns the member of provider with the identifier; ErrProvisionedMemberNotFound when none is, whether the member exists elsewhere or not.

func (*Provisioning) List added in v0.3.0

func (p *Provisioning) List(ctx context.Context, provider string, conds []ProvisionedCondition, startIndex, count int) ([]access.Member, int, error)

List returns the page of provider's members that satisfy every condition, and how many satisfy them in all.

func (*Provisioning) MemberByEmail added in v0.3.0

func (p *Provisioning) MemberByEmail(ctx context.Context, email string) (access.Member, bool, error)

MemberByEmail returns the member holding email whatever its case, with whether they hold a password; false when none does.

func (*Provisioning) ProviderHoldsMembers added in v0.3.0

func (p *Provisioning) ProviderHoldsMembers(ctx context.Context, provider string) (bool, error)

ProviderHoldsMembers reports whether provider has provisioned members, which keep it from being deleted.

func (*Provisioning) Provision added in v0.3.0

func (p *Provisioning) Provision(ctx context.Context, cmd ProvisionCommand) (access.Member, error)

Provision creates the member and records member.provisioned. An email another member holds is refused already_exists, an external ID another member of the provider holds ErrExternalIDTaken.

func (*Provisioning) SetActive added in v0.3.0

func (p *Provisioning) SetActive(ctx context.Context, cmd SetActiveCommand) (access.Member, error)

SetActive deactivates the member, ending their sessions, personal tokens, invitations and password resets, or reactivates them, recording member.deactivated or member.reactivated; a member already as asked is left as they are. The last active instance admin is not deactivated. Reactivated, a member of an identity provider is active: the provider is how they sign in.

func (*Provisioning) Update added in v0.3.0

Update changes the member's email, name and external ID and records member.updated with what changed; a request that changes nothing records nothing.

A member moved to another address keeps neither their password nor an open password reset. A password proves its holder once held the old address, and a reset is mailed to whatever address the member has: kept across the move, they would let whoever holds a SCIM token adopt a member, move them to an address of their own and have a reset mailed there, taking the account over without ever signing in at the identity provider. The provider is how its members sign in, so nobody is locked out. A change of case alone is no move.

type PurgeAuthRecords

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

PurgeAuthRecords deletes ended sessions, emails' failures that no longer count, sources' windows that are over, sources no longer known to their members, and invitations and password resets long past use, so their tables do not grow forever.

func NewPurgeAuthRecords

func NewPurgeAuthRecords(tx Transactor, store AuthRetentionStore, settings AuthSettingsReader, c clock.Clock) *PurgeAuthRecords

NewPurgeAuthRecords returns the handler, which ends sessions by the timeouts settings holds.

func (*PurgeAuthRecords) Handle

func (h *PurgeAuthRecords) Handle(ctx context.Context) (AuthPurged, error)

Handle purges in batches, each in a transaction of its own holding the purge lock, until a batch finds less than a full batch to delete. When another replica holds the lock it leaves the work to it and returns what it purged so far.

type ReactivateMember

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

ReactivateMember brings a deactivated member back.

func NewReactivateMember

func NewReactivateMember(tx Transactor, store ReactivationStore, ways *WaysIn, audit AuditLog, c clock.Clock, ids *id.Source,
	random io.Reader, mailer *InvitationMailer,
) *ReactivateMember

NewReactivateMember returns the handler; random draws invitation secrets and mailer mails them when the instance can.

func (*ReactivateMember) Handle

Handle makes a deactivated member active when they hold a usable way to sign in, a password or an identity at an enabled auth provider, recording member.reactivated. One who holds neither is invited again, with a fresh invitation, since the one they had was consumed when they were deactivated, mailed when the instance can. What their deactivation revoked stays revoked. A member who is not deactivated is left as they are.

type ReactivationStore

type ReactivationStore interface {
	MemberChanger
	InvitationStore
}

ReactivationStore is what bringing a member back needs.

type ReissueInvitation

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

ReissueInvitation replaces an invited member's link.

func NewReissueInvitation

func NewReissueInvitation(tx Transactor, store ReissueStore, audit AuditLog, c clock.Clock, ids *id.Source, random io.Reader,
	mailer *InvitationMailer,
) *ReissueInvitation

NewReissueInvitation returns the handler; random draws invitation secrets and mailer mails them when the instance can.

func (*ReissueInvitation) Handle

Handle issues the member a fresh invitation, which kills every earlier one, recording member.invitation_reissued, and mails it when the instance can. A member who is not invited is refused member_not_invited. The fresh invitation is issued by whoever issued the last one, and keeps its grant only while that member still holds grant.manage in its project: a grant lost since is dropped and recorded as invitation.grant_revoked, so reissuing never widens access.

type ReissueStore

type ReissueStore interface {
	InvitationStore
	InvitationGrantStore
	MemberDirectory
	// MemberByID returns the member with the identifier; ErrNotFound when
	// none has it.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
	// LockMember returns the member, locked until the unit of work ends,
	// and whether they hold a password; ErrNotFound when none has the
	// identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
}

ReissueStore is what reissuing an invitation needs.

type RemoveMyPassword added in v0.3.0

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

RemoveMyPassword lets a signed-in member drop their password.

func NewRemoveMyPassword added in v0.3.0

func NewRemoveMyPassword(tx Transactor, store PasswordRemovalStore, ways *WaysIn, audit AuditLog, c clock.Clock, ids *id.Source) *RemoveMyPassword

NewRemoveMyPassword returns the handler.

func (*RemoveMyPassword) Handle added in v0.3.0

Handle removes the caller's password, ends their open invitations and password resets so no old link sets one again, and records password.removed, in one unit of work. It is refused ErrLastAuthMethod when no identity at an enabled auth provider that enforcement allows remains, even while local login or enforcement refuses the password: unlock makes it a way in again. A member who holds no password changes nothing. Only a session removes a password, so a leaked token cannot lock its owner out of signing in with it.

type RemoveMyPasswordCommand added in v0.3.0

type RemoveMyPasswordCommand struct {
	Caller  access.Caller
	Request governance.Request
}

RemoveMyPasswordCommand is one removal.

type RemoveSMTP added in v0.3.0

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

RemoveSMTP removes the SMTP server: the instance stops mailing.

func NewRemoveSMTP added in v0.3.0

func NewRemoveSMTP(tx Transactor, store SMTPStore, cache SMTPCache, audit AuditLog, c clock.Clock, ids *id.Source) *RemoveSMTP

NewRemoveSMTP returns the handler.

func (*RemoveSMTP) Handle added in v0.3.0

func (h *RemoveSMTP) Handle(ctx context.Context, req governance.Request) error

Handle removes the settings and records smtp.deleted with them as they were, ErrSMTPNotConfigured when there are none.

type RequestPasswordReset added in v0.3.0

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

RequestPasswordReset mails a member a link to set a new password, when they ask for one without being signed in.

func NewRequestPasswordReset added in v0.3.0

func NewRequestPasswordReset(d RequestPasswordResetDeps) *RequestPasswordReset

NewRequestPasswordReset returns the handler.

func (*RequestPasswordReset) Handle added in v0.3.0

Handle counts the request against the throttle of its source and starts it, returning before anything is looked up, whatever the email is: neither what comes of the request nor how long it takes tells who holds an account. A source past the throttle is refused rate_limited, whatever the email; every request counts, so a source cannot make the instance mail or audit at wire speed, and the count is kept, as the answer is the same whether or not the email exists. Behind the answer, a password reset is issued and mailed only when the instance has an SMTP server and lets members ask, the email belongs to an active member who holds a password, and the member has not been issued a reset they asked for in the last PasswordResetInterval, whether or not its mail was sent. An email the auth settings refuse a password, while local login is disabled or in an enforced domain, is issued none. Whatever stops it does so silently; a failure is logged, and so is a request dropped because the replica is running too many background jobs.

type RequestPasswordResetCommand added in v0.3.0

type RequestPasswordResetCommand struct {
	Email string
	// ClientIP is the address the request comes from.
	ClientIP  netip.Addr
	RequestID string
}

RequestPasswordResetCommand is one request for a password reset.

type RequestPasswordResetDeps added in v0.3.0

type RequestPasswordResetDeps struct {
	Tx       Transactor
	Store    RequestPasswordResetStore
	Settings AuthSettingsReader
	SMTP     SMTPReader
	Postman  *Postman
	// Throttle is the source throttle sign-in, acceptance and completion
	// share; every request counts against it.
	Throttle *SourceThrottle
	// Background runs the request after its answer.
	Background *Background
	Audit      AuditLog
	Clock      clock.Clock
	IDs        *id.Source
	Random     io.Reader
	Logger     *slog.Logger
	// ConsoleURL is the address the console is served at, "" when the
	// instance has none, which a link cannot be written without: the mail
	// would otherwise carry whatever address the request claimed to come to.
	ConsoleURL string
}

RequestPasswordResetDeps are what asking for a password reset works with.

type RequestPasswordResetStore added in v0.3.0

type RequestPasswordResetStore interface {
	PasswordResetStore
	// MemberByEmail returns the member whose email is email whatever its
	// case, with their password hash ("" for none); ErrNotFound when there
	// is none.
	MemberByEmail(ctx context.Context, email string) (access.Member, string, error)
	// LockMember returns the member, locked until the unit of work ends, and
	// whether they hold a password; ErrNotFound when none has the identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// LatestSelfServicePasswordReset returns when the latest password reset
	// member asked for was issued, open or not; false when they never asked.
	LatestSelfServicePasswordReset(ctx context.Context, member access.MemberID) (time.Time, bool, error)
}

RequestPasswordResetStore is what asking for a password reset needs.

type RevokePersonalToken

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

RevokePersonalToken revokes a personal access token.

func NewRevokePersonalToken

func NewRevokePersonalToken(tx Transactor, store PersonalTokenStore, audit AuditLog, c clock.Clock, ids *id.Source,
) *RevokePersonalToken

NewRevokePersonalToken returns the handler.

func (*RevokePersonalToken) Handle

Handle revokes the token and records api_token.revoked. A member's own tokens are revoked only from a session, whichever route names them, so a leaked token cannot hide its siblings, an instance admin's included; a token the member does not hold unrevoked is ErrTokenNotFound.

type RevokePersonalTokenCommand

type RevokePersonalTokenCommand struct {
	Caller  access.Caller
	Member  access.MemberID
	Token   access.APITokenID
	Request governance.Request
}

RevokePersonalTokenCommand names the token to revoke: one of Member's, or of the caller's own when Member is zero.

type RevokeProjectToken

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

RevokeProjectToken revokes a project's token.

func NewRevokeProjectToken

func NewRevokeProjectToken(tx Transactor, store ProjectTokenStore, audit AuditLog, c clock.Clock, ids *id.Source,
) *RevokeProjectToken

NewRevokeProjectToken returns the handler.

func (*RevokeProjectToken) Handle

Handle revokes the token and records api_token.revoked in its project; a token the project does not hold unrevoked is ErrTokenNotFound.

type RevokeProjectTokenCommand

type RevokeProjectTokenCommand struct {
	Project ProjectRef
	Token   access.APITokenID
	Request governance.Request
}

RevokeProjectTokenCommand names the token of Project to revoke.

type RevokeSessions

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

RevokeSessions signs a member out of some or all of their devices.

func NewRevokeSessions

func NewRevokeSessions(tx Transactor, store SessionRevoker, settings AuthSettingsReader, audit AuditLog, c clock.Clock,
	ids *id.Source,
) *RevokeSessions

NewRevokeSessions returns the handler.

func (*RevokeSessions) Handle

Handle revokes the live sessions cmd selects and records one session.revoked entry naming them; revoking none records nothing. A member's own sessions are revoked only from a session, whichever route names them, so a leaked token cannot sign its owner out, an instance admin's included; a session the member does not hold live is ErrSessionNotFound.

type RevokeSessionsCommand

type RevokeSessionsCommand struct {
	Caller      access.Caller
	Member      access.MemberID
	Session     *access.SessionID
	KeepCurrent bool
	Request     governance.Request
}

RevokeSessionsCommand selects the sessions to revoke: every live one of Member, or of the caller when Member is zero, or only Session when given; the session the caller is signed in to is kept when KeepCurrent is set.

type RevokeSessionsResult

type RevokeSessionsResult struct {
	Revoked []access.SessionID
	// CurrentRevoked is whether the session the caller is signed in to was
	// among them, so its cookie is cleared.
	CurrentRevoked bool
}

RevokeSessionsResult is what a revocation ended.

type SMTPCache added in v0.3.0

type SMTPCache interface {
	// Forget drops the copy, so the replica's next read sees a change it
	// just made.
	Forget()
}

SMTPCache is a replica's copy of the SMTP settings.

type SMTPReader added in v0.3.0

type SMTPReader interface {
	SMTPSettings(ctx context.Context) (access.SMTPSettings, error)
}

SMTPReader reads the SMTP settings in force, ErrSMTPNotConfigured when there are none.

type SMTPStore added in v0.3.0

type SMTPStore interface {
	// LockSMTPSettings returns the settings and locks them until the
	// transaction ends; ErrSMTPNotConfigured when there are none.
	LockSMTPSettings(ctx context.Context) (access.SMTPSettings, error)
	// SaveSMTPSettings stores the settings, replacing any, and announces the
	// change to every replica once the transaction commits.
	SaveSMTPSettings(ctx context.Context, s access.SMTPSettings) error
	// DeleteSMTPSettings removes the settings and announces it likewise.
	DeleteSMTPSettings(ctx context.Context) error
}

SMTPStore keeps the SMTP settings.

type SSO added in v0.3.0

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

SSO is what the identity context asks of the access context to sign a person in through an auth provider: the members it knows, a member provisioned on first sign-in, and the session that opens. Each method acts in the unit of work its context carries, so the identity context makes all of a sign-in's changes in one transaction.

func NewSSO added in v0.3.0

func NewSSO(store SSOStore, settings AuthSettingsReader, audit AuditLog, c clock.Clock, ids *id.Source, random io.Reader, key []byte) *SSO

NewSSO returns the service, whose session cookies are drawn from random and signed with key.

func (*SSO) ActivateInvited added in v0.3.0

func (s *SSO) ActivateInvited(ctx context.Context, in SSOActivation) (access.Member, error)

ActivateInvited makes the invited member active, as accepting their invitation does: their invitations are consumed, and their pending one, while it is open, makes the grant it carries. An expired one activates them all the same, granting nothing: the provider vouching for them proves what the link would have. It records member.invitation_accepted with the method and the provider, by the member. A member who is no longer invited is ErrNotInvited. The member is locked before their invitation, the order accepting and reissuing take.

func (*SSO) EnforcedProvider added in v0.3.0

func (s *SSO) EnforcedProvider(ctx context.Context, email string) (string, error)

EnforcedProvider returns the slug of the auth provider email's domain is enforced to; "" when it is not.

func (*SSO) LockInstanceAdmins added in v0.4.0

func (s *SSO) LockInstanceAdmins(ctx context.Context) error

LockInstanceAdmins serializes, until the unit of work ends, every change that could leave the instance without an active instance admin. It is taken before a member's lock, the order every change of access takes.

func (*SSO) MemberByEmail added in v0.3.0

func (s *SSO) MemberByEmail(ctx context.Context, email string) (access.Member, bool, error)

MemberByEmail returns the member holding email, whatever its case; false when none does.

func (*SSO) MemberByExternalID added in v0.3.0

func (s *SSO) MemberByExternalID(ctx context.Context, provider, externalID string) (access.Member, bool, error)

MemberByExternalID returns the member the provider with this slug provisioned with externalID as their external ID; false when none.

func (*SSO) MemberByID added in v0.3.0

func (s *SSO) MemberByID(ctx context.Context, member access.MemberID) (access.Member, bool, error)

MemberByID returns the member; false when none has the identifier.

func (*SSO) OpenSession added in v0.3.0

func (s *SSO) OpenSession(ctx context.Context, in SSOSignIn) (secret.String, error)

OpenSession opens the session of a member who proved who they are to an auth provider, records their sign-in and the source it came from, and returns the value of its cookie, which is handed to the browser and never stored. It records auth.signed_in with the method and the provider. The member is locked and read again first, the order deactivating takes: a session opened while the member is deactivated would survive their session revocation and live again when they are reactivated, so a member no longer active is refused ErrSessionExpired.

func (*SSO) ProvisionMember added in v0.3.0

func (s *SSO) ProvisionMember(ctx context.Context, email, displayName string, method access.SignInMethod, provider, requestID string) (access.Member, error)

ProvisionMember creates the active member a first sign-in through provider asks for, without a password, and records member.provisioned with the new member as its actor: they provisioned themself by signing in.

func (*SSO) RecordFailedSignIn added in v0.3.0

func (s *SSO) RecordFailedSignIn(ctx context.Context, member access.Member, method access.SignInMethod, provider, reason, requestID string) error

RecordFailedSignIn records auth.sign_in_failed for a member known to the instance who could not sign in through provider, with reason.

func (*SSO) RevokeProviderSessions added in v0.4.0

func (s *SSO) RevokeProviderSessions(ctx context.Context, member access.MemberID, provider string) (int, error)

RevokeProviderSessions ends every session of member opened through the provider with this slug, so a person who no longer has an identity there does not stay signed in through it; it returns how many it ended.

type SSOActivation added in v0.3.0

type SSOActivation struct {
	Member access.MemberID
	// Method is the protocol of the auth provider, Provider its slug.
	Method    access.SignInMethod
	Provider  string
	RequestID string
}

SSOActivation is an invited member activated by signing in through an auth provider.

type SSOSignIn added in v0.3.0

type SSOSignIn struct {
	Member access.Member
	// Method is the protocol of the auth provider the member signed in
	// through.
	Method access.SignInMethod
	// Provider is the slug of the auth provider the member signed in through.
	Provider string
	// ClientIP and UserAgent describe the device signing in.
	ClientIP  netip.Addr
	UserAgent string
	RequestID string
}

SSOSignIn is one single sign-on opening a session.

type SSOStore added in v0.3.0

type SSOStore interface {
	// MemberByEmail returns the member whose email is email whatever its
	// case, with their password hash ("" for none); ErrNotFound when none.
	MemberByEmail(ctx context.Context, email string) (access.Member, string, error)
	// MemberByID returns the member; ErrNotFound when none has the identifier.
	MemberByID(ctx context.Context, member access.MemberID) (access.Member, error)
	// MemberByExternalID returns the member the provider with this slug
	// provisioned with externalID; ErrNotFound when none.
	MemberByExternalID(ctx context.Context, provider, externalID string) (access.Member, error)
	CreateMember(ctx context.Context, m access.Member, passwordHash string) error
	// LockMember returns the member, locked until the unit of work ends, and
	// whether they hold a password; ErrNotFound when none has the identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// LockInstanceAdmins serializes, until the unit of work ends, every
	// change that could leave the instance without an active instance admin.
	LockInstanceAdmins(ctx context.Context) error
	// PendingInvitation returns the latest invitation of member not consumed
	// yet, expired or not, locked until the unit of work ends; ErrNotFound
	// when the member has none.
	PendingInvitation(ctx context.Context, member access.MemberID) (access.Invitation, error)
	SaveMember(ctx context.Context, m access.Member, at time.Time) error
	// ConsumeInvitations marks every open invitation of member consumed at
	// at and returns how many it marked.
	ConsumeInvitations(ctx context.Context, member access.MemberID, at time.Time) (int, error)

	RecordSignIn(ctx context.Context, member access.MemberID, at time.Time) error

	CreateSession(ctx context.Context, s access.Session) error
	// RevokeProviderSessions ends every session of member opened through the
	// provider with this slug and not ended yet at at, and returns how many
	// it ended.
	RevokeProviderSessions(ctx context.Context, member access.MemberID, provider string, at time.Time) (int, error)
	// contains filtered or unexported methods
}

SSOStore is what single sign-on needs of the stored members and sessions.

type Sealer added in v0.3.0

type Sealer interface {
	Seal(purpose secret.Purpose, plaintext []byte, binding secret.Binding) (string, error)
	// Rebind returns sealed bound to binding, sealing again a value sealed
	// before rows were bound.
	Rebind(purpose secret.Purpose, sealed string, binding secret.Binding) (string, error)
}

Sealer seals a value under the instance's secret key.

type SendTestMail added in v0.3.0

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

SendTestMail sends the caller a mail, while they wait.

func NewSendTestMail added in v0.3.0

func NewSendTestMail(postman *Postman, instance string) *SendTestMail

NewSendTestMail returns the handler; instance is the instance's public address, which the mail names, "" when the instance has none.

func (*SendTestMail) Handle added in v0.3.0

func (h *SendTestMail) Handle(ctx context.Context, caller access.Caller, requestID string) error

Handle sends the test mail to the member calling, in their language, and answers once the server accepted it. It is refused smtp_not_configured while there is no SMTP server, and smtp_failed when the exchange failed, without saying at which step: the host is the instance admin's to name, and telling a refused connection from a failed handshake from a refused recipient would let one who is not the host's operator map the network behind it. The log record of the failure names the step, for the operator.

type SessionRevoker

type SessionRevoker interface {
	MemberSessionStore
	// RevokeSessions ends each of sessions not ended yet at at, and returns
	// those it ended.
	RevokeSessions(ctx context.Context, sessions []access.SessionID, at time.Time) ([]access.SessionID, error)
}

SessionRevoker revokes sessions.

type SessionStore

type SessionStore interface {
	// SessionByHash returns the session stored under hash with its member;
	// ErrNotFound when none is.
	SessionByHash(ctx context.Context, hash access.SessionHash) (access.Session, access.Member, error)
	TouchSession(ctx context.Context, session access.SessionID, at time.Time) error
	RevokeSession(ctx context.Context, session access.SessionID, at time.Time) error
}

SessionStore finds and updates sessions.

type SessionView

type SessionView struct {
	access.Session
	// End is when the absolute timeout in force ends the session.
	End time.Time
	// Current marks the session the request is signed in to.
	Current bool
}

SessionView is a live session as its member sees it.

type SetActiveCommand added in v0.3.0

type SetActiveCommand struct {
	Provider ProviderRef
	Member   access.MemberID
	Active   bool
	Request  governance.Request
}

SetActiveCommand deactivates or reactivates a member of a provider.

type SignIn

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

SignIn opens a session for a member who proves who they are with their email and password.

func NewSignIn

func NewSignIn(d SignInDeps) *SignIn

NewSignIn returns the handler.

func (*SignIn) Handle

func (h *SignIn) Handle(ctx context.Context, cmd SignInCommand) (SignInResult, error)

Handle signs the member in, opening a fresh session, or refuses with invalid_credentials. The attempt is counted as a failure of its email and its source before the password is verified, so attempts made at once cannot all pass the lockout; a locked email (locked) or a throttled source (rate_limited) is refused before any hash, and a right password takes the failure back. A source the member signed in from lately is counted and locked under the email and that source alone, so a stranger locking the email does not keep the member out, and a successful sign-in makes its source known. An unknown email is verified against a hash no password matches, so it takes as long as a wrong password; a member who is not active is refused like a wrong password even when the password is right. Failures of a known member are audited, attempts on unknown emails are not: the log records people, not an attacker's input. While local login is disabled every attempt is refused local_login_disabled, and an email in an enforced domain sso_required naming its provider, whoever holds it.

type SignInCommand

type SignInCommand struct {
	Email    string
	Password secret.String
	// ClientIP and UserAgent describe the device signing in.
	ClientIP  netip.Addr
	UserAgent string
	// RequestID is the request attempting, for the audit entries.
	RequestID string
}

SignInCommand is one attempt to sign in.

type SignInDeps

type SignInDeps struct {
	Tx    Transactor
	Store SignInStore
	// Settings give the timeouts a session opens with, and whether a
	// password is a way in.
	Settings AuthSettingsReader
	Hasher   PasswordVerifier
	Audit    AuditLog
	Clock    clock.Clock
	IDs      *id.Source
	// Random draws session cookies, which are signed with Key.
	Random io.Reader
	Key    []byte
}

SignInDeps are what signing in works with.

type SignInResult

type SignInResult struct {
	Caller access.Caller
	Cookie secret.String
}

SignInResult is the session opened and the value of its cookie, which is handed to the browser and never stored.

type SignInRules added in v0.3.0

type SignInRules struct {
	// LocalLoginEnabled is whether members sign in with a password at all.
	LocalLoginEnabled bool
	// PasswordResetAvailable is whether a reset can be asked for by mail.
	PasswordResetAvailable bool
	// EnforcedProvider is the slug of the auth provider the email's domain
	// is enforced to, "" when it is not.
	EnforcedProvider string
}

SignInRules are what the sign-in page shows of the auth settings, for an email or for anybody.

type SignInStore

type SignInStore interface {

	// LockMemberPassword returns member with their password hash ("" for
	// none), locked until the unit of work ends, so no password change
	// commits between the check and the session it opens; ErrNotFound when
	// there is none.
	LockMemberPassword(ctx context.Context, member access.MemberID) (access.Member, string, error)
	SetPasswordHash(ctx context.Context, member access.MemberID, hash string, at time.Time) error
	RecordSignIn(ctx context.Context, member access.MemberID, at time.Time) error

	CreateSession(ctx context.Context, s access.Session) error
	// contains filtered or unexported methods
}

SignInStore is what signing in needs of the stored members and sessions.

type SignOut

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

SignOut ends the session a caller is signed in to.

func NewSignOut

func NewSignOut(tx Transactor, store SessionStore, audit AuditLog, c clock.Clock, ids *id.Source) *SignOut

NewSignOut returns the handler.

func (*SignOut) Handle

func (h *SignOut) Handle(ctx context.Context, caller access.Caller, requestID string) error

Handle revokes the caller's session and records the sign-out. A caller presenting an API token has no session to end and is refused, so a script never believes it ended something.

type SourceThrottle added in v0.3.0

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

SourceThrottle lets a credential other than a password, such as a SCIM token, count its failed attempts against the throttle of the address they come from, which local sign-in, invitation acceptance and password reset share: guessing at one cannot be traded for guessing at another. A request that presents no credential but makes the instance work for anyone who sends it, such as asking for a password reset by mail, counts against it too and is never taken back, so one address cannot make the instance mail and audit at wire speed.

func NewSourceThrottle added in v0.3.0

func NewSourceThrottle(tx Transactor, store SourceThrottleStore) *SourceThrottle

NewSourceThrottle returns the throttle.

func (*SourceThrottle) Reserve added in v0.3.0

func (t *SourceThrottle) Reserve(ctx context.Context, ip netip.Addr, at time.Time) error

Reserve counts one failure of the source ip comes from at at, which is never taken back: what is presented matched nothing, or is a request that makes the instance work for anyone who sends it. A throttled source is refused rate_limited, its failure taken back.

type SourceThrottleStore added in v0.3.0

type SourceThrottleStore interface {
	// ReserveSourceAttempt counts a as a failure of its source alone, before
	// what it presents is checked, and returns what it found.
	ReserveSourceAttempt(ctx context.Context, a access.Attempt) (access.Reservation, error)
	// ReleaseAttempt takes back the failure r reserved.
	ReleaseAttempt(ctx context.Context, r access.Reservation) error
}

SourceThrottleStore counts the failed attempts of sources.

type TestMailData added in v0.3.0

type TestMailData struct {
	// Instance is the instance's public address, "" when it has none.
	Instance string
}

TestMailData is what the test mail's template reads.

type TokenStore

type TokenStore interface {
	// TokenByHash returns the token and, for a personal access token, the
	// member holding it; ErrNotFound when no token has the hash.
	TokenByHash(ctx context.Context, hash access.TokenHash) (access.APIToken, *access.Member, error)
}

TokenStore finds API tokens by the hash of their value.

type TokenUseStore

type TokenUseStore interface {
	// RecordTokenUse records that token was presented at at from ip, unless
	// a use less than a minute before at is recorded already, so replicas
	// writing the same token's use coalesce.
	RecordTokenUse(ctx context.Context, token access.APITokenID, at time.Time, ip netip.Addr) error
}

TokenUseStore records when and from where API tokens were last used.

type TokenUses

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

TokenUses gathers the uses of API tokens a replica sees and writes them in rounds, so authenticating a request never waits on a write and a token presented many times a minute costs one.

func NewTokenUses

func NewTokenUses(store TokenUseStore) *TokenUses

NewTokenUses returns the replica's gatherer of token uses.

func (*TokenUses) Flush

func (u *TokenUses) Flush(ctx context.Context) error

Flush writes the uses noted since the last round. A use that cannot be written is dropped rather than retried: the next use of its token is noted again, and nothing depends on the record but a member's view of their tokens. It returns the first failure, for the round's log.

func (*TokenUses) Note

func (u *TokenUses) Note(t access.APIToken, at time.Time, ip netip.Addr)

Note keeps t's use at at from ip for the next round, when it is one worth recording; the latest use of a token seen before the round is the one written.

type Transactor

type Transactor interface {
	Within(ctx context.Context, fn func(ctx context.Context) error) error
}

Transactor runs a unit of work.

type Unlock added in v0.3.0

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

Unlock opens the instance again to everybody who signs in with a password, from the command line: what an operator does when a broken auth provider, or settings sending everyone to it, keep every member out.

func NewUnlock added in v0.3.0

func NewUnlock(tx Transactor, store UnlockStore, audit AuditLog, c clock.Clock, ids *id.Source) *Unlock

NewUnlock returns the handler.

func (*Unlock) Handle added in v0.3.0

func (h *Unlock) Handle(ctx context.Context, req governance.Request) (Unlocked, error)

Handle enables local login, lifts every enforced domain and forgets every failed sign-in, of emails and of sources alike, in one unit of work, and records auth_settings.unlocked with the settings before and after and the lockouts cleared. It records the same when there was nothing to undo, so the trail shows every use of the break-glass. Every replica applies the change once the notification reaches it.

type UnlockStore added in v0.3.0

type UnlockStore interface {
	AuthSettingsStore
	// ClearAllSignInFailures forgets every failed sign-in counted, per email and
	// per source, and returns how many emails were locked out at the moment
	// at, each counted once.
	ClearAllSignInFailures(ctx context.Context, at time.Time) (int, error)
}

UnlockStore is what unlocking the instance needs.

type Unlocked added in v0.3.0

type Unlocked struct {
	// LocalLoginWasDisabled is whether local login was off.
	LocalLoginWasDisabled bool
	// DomainsLifted counts the enforced domains lifted.
	DomainsLifted int
	// LockoutsCleared counts the emails that were locked out, alone or from a
	// source, whose failures are now forgotten.
	LockoutsCleared int
}

Unlocked is what an unlock undid.

type UpdateAuthSettings

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

UpdateAuthSettings replaces the auth settings.

func NewUpdateAuthSettings

func NewUpdateAuthSettings(d UpdateAuthSettingsDeps) *UpdateAuthSettings

NewUpdateAuthSettings returns the handler.

func (*UpdateAuthSettings) Handle

Handle checks the settings, stores them and records auth_settings.updated with the settings before and after; settings equal to those in force change nothing and record nothing. Each enforced domain must name an enabled auth provider that vouches for it (invalid_auth_settings otherwise). Disabling local login is refused identity_required unless the caller holds an identity at an enabled provider that the new settings' enforcement still lets sign them in, so the instance admin who closes the door keeps a way through it. Closing local login, or enforcing a domain, ends the sessions the new settings would not let sign in, the caller's own included, and records how many in sessions_revoked; personal access tokens are not sign-ins and stay. Every replica applies a change once the notification reaches it; this one at once.

type UpdateAuthSettingsCommand added in v0.3.0

type UpdateAuthSettingsCommand struct {
	Settings access.AuthSettings
	Caller   access.Caller
	Request  governance.Request
}

UpdateAuthSettingsCommand replaces the settings with Settings, on behalf of Caller.

type UpdateAuthSettingsDeps added in v0.3.0

type UpdateAuthSettingsDeps struct {
	Tx    Transactor
	Store AuthSettingsStore
	Cache AuthSettingsCache
	// Providers tell whether an enforced domain's provider may have it.
	Providers EnforcementProviders
	// Identities tell whether the caller holds an identity, as disabling
	// local login asks.
	Identities IdentityDirectory
	Audit      AuditLog
	Clock      clock.Clock
	IDs        *id.Source
}

UpdateAuthSettingsDeps are what replacing the auth settings works with.

type UpdateMe

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

UpdateMe lets a member rename themself and choose their console language.

func NewUpdateMe

func NewUpdateMe(tx Transactor, store MemberChanger, audit AuditLog, c clock.Clock, ids *id.Source, locales []string) *UpdateMe

NewUpdateMe returns the handler; locales are the console's languages, the ones a member may choose.

func (*UpdateMe) Handle

func (h *UpdateMe) Handle(ctx context.Context, cmd UpdateMeCommand) (MemberView, error)

Handle applies the edit to the caller's member and records member.updated naming the fields it changed; an edit changing nothing records nothing. Only a session edits its member, so a leaked token cannot rename its owner.

type UpdateMeCommand

type UpdateMeCommand struct {
	Caller  access.Caller
	Change  access.ProfileChange
	Request governance.Request
}

UpdateMeCommand is a member's edit of themself.

type UpdateMember

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

UpdateMember edits a member for an instance admin.

func NewUpdateMember

func NewUpdateMember(tx Transactor, store UpdateMemberStore, audit AuditLog, c clock.Clock, ids *id.Source) *UpdateMember

NewUpdateMember returns the handler.

func (*UpdateMember) Handle

Handle applies the edit and records member.updated for a changed email or display name, and member.promoted or member.demoted for a changed instance admin switch; an edit changing nothing records nothing. Demoting the last active instance admin is refused last_instance_admin. Demoting an instance admin drops the grant of each invitation they issued to a project they hold no grant.manage in, recording invitation.grant_revoked, since they no longer hold it everywhere. Changing the email consumes the member's open invitations and password resets: their links were mailed or handed out for the address the member no longer has, and would otherwise let whoever holds them act as the member at the new one.

type UpdateMemberCommand

type UpdateMemberCommand struct {
	Member  access.MemberID
	Change  access.MemberChange
	Request governance.Request
}

UpdateMemberCommand is an edit of a member.

type UpdateMemberStore added in v0.3.0

UpdateMemberStore is what editing a member needs.

type UpdateProvisionedCommand added in v0.3.0

type UpdateProvisionedCommand struct {
	Provider    ProviderRef
	Member      access.MemberID
	Email       *string
	DisplayName *string
	// ExternalID replaces the external ID; ClearExternalID removes it.
	ExternalID      *string
	ClearExternalID bool
	Request         governance.Request
}

UpdateProvisionedCommand changes what the directory states of a member; a nil field is left as it is.

type WaysIn added in v0.3.0

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

WaysIn tells the ways a member holds to sign in. Every change that could remove one asks it under the member's lock, so two changes made at once each see the other's outcome and cannot together leave a member without.

func NewWaysIn added in v0.3.0

func NewWaysIn(store WaysInStore, identities IdentityDirectory, settings AuthSettingsReader) *WaysIn

NewWaysIn returns the service; settings tell which ways in local login and enforcement leave usable.

func (*WaysIn) EnsureWayIn added in v0.3.0

func (w *WaysIn) EnsureWayIn(ctx context.Context, m access.Member, withoutPassword bool, withoutIdentity string) error

EnsureWayIn refuses, with ErrLastAuthMethod, removing the password (withoutPassword) and unlinking the identity withoutIdentity ("" for none) when no other usable way in of m would remain.

func (*WaysIn) Lock added in v0.3.0

func (w *WaysIn) Lock(ctx context.Context, member access.MemberID) (access.Member, error)

Lock locks the member until the unit of work ends and returns them; ErrNotFound when none has the identifier.

func (*WaysIn) Methods added in v0.3.0

func (w *WaysIn) Methods(ctx context.Context, m access.Member) (access.AuthMethods, error)

Methods returns the ways m holds to sign in, judged under the auth settings in force for their email.

func (*WaysIn) PasswordSetAt added in v0.3.0

func (w *WaysIn) PasswordSetAt(ctx context.Context, member access.MemberID) (*time.Time, error)

PasswordSetAt returns when the member set the password they hold, nil when they hold none.

type WaysInStore added in v0.3.0

type WaysInStore interface {
	// LockMember returns the member, locked until the unit of work ends, and
	// whether they hold a password; ErrNotFound when none has the identifier.
	LockMember(ctx context.Context, member access.MemberID) (access.Member, bool, error)
	// PasswordSetAt returns when the member set the password they hold, nil
	// when they hold none.
	PasswordSetAt(ctx context.Context, member access.MemberID) (*time.Time, error)
}

WaysInStore is what telling a member's ways in needs of the stored members.

type WebhookDisabledMailData added in v0.3.0

type WebhookDisabledMailData struct {
	// Name is the subscription's name.
	Name string
	// Project is the name of the project the subscription belongs to; ""
	// for an instance subscription.
	Project string
	// Reason is why the platform disabled it: the subscription's disabled
	// reason, such as persistent_failure.
	Reason string
	// URL is the subscription's page in the console.
	URL string
}

WebhookDisabledMailData is what the webhook_disabled mail's template reads.

type WebhookDisabledMailer added in v0.3.0

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

WebhookDisabledMailer mails those who manage a webhook subscription when the platform disables it: the active members whose grants give them webhook.manage in its project, instance admins among them, or the active instance admins for an instance subscription. Like every mail it goes out once the unit of work that disabled the subscription has committed, and nothing that happens to it undoes the disable.

func NewWebhookDisabledMailer added in v0.3.0

func NewWebhookDisabledMailer(postman *Postman, smtp SMTPReader, directory WebhookManagerDirectory, consoleURL string,
) *WebhookDisabledMailer

NewWebhookDisabledMailer returns the mailer; consoleURL is the address the console is served at, "" when the instance has none, in which case nothing is mailed: a mail linking to nowhere helps nobody.

func (*WebhookDisabledMailer) Notify added in v0.3.0

Notify queues the mail of w to each recipient, in their language else the instance's. It queues nothing while the instance has no SMTP server or no console address, and a nil mailer never mails.

type WebhookManagerDirectory added in v0.3.0

type WebhookManagerDirectory interface {
	// ProjectMembers returns the members holding grants in project, each
	// with their grants there.
	ProjectMembers(ctx context.Context, project workspace.ProjectID) ([]ProjectMember, error)
	// ActiveInstanceAdmins returns the active members who are instance
	// admins.
	ActiveInstanceAdmins(ctx context.Context) ([]access.Member, error)
	// ProjectKeyAndName returns the key and the name of project;
	// ErrNotFound when it no longer exists.
	ProjectKeyAndName(ctx context.Context, project workspace.ProjectID) (key, name string, err error)
}

WebhookManagerDirectory reads who is told of a disabled subscription.

type WorkingProjects

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

WorkingProjects answers which projects a caller works in, for listing them.

func NewWorkingProjects

func NewWorkingProjects(grants GrantReader) *WorkingProjects

NewWorkingProjects returns the handler.

func (*WorkingProjects) Handle

func (h *WorkingProjects) Handle(ctx context.Context, caller access.Caller) (all bool, only []workspace.ProjectID, err error)

Handle reports whether the caller works in every project, as an instance admin does, and otherwise the projects their member holds a grant in.

Jump to

Keyboard shortcuts

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