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
- Variables
- func Authorize(c Caller, op Operation, in *ProjectAccess) error
- func CheckGrantorCap(held []Permission, role Role) error
- func CheckPassword(password, email string, minLength int) error
- func CheckPasswordAt(pointer, password, email string, minLength int) error
- func CheckScopesHeld(c Caller, scopes []Scope) error
- func CheckTokenExpiry(expiresAt *time.Time, now time.Time, s AuthSettings) error
- func GeneratePassword(email string, random io.Reader) secret.String
- func IsRequirement(r Requirement) bool
- func KeepAnInstanceAdmin(before, after Member, others int) error
- func LockoutSchedule() []time.Duration
- func LockoutWindow(failures int) time.Duration
- func MaskEmail(email string) string
- func NewPersonalToken(tokenID APITokenID, in NewPersonalTokenInput, random io.Reader) (APIToken, TokenValue, error)
- func NewProjectToken(tokenID APITokenID, in NewProjectTokenInput, random io.Reader) (APIToken, TokenValue, error)
- func PasswordRule(err error) string
- func SourceOf(ip netip.Addr) netip.Prefix
- func UnknownRoleError(pointer string) error
- type APIToken
- type APITokenID
- type Attempt
- type AuthSettings
- type Caller
- type FailureCutoffs
- type Grant
- type GrantID
- type GrantSource
- type Invitation
- type InvitationCutoffs
- type InvitationHash
- type InvitationID
- type Member
- func (m Member) Deactivated() Member
- func (m Member) Edited(change MemberChange) (Member, error)
- func (m Member) IsActiveInstanceAdmin() bool
- func (m Member) Joined() Member
- func (m Member) Profiled(change ProfileChange, offered []string) (Member, error)
- func (m Member) Reactivated(holdsPassword bool) Member
- type MemberChange
- type MemberID
- type MemberStatus
- type Method
- type NewGrantInput
- type NewPersonalTokenInput
- type NewProjectTokenInput
- type NewSessionInput
- type Operation
- type Permission
- type PermissionSpec
- type ProfileChange
- type ProjectAccess
- type Requirement
- type Reservation
- type Role
- type RoleName
- type Scope
- type Session
- type SessionCutoffs
- type SessionHash
- type SessionID
- type SessionTimeouts
- type SignInMethod
- type TokenHash
- type TokenKind
- type TokenValue
Constants ¶
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.
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.
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.
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.
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.
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.
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.
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 ¶
var DefaultAuthSettings = AuthSettings{ SessionIdleTimeout: DefaultSessionTimeouts.Idle, SessionAbsoluteTimeout: DefaultSessionTimeouts.Absolute, TokenMaxLifetime: 365 * 24 * time.Hour, PasswordMinLength: MinPasswordLength, }
DefaultAuthSettings are the settings of a fresh instance.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 LockoutSchedule ¶
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 ¶
LockoutWindow returns how long the failures-th consecutive failure on an email locks it, 0 below the threshold.
func MaskEmail ¶
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 ¶
PasswordRule returns the rule of the password policy err reports broken, or "" when err is no refusal of the policy.
func SourceOf ¶
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 ¶
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.
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.
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 ¶
SessionCaller returns the caller signed in to s as holder.
func TokenCaller ¶
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
}
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.
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.
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 ¶
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 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 ¶
NewInstanceAdmin returns an active instance admin. Without a display name the member is named after the local part of their email.
func NewInvitedMember ¶
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 ¶
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 ¶
IsActiveInstanceAdmin reports whether m can administer the instance now.
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 ¶
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 ¶
MemberChange is an edit of a member by an instance admin; a nil field is left as it is.
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 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.
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" // 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" )
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, which a
// project token never exercises whatever its role, so a pipeline
// credential cannot be turned into a way in.
MembersOnly bool
}
PermissionSpec is one row of 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
// LockedUntil is when an email locked before this attempt unlocks; zero
// when it was not locked, and then the attempt counts as a failure.
LockedUntil time.Time
// Failures are the consecutive failures on the email, 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. A refused attempt takes no hashing slot.
type Role ¶
type Role struct {
Name RoleName
Permissions []Permission
}
Role is a fixed list of permissions.
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 ¶
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 ¶
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.
type SessionCutoffs ¶
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 ¶
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 SessionTimeouts ¶
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 ¶
TokenHash is the SHA-256 of a token's whole value, the only form in which the value is stored.
func ParseTokenValue ¶
ParseTokenValue returns the hash of a well-formed token value. Any other value is an invalid token, refused without a lookup.
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.