access

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 17 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 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 DefaultAuthSettings = AuthSettings{
	SessionIdleTimeout:     DefaultSessionTimeouts.Idle,
	SessionAbsoluteTimeout: DefaultSessionTimeouts.Absolute,
	TokenMaxLifetime:       365 * 24 * time.Hour,
	PasswordMinLength:      MinPasswordLength,
}

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 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 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 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 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.

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 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 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 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 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 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 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
}

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.

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 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
	// 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 is not deactivated; an invited member may hold grants before they join.

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 GrantSource = "manual"

GrantManual is a grant made by hand, by a member managing the project's grants.

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
}

Invitation is the one-time link that lets an invited member set their first password.

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) 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.

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 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 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
	// Locale is the console language the member chose, or "" to follow the
	// browser.
	Locale    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 (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.

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) Reactivated

func (m Member) Reactivated(holdsPassword bool) Member

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

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
	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 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"
	// PermProjectDelete deletes a project with everything in it.
	PermProjectDelete Permission = "project.delete"
)

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 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
	// 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 SignInMethod = "local"

SignInLocal is signing in with an email and a password. Identity providers join it with single sign-on.

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