access

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package access is the domain of who may do what: members and the instance admin, API tokens and their scopes, the permission catalog, the built-in roles and how a caller is judged against what an operation requires.

Index

Constants

View Source
const (
	SourceFailureLimit = 100
	SourceWindow       = 15 * time.Minute
)

The throttle of a source: a hundred failures within a window of fifteen minutes refuse it until the window ends, so one source cannot spray guesses across many emails. A source's window opens at its first failure and does not slide; the first failure after it ends opens the next.

View Source
const (
	MinPasswordLength = 12
	MaxPasswordLength = 128
)

Password length bounds, in code points. MinPasswordLength is the floor of the minimum an instance admin may set: they may raise it, never lower it. MaxPasswordLength is fixed, and checked before any hash, so a huge password cannot cost one.

View Source
const (
	PasswordRuleLength = "length"
	PasswordRuleEmail  = "email"
	PasswordRuleCommon = "common"
)

The rules of the password policy, named in a refusal so a client explains which one a password broke.

View Source
const EmailFailureRetention = 24 * time.Hour

EmailFailureRetention is how long an email's failures are kept after its last one once no lock holds it: long enough that a guesser pausing between bursts still meets the lockout, short enough that a member's forgotten mistakes stop counting against them.

View Source
const InvitationLifetime = 7 * 24 * time.Hour

InvitationLifetime is how long an invitation can be accepted: long enough to reach someone through whoever passes the link on, short enough that a link lying forgotten in a chat stops working.

View Source
const InvitationRetention = 30 * 24 * time.Hour

InvitationRetention is how long an invitation is kept once it can no longer be accepted before the retention worker deletes it, so the table does not grow forever while a recent link can still be looked into. Each member's latest invitation is kept regardless, as the record of their last link.

View Source
const KnownSourceAge = 30 * 24 * time.Hour

KnownSourceAge is how long a source stays known to a member after they last signed in from it: long enough to span a holiday away from the desk, short enough that an address the member gave up, which someone else may hold now, stops being theirs.

View Source
const (
	LockoutThreshold = 5
)

The lockout of an email: from the fifth consecutive failure on, each failure locks the email, for a minute at first and twice as long with each further failure, up to an hour. Guessing one member's password is slow, and since unknown emails lock the same way, enumeration learns nothing.

The lock holds against every source but the member's known ones, those they signed in from within KnownSourceAge: a known source's attempts are counted under the email and that source alone, and locked by the same schedule. Anyone can lock an email by guessing at it, so a lock meeting every source would let them keep its member, an instance admin included, out for as long as they keep guessing; a known source is one an attacker rarely shares with the member.

View Source
const PasswordResetInterval = 5 * time.Minute

PasswordResetInterval is how long a member waits between two password resets they asked for, counted from the issuing and not from the mail, so a request repeated for an address cannot flood its inbox nor, while the mail fails, the relay.

View Source
const PasswordResetLifetime = time.Hour

PasswordResetLifetime is how long a password reset can be completed: long enough to reach the member through whoever passes the link on, short enough that a link lying in a chat or a mailbox stops working soon.

View Source
const PasswordResetRetention = 30 * 24 * time.Hour

PasswordResetRetention is how long a password reset is kept once it can no longer be completed before the retention worker deletes it, so the table does not grow forever while a recent link can still be looked into.

View Source
const TokenUseInterval = time.Minute

TokenUseInterval is how often a token's use is recorded at most: often enough for a member to tell a token in use from one forgotten, rarely enough that a busy script does not write on every request.

Variables

View Source
var (
	// ErrLocalLoginDisabled refuses every password while local login is
	// disabled.
	ErrLocalLoginDisabled = apperrors.Forbidden("local_login_disabled",
		"local login is disabled; sign in through an auth provider")
	// ErrIdentityRequired refuses disabling local login to a caller who holds
	// no identity at an enabled auth provider: they would lock themself out
	// along with everybody else.
	ErrIdentityRequired = apperrors.Invalid("identity_required",
		"local login can be disabled only by a member who holds an identity at an enabled auth provider")
)

Errors refusing a password as a way in.

View Source
var DefaultAuthSettings = AuthSettings{
	SessionIdleTimeout:     DefaultSessionTimeouts.Idle,
	SessionAbsoluteTimeout: DefaultSessionTimeouts.Absolute,
	TokenMaxLifetime:       365 * 24 * time.Hour,
	PasswordMinLength:      MinPasswordLength,

	SelfServicePasswordReset: true,
	LocalLoginEnabled:        true,
}

DefaultAuthSettings are the settings of a fresh instance.

View Source
var DefaultSessionTimeouts = SessionTimeouts{Idle: 24 * time.Hour, Absolute: 30 * 24 * time.Hour}

DefaultSessionTimeouts end a session a day after its last request or thirty days after it opened, so a forgotten browser does not stay signed in.

View Source
var ErrInvalidToken = apperrors.Unauthenticated("invalid_token", "the API token is not valid")

ErrInvalidToken refuses a bearer value that is no token, malformed or unknown alike, so a caller cannot tell which.

View Source
var ErrInvitationGone = apperrors.Gone("invitation_gone",
	"this invitation was never issued, has been used or replaced, or has expired")

ErrInvitationGone answers an invitation that cannot be accepted, whatever the reason, so a link tells nobody whether it ever existed.

View Source
var ErrLastAuthMethod = apperrors.Conflict("last_auth_method",
	"this is the member's last usable way to sign in; set another way in first")

ErrLastAuthMethod refuses removing the way in a member would be left without: a member always keeps one they can sign in with.

View Source
var ErrLastInstanceAdmin = apperrors.Conflict("last_instance_admin",
	"the instance's last active instance admin can be neither deactivated nor demoted")

ErrLastInstanceAdmin refuses a change that would leave the instance without an active instance admin, whom nobody could replace through the API.

View Source
var ErrMemberDeactivated = apperrors.Conflict("member_deactivated", "the member is deactivated")

ErrMemberDeactivated refuses a grant to a member who is deactivated: they can use nothing it gives until they are reactivated.

View Source
var ErrMemberInvited = apperrors.Conflict("member_invited",
	"the member has not accepted their invitation yet; they are given this once they have joined")

ErrMemberInvited refuses giving a member who has not accepted their invitation more than the invitation carries. Until an invitation is mailed its link is held by whoever issued it, who can accept it as the person invited: a role granted, or the instance admin switch set, before the person joins would be given to whoever holds their link.

View Source
var ErrMemberNotActive = apperrors.Conflict("member_not_active",
	"only an active member can be given a password reset; issue an invited member's invitation again instead")

ErrMemberNotActive refuses issuing a password reset for a member who is still invited: they hold no password to reset, and their invitation is the way to give them one.

View Source
var ErrMemberNotInvited = apperrors.Conflict("member_not_invited", "only an invited member has an invitation to reissue")

ErrMemberNotInvited refuses reissuing the invitation of a member who has joined or was deactivated: there is no first password left to set.

View Source
var ErrMemberProvisioned = apperrors.Conflict("member_provisioned",
	"the member is provisioned by an identity provider, which decides their email, name and status; change them there")

ErrMemberProvisioned refuses changing by hand what the identity provider that provisioned a member decides: their email, name and status.

View Source
var ErrNotAdoptable = apperrors.Conflict("not_adoptable", "the member cannot be adopted by an identity provider")

ErrNotAdoptable refuses adopting a member an identity provider may not take over: an instance admin, whom no directory decides; one another provider (or this one) provisions already; one who is not active, whose invitation or offboarding is someone's decision.

View Source
var ErrPasswordResetGone = apperrors.Gone("reset_gone",
	"this password reset was never issued, has been used or ended, or has expired")

ErrPasswordResetGone answers a password reset that cannot be completed, whatever the reason, so a link tells nobody whether it ever existed.

View Source
var ErrProjectNotFound = apperrors.NotFound("not_found", "no project has this key")

ErrProjectNotFound answers an operation addressing a project no project's key names. It is answered before any permission is judged, so a caller tells an unknown project from one they may not touch only by its key.

View Source
var ErrSSOSourced = apperrors.Conflict("sso_sourced", "an auth provider's group mapping granted this; change the mapping or the directory instead")

ErrSSOSourced refuses removing by hand what a provider's group mapping granted: the directory owns it, and it goes when the person leaves the group or the mapping is removed.

View Source
var ErrSessionExpired = apperrors.Unauthenticated("session_expired", "the session has ended; sign in again")

ErrSessionExpired refuses a session cookie that no longer signs anyone in: ended by timeout, sign-out or revocation, or the member is no longer active.

View Source
var ErrSessionRequired = apperrors.Forbidden("session_required", "this operation needs a signed-in session; an API token cannot perform it")

ErrSessionRequired refuses an API token an operation only a signed-in session performs.

View Source
var ErrTokenCannotApprove = apperrors.Forbidden("token_cannot_approve", "a project token cannot decide a change request")

ErrTokenCannotApprove refuses a project token whose role would decide change requests, naming why rather than the permission it lacks: no token ever decides one, whatever its role.

MailKinds are every kind of mail the instance sends; each has a template in every language of MailLocales.

View Source
var MailLocales = []string{"en", "ru"}

MailLocales are the languages mail is written in, the console's.

Functions

func Authorize

func Authorize(c Caller, op Operation, in *ProjectAccess) error

Authorize judges an authenticated caller against op, in the order every refusal is explained: a project token outside its reach, then a write that needs a session, then a scope the token lacks, then an unknown project, then the requirement itself. A public operation admits anyone.

in is what the caller holds in the project an operation requiring a catalog permission addresses; without it such an operation is refused, so none is ever open before its project's grants are judged.

func CanAskForPasswordReset added in v0.3.0

func CanAskForPasswordReset(m Member, holdsPassword bool) bool

CanAskForPasswordReset reports whether a request for a password reset of m leads to one: only an active member who holds a password has one to forget. An invited member has an invitation, a deactivated one no way in, and one who signs in through a provider only no password.

func CheckGrantorCap

func CheckGrantorCap(held []Permission, role Role) error

CheckGrantorCap refuses handing out role, by making or removing a grant of it or by creating a project token holding it, when held, the permissions the caller holds in the project, lacks any permission of the role; role_not_allowed names the first one missing. So managing access never escalates into more access than the manager has. held are the effective permissions of the credential in use, narrowed by a token's scopes: a credential cannot hand out what it does not hold.

func CheckPassword

func CheckPassword(password, email string, minLength int) error

CheckPassword refuses, with weak_password, a password for the member with email that has fewer code points than minLength (never below 12) or more than 128, contains the email's local part whatever its case, or is a common password. There are no composition rules: length is what makes a password hard to guess.

func CheckPasswordAt

func CheckPasswordAt(pointer, password, email string, minLength int) error

CheckPasswordAt is CheckPassword for a password sent at pointer in the request, which its refusal names, such as /new_password beside the current one.

func CheckPasswordResetIssuable added in v0.3.0

func CheckPasswordResetIssuable(m Member) error

CheckPasswordResetIssuable refuses a password reset for a member who is not active: ErrMemberNotActive for one still invited, ErrMemberDeactivated for one deactivated.

func CheckScopesHeld

func CheckScopesHeld(c Caller, scopes []Scope) error

CheckScopesHeld refuses scopes c does not hold itself, scope_not_allowed naming the first, so a credential never hands out more than it holds: a session holds every scope, but instance:admin only for an instance admin; a token holds its own scopes.

func CheckTokenExpiry

func CheckTokenExpiry(expiresAt *time.Time, now time.Time, s AuthSettings) error

CheckTokenExpiry refuses the expiry of a token created at now unless it lies in the future and at most the settings' maximum lifetime ahead, or its absence when the settings require one, so no token outlives what the instance allows. A token without an expiry never expires.

func GeneratePassword

func GeneratePassword(email string, random io.Reader) secret.String

GeneratePassword draws a password of 24 base62 characters, about 143 bits, for a member created without one. It draws again until the policy accepts it for email, which a short local part can make necessary.

func IsRequirement

func IsRequirement(r Requirement) bool

IsRequirement reports whether r is a requirement an operation may declare: a catalog permission or one of the reserved values.

func KeepAnInstanceAdmin

func KeepAnInstanceAdmin(before, after Member, others int) error

KeepAnInstanceAdmin refuses changing before into after when before is an active instance admin, after is not, and the instance has no other active instance admin, others counting them. The count must be read under the lock that serializes such changes, or two admins demoting each other at once would both pass.

func KnownSourceOf added in v0.2.0

func KnownSourceOf(ip netip.Addr) (netip.Prefix, bool)

KnownSourceOf returns the source a sign-in from ip makes known to its member, and false when there is no address: every attempt without one shares the unspecified source, which is nobody's own.

func LockoutSchedule

func LockoutSchedule() []time.Duration

LockoutSchedule returns LockoutWindow of each consecutive failure, the first entry for the first failure, up to the first failure that locks for the longest window, which every failure after it locks for too. The store counting failures locks an email by it in the same step as it counts, so the lock it stores is the one this function decides.

func LockoutWindow

func LockoutWindow(failures int) time.Duration

LockoutWindow returns how long the failures-th consecutive failure on an email locks it, 0 below the threshold.

func MailLocale added in v0.3.0

func MailLocale(fallback string, preferred ...string) string

MailLocale returns the language a mail is written in: the first of preferred that mail is written in, else fallback. A caller lists whose language counts in order, such as the recipient's, then for an invitation the inviter's, and passes the instance's default as the fallback.

func MaskEmail

func MaskEmail(email string) string

MaskEmail returns email as the page an invitation opens shows it: its first character and its domain, enough for the invited person to recognise their address, too little for whoever finds a stray link to learn it.

func NewPersonalToken

func NewPersonalToken(tokenID APITokenID, in NewPersonalTokenInput, random io.Reader) (APIToken, TokenValue, error)

NewPersonalToken returns a personal access token and its value, drawn from random.

func NewProjectToken

func NewProjectToken(tokenID APITokenID, in NewProjectTokenInput, random io.Reader) (APIToken, TokenValue, error)

NewProjectToken returns a project token and its value, drawn from random. It holds one built-in role in its project and never instance:admin: it acts in its project alone.

func PasswordRule

func PasswordRule(err error) string

PasswordRule returns the rule of the password policy err reports broken, or "" when err is no refusal of the policy.

func SSORequired added in v0.3.0

func SSORequired(provider string) error

SSORequired is the refusal of a way in for an email whose domain is enforced to provider (a slug), naming the provider to sign in through.

func SelfServicePasswordResetDue added in v0.3.0

func SelfServicePasswordResetDue(last *time.Time, now time.Time) bool

SelfServicePasswordResetDue reports whether a member may be issued a password reset they asked for at now, when their latest was issued at last (nil for a member who never asked).

func SourceOf

func SourceOf(ip netip.Addr) netip.Prefix

SourceOf returns the source an address's failures are counted against: an IPv4 address alone, an IPv6 address with the rest of its /64, which one subscriber usually holds whole. Without an address, the source is the unspecified one.

func UnknownProjectError added in v0.3.0

func UnknownProjectError(pointer string) error

UnknownProjectError refuses an invitation's grant in a project the instance does not hold, at pointer.

func UnknownRoleError

func UnknownRoleError(pointer string) error

UnknownRoleError refuses a role that is none of the built-in ones, at pointer.

Types

type APIToken

type APIToken struct {
	ID   APITokenID
	Kind TokenKind
	// Member holds a personal access token; zero for a project token.
	Member MemberID
	// Project is the one project a project token reaches, and Role the one
	// role it holds there; zero for a personal access token.
	Project workspace.ProjectID
	Role    RoleName
	Name    string
	Hint    string
	Hash    TokenHash
	// Scopes always hold read beside any write scope.
	Scopes []Scope
	// ExpiresAt is nil for a token that does not expire.
	ExpiresAt *time.Time
	RevokedAt *time.Time
	CreatedAt time.Time
	// CreatedBy is the member who created a project token; zero for a
	// personal access token, whose member is Member. The project token
	// outlives them: it belongs to its project.
	CreatedBy MemberID
	// LastUsedAt and LastUsedIP are when and from where the token was last
	// presented, as last recorded; nil and the zero address until then.
	LastUsedAt *time.Time
	LastUsedIP netip.Addr
}

APIToken is a credential presented to the management API as a bearer token.

func (APIToken) HasScope

func (t APIToken) HasScope(s Scope) bool

HasScope reports whether the token carries s.

func (APIToken) Refusal

func (t APIToken) Refusal(now time.Time, holder *Member) error

Refusal judges the token at now, held by holder (nil for a project token): a revoked token is refused as revoked whether or not it also expired, and so is a personal access token whose member is not active; then an expired one as expired.

func (APIToken) UseToRecord

func (t APIToken) UseToRecord(now time.Time) bool

UseToRecord reports whether presenting the token at now is a use worth recording: its first, or a minute or more after the last one recorded.

type APITokenID

type APITokenID = id.Of[APIToken]

APITokenID identifies an API token.

type Attempt

type Attempt struct {
	// Email is the email the attempt names, trimmed and in lower case, as
	// members are found by it.
	Email string
	// Source is the source the attempt comes from, as SourceOf gives it.
	Source netip.Prefix
	// At is when the attempt is made; it is judged at that time throughout.
	At time.Time
}

Attempt is one attempt at a password, counted under its email and its source.

func NewAttempt

func NewAttempt(email string, ip netip.Addr, at time.Time) Attempt

NewAttempt returns the attempt naming email from the address ip at at.

func (Attempt) KnownAfter added in v0.2.0

func (a Attempt) KnownAfter() time.Time

KnownAfter returns the instant after which the member the attempt's email names must have signed in from its source for the source to be known.

type AuthMethods added in v0.3.0

type AuthMethods struct {
	Status MemberStatus
	// PasswordSetAt is when the member set the password they hold; nil when
	// they hold none.
	PasswordSetAt *time.Time
	// Identities are every identity the member holds, whether or not its
	// provider is enabled.
	Identities []IdentityMethod
	// PasswordRefused is whether the auth settings refuse the member's email
	// a password: local login is disabled, or their domain is enforced.
	PasswordRefused bool
	// EnforcedProvider is the slug of the auth provider the member's email
	// domain is enforced to, "" when it is not: an identity at another
	// provider signs them in nowhere.
	EnforcedProvider string
}

AuthMethods are the ways a member holds to sign in.

func (AuthMethods) HoldsUsableWayIn added in v0.3.0

func (m AuthMethods) HoldsUsableWayIn() bool

HoldsUsableWayIn reports whether the member holds a usable way in, whatever their status: what reactivating them asks, since a deactivated member signs in nowhere until then.

func (AuthMethods) KeepsWayIn added in v0.3.0

func (m AuthMethods) KeepsWayIn(withoutPassword bool, withoutIdentity string) bool

KeepsWayIn reports whether the member keeps a usable way in when the password is removed (withoutPassword) and the identity named by withoutIdentity ("" for none) is unlinked. A usable way in is a password local login accepts for the member's email, or an identity at an enabled provider that enforcement does not refuse them. A password local login or enforcement refuses today still counts as what the member would lose: `flagnetic admin unlock` makes it a way in again, so removing it while no usable way in remains could strand the member past the break-glass. A deactivated member signs in nowhere, so they need none.

func (AuthMethods) PasswordSet added in v0.3.0

func (m AuthMethods) PasswordSet() bool

PasswordSet reports whether the member holds a password.

func (AuthMethods) UnderSettings added in v0.3.0

func (m AuthMethods) UnderSettings(s AuthSettings, email string) AuthMethods

UnderSettings returns m with what the settings s say of the member's email applied: whether a password is refused, and the provider it is enforced to.

type AuthSettings

type AuthSettings struct {
	// SessionIdleTimeout ends a session that long after its last request.
	SessionIdleTimeout time.Duration
	// SessionAbsoluteTimeout ends a session that long after it opened,
	// however much it is used.
	SessionAbsoluteTimeout time.Duration
	// TokenMaxLifetime is the furthest ahead an API token may expire.
	TokenMaxLifetime time.Duration
	// TokenExpiryRequired refuses an API token without an expiry.
	TokenExpiryRequired bool
	// PasswordMinLength is the fewest code points a password has, never
	// below MinPasswordLength.
	PasswordMinLength int
	// SelfServicePasswordReset lets a member ask for a password reset by
	// mail. An instance admin can still issue a password reset whatever it says.
	SelfServicePasswordReset bool
	// LocalLoginEnabled lets members sign in with a password at all. Off,
	// every member signs in through an auth provider.
	LocalLoginEnabled bool
	// SSOEnforcedDomains are the email domains whose people sign in only
	// through one auth provider, each named once.
	SSOEnforcedDomains []EnforcedDomain
}

AuthSettings are the instance's rules for sessions, API tokens and passwords, which an instance admin changes at runtime.

func (AuthSettings) Check

func (s AuthSettings) Check() error

Check refuses settings that break a rule, invalid_auth_settings naming each field: every duration a whole number of seconds from a minute to ten years, the idle timeout at most the absolute one, and the password minimum length from MinPasswordLength to MaxPasswordLength, so a policy never lets weaker passwords in nor refuses every one, and each enforced domain named once, with a provider. Whether the provider exists and vouches for the domain is the identity context's to say. Check judges the settings as Normalized returns them.

func (AuthSettings) EnforcedDomainsOf added in v0.3.0

func (s AuthSettings) EnforcedDomainsOf(provider string) []string

EnforcedDomainsOf returns the enforced domains sent to provider, a slug.

func (AuthSettings) EnforcedFor added in v0.3.0

func (s AuthSettings) EnforcedFor(email string) (EnforcedDomain, bool)

EnforcedFor returns the enforced domain email belongs to, judged from its domain alone, so the answer never tells whether a member holds email.

func (AuthSettings) Equal added in v0.3.0

func (s AuthSettings) Equal(t AuthSettings) bool

Equal reports whether s and t are the same settings, the enforced domains in the same order.

func (AuthSettings) Normalized added in v0.3.0

func (s AuthSettings) Normalized() AuthSettings

Normalized returns s with each enforced domain trimmed, lowercased and without a trailing dot, as the settings keep and compare them.

func (AuthSettings) PasswordRefusal added in v0.3.0

func (s AuthSettings) PasswordRefusal(email string) error

PasswordRefusal returns why a password is no way in for email: sso_required naming the provider when its domain is enforced, local_login_disabled while local login is off, nil when a password may sign it in. The enforcement wins, since it says where to go instead.

func (AuthSettings) ProviderRefusal added in v0.3.0

func (s AuthSettings) ProviderRefusal(email, provider string) error

ProviderRefusal returns why the auth provider with the slug provider may not sign in or link email: sso_required naming the provider its domain is enforced to, when that is another one; nil otherwise.

func (AuthSettings) SessionTimeouts

func (s AuthSettings) SessionTimeouts() SessionTimeouts

SessionTimeouts are the timeouts the settings give sessions.

type Caller

type Caller struct {
	Method Method
	// Token is the API token presented, for MethodToken.
	Token *APIToken
	// Session is the session signed in to, for MethodSession.
	Session *Session
	// Member is the member the credential acts for; nil for a project token.
	Member *Member
}

Caller is who makes a request to the management API: the credential in use and the member it acts for.

func SessionCaller

func SessionCaller(s Session, holder Member) Caller

SessionCaller returns the caller signed in to s as holder.

func TokenCaller

func TokenCaller(tok APIToken, holder *Member) Caller

TokenCaller returns the caller presenting tok, held by holder (nil for a project token).

type EnforcedDomain added in v0.3.0

type EnforcedDomain struct {
	// Domain is lowercase, such as example.com; its subdomains are not
	// included.
	Domain string
	// Provider is the slug of the auth provider.
	Provider string
}

EnforcedDomain sends the people of an email domain to one auth provider: a password is no way in for them, whether to sign in, to accept an invitation or to complete a password reset, and no other provider signs them in or links them.

type FailureCutoffs

type FailureCutoffs struct {
	// Now is when the cutoffs are judged: a lock running past it keeps its
	// email's failures.
	Now time.Time
	// LastEmailFailureBy ends an unlocked email's failures when its last one
	// is at or before it.
	LastEmailFailureBy time.Time
	// SourceWindowStartBy ends a source's failures when its window opened at
	// or before it: the window is over, and the next failure opens another.
	SourceWindowStartBy time.Time
	// KnownSourceBy ends a member's known source when they last signed in
	// from it at or before it.
	KnownSourceBy time.Time
}

FailureCutoffs are the instants before which counted failures no longer matter, as the retention worker selects them in bulk.

func AttemptCutoffs

func AttemptCutoffs(now time.Time) FailureCutoffs

AttemptCutoffs returns the cutoffs at now.

type Grant

type Grant struct {
	ID      GrantID
	Project workspace.ProjectID
	Member  MemberID
	Role    RoleName
	Source  GrantSource
	// Provider is the slug of the auth provider whose group mapping made an
	// `sso` grant; "" for a manual one.
	Provider string
	// CreatedBy is the member who made the grant; zero when none did.
	CreatedBy MemberID
	CreatedAt time.Time
}

Grant is one role held by one member in one project. A member may hold several in a project; their permissions there are the union.

func NewGrant

func NewGrant(grantID GrantID, in NewGrantInput) (Grant, error)

NewGrant returns a grant made by hand of a built-in role to a member who has joined and is not deactivated: an invited member is refused ErrMemberInvited, and holds only what their invitation grants once they accept it.

func NewSSOGrant added in v0.3.0

func NewSSOGrant(grantID GrantID, project workspace.ProjectID, member MemberID, role RoleName, provider string, now time.Time) Grant

NewSSOGrant returns the grant of a built-in role in project that the group mappings of the auth provider with slug provider made to member.

type GrantDropReason added in v0.3.0

type GrantDropReason string

GrantDropReason is why an invitation's grant was dropped.

const (
	// GrantDropInviterLostPermission is an inviter who no longer holds
	// grant.manage in the project.
	GrantDropInviterLostPermission GrantDropReason = "inviter_lost_permission"
	// GrantDropInviterDeactivated is an inviter who was deactivated.
	GrantDropInviterDeactivated GrantDropReason = "inviter_deactivated"
)

The reasons an invitation's grant is dropped.

func GrantDrop added in v0.3.0

func GrantDrop(inviter Member, held []Grant) (GrantDropReason, bool)

GrantDrop reports whether the grant of an invitation issued by inviter to a project must be dropped, and why, given held, the grants inviter holds in that project. An invitation never grants more than its inviter may hand out, so it is dropped once its inviter is deactivated or no longer holds grant.manage there; an instance admin holds it in every project, so their invitations are not dropped for lack of a grant. The same rule decides whether an invitation issued again keeps its grant.

type GrantID

type GrantID = id.Of[Grant]

GrantID identifies a grant.

type GrantSource

type GrantSource string

GrantSource is what made a grant. Each source owns only its own grants, so grants from several sources sit side by side.

const (
	// GrantManual is a grant made by hand, by a member managing the project's
	// grants.
	GrantManual GrantSource = "manual"
	// GrantSSO is a grant made by an auth provider's group mapping.
	GrantSSO GrantSource = "sso"
)

The sources of a grant.

type IdentityMethod added in v0.3.0

type IdentityMethod struct {
	// ID identifies the identity, in the form its context gives it.
	ID string
	// Provider is the slug of the auth provider the identity is at.
	Provider string
	// ProviderEnabled is whether the auth provider the identity is at is
	// enabled: an identity at a disabled provider signs nobody in.
	ProviderEnabled bool
}

IdentityMethod is an identity a member holds, as far as it is a way in.

type Invitation

type Invitation struct {
	ID        InvitationID
	Member    MemberID
	Hash      InvitationHash
	CreatedAt time.Time
	ExpiresAt time.Time
	// ConsumedAt is when the invitation stopped being acceptable before it
	// expired: accepted, replaced by another, or consumed when its member was
	// deactivated. Nil while it is open.
	ConsumedAt *time.Time
	// InvitedBy is the member who issued the invitation; zero when none
	// did, such as one issued again to a member reactivated.
	InvitedBy MemberID
	// Grant is the role in a project that accepting makes; nil when the
	// invitation brings the member to the instance alone, or once it was
	// dropped.
	Grant *InvitationGrant
}

Invitation is the one-time link that lets an invited member set their first password; signing in through an auth provider that vouches for their email accepts it too.

func NewInvitation

func NewInvitation(invitationID InvitationID, member MemberID, now time.Time, random io.Reader) (Invitation, secret.String)

NewInvitation issues an invitation of member and returns it with its secret: 32 bytes drawn from random in unpadded base64url, shown once to whoever issued it and never stored.

func (Invitation) IssuedBy added in v0.3.0

func (i Invitation) IssuedBy(inviter MemberID, grant *InvitationGrant) Invitation

IssuedBy returns i as issued by inviter, bringing grant (none when nil) with it.

func (Invitation) Open

func (i Invitation) Open(now time.Time, holder Member) bool

Open reports whether the invitation can be accepted at now by holder, its member: not consumed, not expired, and holder still invited.

func (Invitation) WithoutGrant added in v0.3.0

func (i Invitation) WithoutGrant() Invitation

WithoutGrant returns i with its grant dropped: it still activates its member, and grants nothing.

type InvitationCutoffs

type InvitationCutoffs struct {
	// EndedBy purges an invitation consumed, or expired, at or before it.
	EndedBy time.Time
}

InvitationCutoffs select the invitations the retention worker purges.

func InvitationCutoffsAt

func InvitationCutoffsAt(now time.Time) InvitationCutoffs

InvitationCutoffsAt returns the cutoffs at now.

type InvitationGrant added in v0.3.0

type InvitationGrant struct {
	Project workspace.ProjectID
	Role    RoleName
}

InvitationGrant is the role in a project that an invitation, once accepted, makes the member hold.

func NewInvitationGrant added in v0.3.0

func NewInvitationGrant(project workspace.ProjectID, role RoleName, pointer string) (InvitationGrant, error)

NewInvitationGrant returns the grant of role in project; role is one of the built-in ones, or the refusal names pointer, where the request holds it.

type InvitationHash

type InvitationHash [sha256.Size]byte

InvitationHash is the SHA-256 of an invitation's secret, the only form in which the secret is stored.

func ParseInvitationSecret

func ParseInvitationSecret(value string) (InvitationHash, bool)

ParseInvitationSecret returns the hash an invitation's secret is stored under; false for a value no invitation was ever issued with, which needs no lookup.

type InvitationID

type InvitationID = id.Of[Invitation]

InvitationID identifies an invitation.

type MailFailure added in v0.3.0

type MailFailure string

MailFailure is the class of a failed send, the part an operator acts on.

const (
	// MailFailureConnection means the server could not be reached, or the
	// connection broke or timed out.
	MailFailureConnection MailFailure = "connection"
	// MailFailureTLS means TLS could not be established, the server did not
	// offer STARTTLS, or its certificate was not trusted.
	MailFailureTLS MailFailure = "tls"
	// MailFailureAuthentication means the server refused the username and
	// password, or they could not be sent safely.
	MailFailureAuthentication MailFailure = "authentication"
	// MailFailureRejected means the server refused the sender, a recipient or
	// the mail.
	MailFailureRejected MailFailure = "rejected"
)

The classes of a failed send.

type MailKind added in v0.3.0

type MailKind string

MailKind is what a mail is for, which decides its template.

const (
	// MailTest is the mail an instance admin sends themselves to try the
	// SMTP settings.
	MailTest MailKind = "test"
	// MailPasswordReset carries the link a member asked for to set a new
	// password.
	MailPasswordReset MailKind = "password_reset"
	// MailInvitation carries the link that lets a person invited to the
	// instance, or to a project in it, set their first password.
	MailInvitation MailKind = "invitation"
	// MailWebhookDisabled tells those who manage a webhook subscription that
	// the platform disabled it for failing persistently.
	MailWebhookDisabled MailKind = "webhook_disabled"
)

The kinds of mail.

type Member

type Member struct {
	ID MemberID
	// Email is unique on the instance whatever its case, and kept as given.
	Email       string
	DisplayName string
	Status      MemberStatus
	// InstanceAdmin holds every permission in every project.
	InstanceAdmin bool
	// InstanceAdminProvider is the slug of the auth provider whose group
	// mapping made the member an instance admin, "" for one made by hand. Only
	// that provider takes it away.
	InstanceAdminProvider string
	// Locale is the console language the member chose, or "" to follow the
	// browser.
	Locale string
	// Provider is the slug of the auth provider whose SCIM token created or
	// adopted the member, "" for a member nobody provisioned. A provisioned
	// member's email, name and status follow that provider.
	Provider string
	// ExternalID is the provider's own identifier of the person, "" for none;
	// unique among the provider's members, and what a sign-in through the
	// provider is linked by.
	ExternalID string
	CreatedAt  time.Time
}

Member is a person who uses the management API or the console.

func NewInstanceAdmin

func NewInstanceAdmin(memberID MemberID, email, displayName string, now time.Time) (Member, error)

NewInstanceAdmin returns an active instance admin. Without a display name the member is named after the local part of their email.

func NewInvitedMember

func NewInvitedMember(memberID MemberID, email, displayName string, now time.Time) (Member, error)

NewInvitedMember returns a member invited to the instance, who holds no password until they accept their invitation and is no instance admin.

func NewProvisionedMember added in v0.3.0

func NewProvisionedMember(memberID MemberID, email, displayName string, now time.Time) (Member, error)

NewProvisionedMember returns the active member a single sign-on creates on a person's first sign-in. They hold no password: the identity provider is how they sign in. Without a display name, or with one over the bound, the member is named after what fits of it or of their email.

func NewSCIMMember added in v0.3.0

func NewSCIMMember(memberID MemberID, email, displayName, provider, externalID string, now time.Time) (Member, error)

NewSCIMMember returns the active member an identity provider provisions through SCIM, without a password: the provider's directory is how they sign in. Without a display name the member is named after their email.

func (Member) Adoptable added in v0.3.0

func (m Member) Adoptable() bool

Adoptable reports whether an identity provider may adopt m: they are active, no instance admin, and nobody provisions them.

func (Member) Adopted added in v0.3.0

func (m Member) Adopted(email, displayName, provider, externalID string) (Member, error)

Adopted returns m, a member the instance already knew, as the provider whose SCIM token adopts them provisions them from now on: the directory's email, name and external ID replace theirs.

func (Member) Deactivated

func (m Member) Deactivated() Member

Deactivated returns m offboarded: they can no longer sign in, and every credential they held is revoked with them.

func (Member) Edited

func (m Member) Edited(change MemberChange) (Member, error)

Edited returns m with change applied, the email and display name trimmed and held to the bounds of a new member's. Whether another member holds the email is the store's to judge. A member still invited is not made an instance admin (ErrMemberInvited).

func (Member) IsActiveInstanceAdmin

func (m Member) IsActiveInstanceAdmin() bool

IsActiveInstanceAdmin reports whether m can administer the instance now.

func (Member) Joined

func (m Member) Joined() Member

Joined returns m once they have set their first password: active.

func (Member) Profiled

func (m Member) Profiled(change ProfileChange, offered []string) (Member, error)

Profiled returns m with change applied: the display name trimmed and held to the bounds of a new member's, the locale one of offered, the console languages, or "" to follow the browser. The email and the instance admin switch are an instance admin's to change, never the member's own.

func (Member) Provisioned added in v0.3.0

func (m Member) Provisioned() bool

Provisioned reports whether an identity provider created or adopted the member through SCIM, so that its directory decides the member's email, name and status.

func (Member) Reactivated

func (m Member) Reactivated(holdsWayIn bool) Member

Reactivated returns m back on the instance: active when they hold a way to sign in with, a password or an identity at an auth provider, invited otherwise, to set a password through an invitation. Nothing revoked at their deactivation comes back.

func (Member) Synced added in v0.3.0

func (m Member) Synced(email, displayName *string) (Member, error)

Synced returns m with the email and display name a directory states, trimmed and held to the bounds of a new member's; a nil one is left as it is.

type MemberChange

type MemberChange struct {
	Email         *string
	DisplayName   *string
	InstanceAdmin *bool
}

MemberChange is an edit of a member by an instance admin; a nil field is left as it is.

type MemberID

type MemberID = id.Of[Member]

MemberID identifies a member.

type MemberStatus

type MemberStatus string

MemberStatus is where a member is in their life on the instance.

const (
	MemberInvited     MemberStatus = "invited"
	MemberActive      MemberStatus = "active"
	MemberDeactivated MemberStatus = "deactivated"
)

The member statuses. There is no deletion: an offboarded member is deactivated and keeps their history.

func ParseMemberStatus

func ParseMemberStatus(s string) (MemberStatus, bool)

ParseMemberStatus returns the status s names; false for none.

type Method

type Method string

Method is how a caller proved who they are.

const (
	MethodToken   Method = "token"
	MethodSession Method = "session"
)

The methods.

type NewGrantInput

type NewGrantInput struct {
	Project   workspace.ProjectID
	Member    Member
	Role      RoleName
	CreatedBy MemberID
	Now       time.Time
}

NewGrantInput is what a grant is made of.

type NewPersonalTokenInput

type NewPersonalTokenInput struct {
	Member MemberID
	Name   string
	// Scopes default to read alone; read is added to any write scope.
	Scopes    []Scope
	ExpiresAt *time.Time
	Now       time.Time
}

NewPersonalTokenInput is what a personal access token is made of.

type NewProjectTokenInput

type NewProjectTokenInput struct {
	Project workspace.ProjectID
	// Role is the one built-in role the token holds in Project, fixed for
	// its life.
	Role RoleName
	Name string
	// Scopes default to read alone; read is added to any write scope.
	Scopes    []Scope
	ExpiresAt *time.Time
	CreatedBy MemberID
	Now       time.Time
}

NewProjectTokenInput is what a project token is made of.

type NewSessionInput

type NewSessionInput struct {
	Member    MemberID
	Method    SignInMethod
	Provider  string
	ClientIP  netip.Addr
	UserAgent string
	Timeouts  SessionTimeouts
	Now       time.Time
}

NewSessionInput is what a session is opened with.

type Operation

type Operation struct {
	// Name is the operation's identifier in the document, for counting its
	// refusals.
	Name string
	// Requirement is a catalog permission or a reserved value.
	Requirement Requirement
	// SessionRequired operations refuse every API token, so a leaked token
	// can neither mint another credential nor lock its member out.
	SessionRequired bool
	// Read operations change nothing.
	Read bool
	// Scope is the scope a token needs, as ScopeOf derives it; "" for none.
	Scope Scope
	// OpenToProjectTokens marks the one kind of operation outside a project
	// a project token reaches: reading which token it is. Everywhere else a
	// project token reaches its own project only.
	OpenToProjectTokens bool
}

Operation is what one operation of the management API requires, as its OpenAPI document declares it.

func (Operation) InProject

func (op Operation) InProject() bool

InProject reports whether op requires a catalog permission, which is judged in the project the operation addresses.

type PasswordReset added in v0.3.0

type PasswordReset struct {
	ID     PasswordResetID
	Member MemberID
	Hash   PasswordResetHash
	// IssuedBy is the instance admin who issued the reset; zero for one the
	// member asked for themselves.
	IssuedBy  MemberID
	CreatedAt time.Time
	ExpiresAt time.Time
	// ConsumedAt is when the reset stopped being completable before it
	// expired: completed, or ended by the completion of another, by a
	// password change or by its member's deactivation. Nil while it is open.
	ConsumedAt *time.Time
}

PasswordReset is the one-time link that lets an active member set a new password.

func NewPasswordReset added in v0.3.0

func NewPasswordReset(resetID PasswordResetID, member, issuedBy MemberID, now time.Time, random io.Reader) (PasswordReset, secret.String)

NewPasswordReset issues a password reset of member, by issuedBy (zero for the member themselves), and returns it with its secret: 32 bytes drawn from random in unpadded base64url, shown once to whoever the reset is handed to and never stored.

func (PasswordReset) Open added in v0.3.0

func (r PasswordReset) Open(now time.Time, holder Member) bool

Open reports whether the reset can be completed at now by holder, its member: not consumed, not expired, and holder active. A member who was deactivated since the reset was issued has it consumed with their deactivation, and one still invited never holds a reset, so the status check only makes certain no link outlives either.

type PasswordResetCutoffs added in v0.3.0

type PasswordResetCutoffs struct {
	// EndedBy purges a password reset consumed, or expired, at or before it.
	EndedBy time.Time
}

PasswordResetCutoffs select the password resets the retention worker purges.

func PasswordResetCutoffsAt added in v0.3.0

func PasswordResetCutoffsAt(now time.Time) PasswordResetCutoffs

PasswordResetCutoffsAt returns the cutoffs at now.

type PasswordResetHash added in v0.3.0

type PasswordResetHash [sha256.Size]byte

PasswordResetHash is the SHA-256 of a password reset's secret, the only form in which the secret is stored.

func ParsePasswordResetSecret added in v0.3.0

func ParsePasswordResetSecret(value string) (PasswordResetHash, bool)

ParsePasswordResetSecret returns the hash a password reset's secret is stored under; false for a value no reset was ever issued with, which needs no lookup.

type PasswordResetID added in v0.3.0

type PasswordResetID = id.Of[PasswordReset]

PasswordResetID identifies a password reset.

type Permission

type Permission string

Permission is one action a role allows, named entity.verb.

const (
	// PermProjectRead covers every ordinary read in a project, its audit log
	// included.
	PermProjectRead Permission = "project.read"
	// PermProjectUpdate renames a project and changes its description.
	PermProjectUpdate Permission = "project.update"
	// PermEnvironmentManage creates, renames and deletes environments.
	PermEnvironmentManage Permission = "environment.manage"
	// PermEnvironmentProtect protects an environment, so its ruleset changes
	// only through approved change requests, or stops protecting it.
	PermEnvironmentProtect Permission = "environment.protect"
	// PermDeclarationManage creates, renames and deletes unit types and
	// attributes.
	PermDeclarationManage Permission = "declaration.manage"
	// PermGrantManage makes and removes grants.
	PermGrantManage Permission = "grant.manage"
	// PermProjectTokenManage lists, creates and revokes project tokens.
	PermProjectTokenManage Permission = "project_token.manage"
	// PermFlagEdit creates flags and changes their definition.
	PermFlagEdit Permission = "flag.edit"
	// PermFlagArchive archives, restores and deletes flags.
	PermFlagArchive Permission = "flag.archive"
	// PermFlagConfigurationUpdate replaces a flag's configuration in an
	// environment.
	PermFlagConfigurationUpdate Permission = "flag_configuration.update"
	// PermFlagConfigurationKill switches a flag off in an environment with
	// the kill switch.
	PermFlagConfigurationKill Permission = "flag_configuration.kill"
	// PermFlagConfigurationRevert writes a flag's configuration in an
	// environment again as an earlier version had it. It is apart from
	// update so that whoever is on call may undo a change without being
	// allowed to write rules.
	PermFlagConfigurationRevert Permission = "flag_configuration.revert"
	// PermSegmentEdit creates segments and changes them.
	PermSegmentEdit Permission = "segment.edit"
	// PermSegmentDelete deletes segments.
	PermSegmentDelete Permission = "segment.delete"
	// PermSDKKeyManage creates, renames, rotates and revokes an
	// environment's SDK keys and edits their allowed origins. Reading them
	// is project.read: a listed key never carries its value.
	PermSDKKeyManage Permission = "sdk_key.manage"
	// PermExperimentEdit creates experiments, changes them, moves them
	// through their statuses and acknowledges their alerts.
	PermExperimentEdit Permission = "experiment.edit"
	// PermExperimentDelete deletes draft experiments.
	PermExperimentDelete Permission = "experiment.delete"
	// PermChangeRequestPropose proposes changes as change requests: creates
	// them, edits, rebases, opens and cancels its holder's own, and copies
	// any into a new draft.
	PermChangeRequestPropose Permission = "change_request.propose"
	// PermChangeRequestApprove decides change requests: approves and
	// rejects another's, and cancels or applies another's.
	PermChangeRequestApprove Permission = "change_request.approve"
	// PermWebhookManage creates, reads, edits and deletes a project's
	// webhook subscriptions. Reading them needs it too: a subscription
	// says where a project's changes are sent.
	PermWebhookManage Permission = "webhook.manage"
	// PermSinkManage creates, reads, edits and deletes a project's sinks and
	// rotates a webhook sink's secret. Reading them needs it too: a sink's
	// configuration names internal hosts, buckets and URLs that carry
	// tokens, which everyone who can read the project may not see.
	PermSinkManage Permission = "sink.manage"
	// PermProjectDelete deletes a project with everything in it.
	PermProjectDelete Permission = "project.delete"
	// PermProjectImport imports a project document into a project, writing
	// its configuration whatever protects an environment.
	PermProjectImport Permission = "project.import"
)

The permissions of the catalog.

func EffectivePermissions

func EffectivePermissions(c Caller, project workspace.ProjectID, grants []RoleName) []Permission

EffectivePermissions returns what c holds in project, in catalog order, given the roles of the grants c's member holds there. An instance admin holds every permission without a grant; a member, the union of their grants' roles; a project token, its role in its own project, without the permissions that change who has access. A token's permissions are further narrowed to those whose scope it carries.

type PermissionSpec

type PermissionSpec struct {
	Name Permission
	// Scope is the token scope the permission falls under: a token exercises
	// the permission only when it carries the scope.
	Scope Scope
	// MembersOnly marks a permission that changes who has access or whose
	// review a change needs, which a project token never exercises whatever
	// its role, so a pipeline credential cannot be turned into a way in or
	// around review.
	MembersOnly bool
	// TokenRefusal, for a permission kept to members, is how a project
	// token whose role holds it is refused, when that says more than the
	// permission missing.
	TokenRefusal error
}

PermissionSpec is one row of the permission catalog.

func Catalog

func Catalog() []PermissionSpec

Catalog returns the permission catalog.

func PermissionNamed

func PermissionNamed(name string) (PermissionSpec, bool)

PermissionNamed returns the catalog's permission called name.

type ProfileChange

type ProfileChange struct {
	DisplayName *string
	// Locale is the console language chosen; "" follows the browser.
	Locale *string
}

ProfileChange is a member's edit of themself; a nil field is left as it is.

type ProjectAccess

type ProjectAccess struct {
	// Project is the project addressed; zero when no project has the key the
	// request names.
	Project workspace.ProjectID
	// Permissions are the caller's effective permissions there.
	Permissions []Permission
}

ProjectAccess is what the caller holds in the project an operation addresses, as the seam found it before judging the operation.

type Requirement

type Requirement string

Requirement is what an operation requires of its caller: a catalog permission, judged in the operation's project, or one of the reserved values below.

const (
	// RequirePublic: anyone, without credentials; a credential presented is
	// still authenticated, and a bad one refused.
	RequirePublic Requirement = "public"
	// RequireMember: any credential acting for a member, whatever their
	// grants; a project token only where the operation is open to it.
	RequireMember Requirement = "member"
	// RequireInstanceAdmin: an instance admin, whose token must carry
	// instance:admin to write and read to read.
	RequireInstanceAdmin Requirement = "instance_admin"
)

The requirements an operation may declare besides a catalog permission.

type Reservation

type Reservation struct {
	Attempt
	// KnownSource is whether the attempt comes from a source known to the
	// member its email names: its failures are then counted, and locked,
	// under the email and that source alone, and the email's lock does not
	// refuse it. An email no member has knows no source.
	KnownSource bool
	// LockedUntil is when the failures the attempt is counted under, locked
	// before this attempt, unlock; zero when they were not locked, and then
	// the attempt counts as a failure.
	LockedUntil time.Time
	// Failures are the consecutive failures the attempt is counted under,
	// this one included; 0 when the attempt was not counted against the
	// email.
	Failures int
	// LocksUntil is when the lock this attempt's failure starts ends, as
	// stored; zero when it starts none.
	LocksUntil time.Time
	// SourceFailures are the failures of the source in the current window,
	// this one included.
	SourceFailures int
	// WindowStart is the start of the source's window the attempt counts in.
	WindowStart time.Time
}

Reservation is what reserving a failure for an attempt before its password is verified found: whether the email or the source refuses the attempt, the failures counted with this one, and the lock it starts.

func (Reservation) Locks

func (r Reservation) Locks() (bool, time.Duration)

Locks reports whether this attempt, should it fail, locks the email, and for how long.

func (Reservation) Refusal

func (r Reservation) Refusal() error

Refusal returns why the attempt is refused before its password is verified, judged at the time the attempt was reserved, or nil when it is verified: a throttled source first, then a locked email, or, from a source known to its member, the lock of that source's own failures on it, which answers the same. A refused attempt takes no hashing slot.

type Role

type Role struct {
	Name        RoleName
	Permissions []Permission
}

Role is a fixed list of permissions.

func RoleNamed

func RoleNamed(name RoleName) (Role, bool)

RoleNamed returns the built-in role called name.

func Roles

func Roles() []Role

Roles returns the built-in roles, the most powerful first.

type RoleName

type RoleName string

RoleName names a built-in role.

const (
	RoleOwner      RoleName = "owner"
	RoleMaintainer RoleName = "maintainer"
	RoleDeveloper  RoleName = "developer"
	RoleViewer     RoleName = "viewer"
)

The built-in roles, fixed by the release so a name means the same on every instance.

type SMTPChange added in v0.3.0

type SMTPChange struct {
	Host     string
	Port     int
	Security SMTPSecurity
	Username string
	Password *string
	From     string
}

SMTPChange is a write of the SMTP settings. Password is write only: nil keeps the stored one.

func (SMTPChange) Check added in v0.3.0

func (c SMTPChange) Check(stored SMTPSettings) (SMTPChange, error)

Check returns the change with its host, username and sender trimmed, or invalid_smtp_settings naming each field that breaks a rule: a host of 1 to 253 characters without spaces, a port from 1 to 65535, a known security, a sender that is one address, a username on one line, a username and a password together (a password the change leaves out is the one stored in stored, zero when nothing is), a stored password kept only while the host, port, security and username it was given for stay as they are (otherwise the write would send it somewhere its owner never chose, so the change must give the password again), and credentials over no security only to this machine, since the client refuses to send them in the clear and nothing could ever be sent.

type SMTPSecurity added in v0.3.0

type SMTPSecurity string

SMTPSecurity is how the connection to the SMTP server is secured.

const (
	// SMTPStartTLS upgrades a plain connection with STARTTLS, which the
	// server must offer.
	SMTPStartTLS SMTPSecurity = "starttls"
	// SMTPTLS speaks TLS from the first byte.
	SMTPTLS SMTPSecurity = "tls"
	// SMTPNone secures nothing.
	SMTPNone SMTPSecurity = "none"
)

The ways a connection to the SMTP server is secured.

type SMTPSettings added in v0.3.0

type SMTPSettings struct {
	Host     string
	Port     int
	Security SMTPSecurity
	// Username is who to authenticate as; "" for no authentication.
	Username string
	// PasswordSealed is the password sealed under the instance's secret key;
	// "" when none is stored. It is never shown: only SMTPSettings.PasswordSet
	// is.
	PasswordSealed string
	// From is the sender of every mail: one address, optionally with a
	// display name.
	From      string
	UpdatedAt time.Time
}

SMTPSettings are the mail server the instance sends its mail through, as stored.

func (SMTPSettings) PasswordSet added in v0.3.0

func (s SMTPSettings) PasswordSet() bool

PasswordSet reports whether a password is stored.

type Scope

type Scope string

Scope is what an API token is allowed to touch. Scopes narrow a token's permissions and never add to them.

const (
	ScopeRead             Scope = "read"
	ScopeFlagsWrite       Scope = "flags:write"
	ScopeExperimentsWrite Scope = "experiments:write"
	ScopeProjectAdmin     Scope = "project:admin"
	ScopeInstanceAdmin    Scope = "instance:admin"
)

The scopes a token can carry.

func AllScopes

func AllScopes() []Scope

AllScopes returns every scope a token can carry, read first.

func ScopeOf

func ScopeOf(requirement Requirement, read bool) Scope

ScopeOf returns the scope a token needs for an operation requiring requirement, a read operation or not; "" when any token will do.

type Session

type Session struct {
	ID     SessionID
	Hash   SessionHash
	Member MemberID
	Method SignInMethod
	// Provider is the slug of the auth provider a single sign-on session
	// opened through; empty for a local one.
	Provider string
	// ClientIP and UserAgent describe the device the session opened on, so
	// a member notices a session they do not recognise.
	ClientIP   netip.Addr
	UserAgent  string
	CreatedAt  time.Time
	LastSeenAt time.Time
	// ExpiresAt is when the absolute timeout in force at sign-in ends the
	// session; a lower timeout set later ends it sooner.
	ExpiresAt time.Time
	RevokedAt *time.Time
}

Session is a member's sign-in to the console, held server-side and referred to by a cookie.

func LiveSessions

func LiveSessions(sessions []Session, holder Member, now time.Time, t SessionTimeouts) []Session

LiveSessions returns the sessions of holder that still sign them in at now, in the order given.

func NewSession

func NewSession(sessionID SessionID, in NewSessionInput, random io.Reader, key []byte) (Session, secret.String)

NewSession opens a session and returns it with the value of its cookie: 32 bytes drawn from random and their HMAC-SHA256 tag under key, each in unpadded base64url, joined by a dot. The tag tells a cookie the server did not issue apart without a lookup.

func (Session) End

func (s Session) End(t SessionTimeouts) time.Time

End is when the absolute timeout ends the session under the timeouts in force: the earlier of the expiry stored at sign-in and its opening plus the current absolute timeout, so a lowered timeout shortens it and a raised one never lengthens it.

func (Session) Live

func (s Session) Live(now time.Time, holder Member, t SessionTimeouts) bool

Live reports whether the session still signs holder in at now under the timeouts in force: it is not revoked, its member is active, its last request is within the idle timeout, and neither the expiry stored at sign-in nor its opening plus the current absolute timeout has passed. The current timeouts are applied to every live session, so lowering one takes effect at once.

func (Session) NeedsTouch

func (s Session) NeedsTouch(now time.Time) bool

NeedsTouch reports whether a request at now should write the session's last request time: at most once a minute.

type SessionCutoffs

type SessionCutoffs struct {
	LastSeenBy time.Time
	CreatedBy  time.Time
	ExpiresBy  time.Time
}

SessionCutoffs are the instants that end a session at a given time, as the retention worker selects ended sessions in bulk: a session is ended when it is revoked, or its last request, its opening or its stored expiry is at or before the cutoff for it.

func EndedSessionCutoffs

func EndedSessionCutoffs(now time.Time, t SessionTimeouts) SessionCutoffs

EndedSessionCutoffs returns the cutoffs that end, at now under the timeouts in force, exactly the sessions Live no longer admits, whatever their member's status: a member who is not active has their sessions revoked when their status changes.

func (SessionCutoffs) Ended

func (c SessionCutoffs) Ended(s Session) bool

Ended reports whether the cutoffs end s.

type SessionHash

type SessionHash [sha256.Size]byte

SessionHash is the SHA-256 of the random part of a session cookie, the only form in which the session's secret is stored.

func ParseSessionCookie

func ParseSessionCookie(value string, key []byte) (SessionHash, bool)

ParseSessionCookie returns the hash a session cookie's value is stored under, when the value carries the tag key gives its random part; false for any other value, which is dropped without a lookup, so spraying forged cookies costs the database nothing.

type SessionID

type SessionID = id.Of[Session]

SessionID identifies a session.

type SessionTimeouts

type SessionTimeouts struct {
	Idle     time.Duration
	Absolute time.Duration
}

SessionTimeouts end a session: after Idle without a request, and after Absolute in all, whichever comes first.

type SignInMethod

type SignInMethod string

SignInMethod is how a member proved who they are when a session opened.

const (
	// SignInLocal is signing in with an email and a password.
	SignInLocal SignInMethod = "local"
	// SignInOIDC is signing in through an OIDC auth provider.
	SignInOIDC SignInMethod = "oidc"
	// SignInSAML is signing in through a SAML auth provider.
	SignInSAML SignInMethod = "saml"
)

The ways a member signs in.

type TokenHash

type TokenHash [sha256.Size]byte

TokenHash is the SHA-256 of a token's whole value, the only form in which the value is stored.

func ParseTokenValue

func ParseTokenValue(value string) (TokenHash, error)

ParseTokenValue returns the hash of a well-formed token value. Any other value is an invalid token, refused without a lookup.

type TokenKind

type TokenKind string

TokenKind says whom an API token acts for.

const (
	// TokenPersonal acts for the member who holds it.
	TokenPersonal TokenKind = "personal"
	// TokenProject holds one role in one project and acts for no member.
	TokenProject TokenKind = "project"
)

The kinds of API token.

type TokenValue

type TokenValue struct {
	Value secret.String
	// Hint is the prefix and the first four characters, enough for a member
	// to tell their tokens apart and for the audit log to name one.
	Hint string
	Hash TokenHash
}

TokenValue is a newly drawn token value: shown once, then only its hint and hash remain.

func NewTokenValue

func NewTokenValue(kind TokenKind, random io.Reader) TokenValue

NewTokenValue draws a token value of kind from random: the kind's prefix and 40 base62 characters, about 238 bits.

Jump to

Keyboard shortcuts

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