directory

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package directory is the identity and tenancy data an auth deployment keeps: users and the external identities they sign in with, groups and their members, teams, projects (each in one team), service accounts (each in one project), roles, and the role bindings that grant them to users, groups, service accounts or every authenticated principal. It validates rows, runs the grant check on every write that hands out a permission, invalidates a user's tokens and sessions when the account changes, and reports each committed write to a Notifier. A provisioning source, such as a SCIM client, writes through the narrower Provisioner instead, which reaches only the users and groups that source created.

Every read and write goes through the Stores interfaces: auth/store/postgres is the ready-made implementation, directory/memstore an in-memory one, and directory/storetest the behaviour any other implementation must share. The package also provides the default rbac.ScopeResolver over the team and project hierarchy.

Out of scope: authenticating callers (auth/authn, auth/session, auth/oidc), authorizing the calls themselves (a product's handler asks auth/rbac before calling in), manifests, and HTTP handlers. Kinds and verbs in role rules are the product's vocabulary, handed in through Config.

Index

Constants

View Source
const (
	OwnerSystem  = "system"
	OwnerUser    = "user"
	OwnerTeam    = "team"
	OwnerProject = "project"
)

Owner kinds the module gives a meaning to. Any other kind is the product's and passes through untouched.

View Source
const IdentitySeparator = "|"

IdentitySeparator joins an identity's issuer and subject in its stored form; an issuer must not contain it.

View Source
const MaxNameLen = 63

MaxNameLen is the DNS-1123 label limit a row name obeys.

View Source
const ReservedGroupPrefix = "system:"

ReservedGroupPrefix marks group names that stand for a built-in set of principals rather than a stored group, such as the all-authenticated subject. A stored group may not claim one.

Variables

View Source
var (
	// ErrNotFound reports an operation on a row that does not exist.
	ErrNotFound = errors.New("directory: not found")
	// ErrInvalid reports a row that fails validation or references a row that does not exist.
	ErrInvalid = errors.New("directory: invalid")
	// ErrConflict reports a write that would duplicate a unique name, username, email or identity.
	ErrConflict = errors.New("directory: conflict")
	// ErrEmailTaken is the ErrConflict of an account whose email another account holds.
	ErrEmailTaken = fmt.Errorf("%w: email is taken", ErrConflict)
	// ErrStaleResourceVersion reports a conditional update whose ResourceVersion no longer matches the stored row.
	ErrStaleResourceVersion = errors.New("directory: resource changed since it was read")
)
View Source
var AllAuthenticated = Subject{Kind: SubjectGroup, Name: ReservedGroupPrefix + "authenticated"}

AllAuthenticated is the reserved subject every authenticated principal acts under. It is stored as a group subject so a binding to it needs no membership; its Key is "group:system:authenticated", which a product adds to every principal's subjects.

View Source
var ErrForeign = errors.New("directory: row belongs to another source")

ErrForeign reports a provisioning source reaching for a row it did not provision: a local row, or another source's. It always comes wrapped together with ErrNotFound, so the source cannot tell a foreign row from a missing one.

View Source
var ErrManaged = errors.New("directory: managed by a provisioning source")

ErrManaged reports a write to a group that a provisioning source manages, made by someone else without Writer.Force. The error returned is a *ManagedError.

View Source
var Global = rbac.Scope{Kind: OwnerSystem}

Global is the scope every chain ends in and the scope a binding names to apply everywhere.

Functions

func CanonicalIssuer

func CanonicalIssuer(issuer string) string

CanonicalIssuer is issuer without trailing slashes, the form identities are stored and looked up in: a provider and a configuration that disagree only on the slash name one issuer.

func ChangesCredentials

func ChangesCredentials(stored, u *User) bool

ChangesCredentials reports whether writing u over stored, nil for a new account, sets, changes or clears its password or primary sign-in identity. Either lets whoever writes it sign in as the account.

func FormatResourceVersion

func FormatResourceVersion(v int64) string

FormatResourceVersion renders a stored version counter as a ResourceVersion.

func NewID

func NewID() string

NewID returns a fresh UUIDv7. Panics only if the system random source fails.

func Slugify

func Slugify(text string) string

Slugify derives a name from free text: lowercased, every run of other characters turned into one dash, dashes trimmed from both ends, cut to MaxNameLen. It returns "" when nothing usable is left.

func UniqueName

func UniqueName(base string, taken func(name string) bool) string

UniqueName returns base when taken reports it free, else the first free of base-2, base-3, …, each cut to fit MaxNameLen.

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a DNS-1123 label of at most MaxNameLen characters.

Types

type Change

type Change struct {
	Kind Kind
	Op   Op
	ID   string
}

Change is one committed write. A group membership change is an OpUpsert of the group. A delete is reported for the row named, not for the rows its store cascaded to.

type Config

type Config struct {
	Stores Stores
	Grants GrantChecker
	// Kinds and Verbs are the product's vocabulary. A role rule must name entries of them or the wildcard, and the grant check expands a wildcard over them. Nil accepts any name and checks a wildcard as itself.
	Kinds []string
	Verbs []string
	// Notifier hears every committed write; nil drops them.
	Notifier Notifier
	// Revoker ends a user's sessions when the account is disabled, deleted or its roles change; nil leaves sessions alone.
	Revoker Revoker
}

Config wires a Directory.

type Directory

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

Directory runs the operations. It holds no state beyond its Config and the writer WithWriter set, and is safe for concurrent use when the stores are.

func New

func New(cfg Config) (*Directory, error)

New returns a Directory over cfg. Every store and the grant checker are required, so no grant is ever made unchecked.

func (*Directory) AddFirstIdentity

func (d *Directory) AddFirstIdentity(ctx context.Context, userID string, id Identity) error

AddFirstIdentity links id to an account that holds no identity, as its primary, and kills the account's tokens and sessions. The store checks and writes in one step, so of two concurrent first links to one account only one succeeds; the other, like a link to an account that already has an identity, is ErrConflict.

func (*Directory) AddGroupMember

func (d *Directory) AddGroupMember(ctx context.Context, p *principal.Principal, groupID, userID string) error

AddGroupMember adds the user to the group; adding a member twice does nothing. The new member acts under every binding naming the group, so p must pass the grant check for each of those roles at the binding's scope. The write is conditional on the version read, so a concurrent membership change fails with ErrStaleResourceVersion instead of being lost.

func (*Directory) AddIdentity

func (d *Directory) AddIdentity(ctx context.Context, userID string, id UserIdentity) error

AddIdentity links an identity to the account, or updates its external id when the account already holds it, and kills the account's tokens and sessions: a new way to sign in is a credential change. An identity another account holds is ErrConflict. The first identity of an account with none becomes its primary.

func (*Directory) CheckMembershipGrants

func (d *Directory) CheckMembershipGrants(ctx context.Context, p *principal.Principal, g *Group) error

CheckMembershipGrants runs the grant check that writing g would run, against the stored group with g's id (none for a create), and writes nothing. A product planning several writes calls it to refuse a group before any write lands; the write checks again.

func (*Directory) CreateGroup

func (d *Directory) CreateGroup(ctx context.Context, p *principal.Principal, g *Group) error

CreateGroup adds a group. A binding may already name it, so members go through the grant check as AddGroupMember's do; a group with no members needs no principal. An empty owner is the system.

func (*Directory) CreateProject

func (d *Directory) CreateProject(ctx context.Context, p *Project) error

CreateProject adds a project to the team named by its spec.

func (*Directory) CreateRole

func (d *Directory) CreateRole(ctx context.Context, r *Role) error

CreateRole adds a role. It grants nothing until a binding names it, so it needs no grant check. An empty owner is the system.

func (*Directory) CreateRoleBinding

func (d *Directory) CreateRoleBinding(ctx context.Context, p *principal.Principal, b *RoleBinding) error

CreateRoleBinding grants a role to the binding's subjects at its scope. Binding hands out every permission in the role, so p must already hold each one there.

func (*Directory) CreateServiceAccount

func (d *Directory) CreateServiceAccount(ctx context.Context, sa *ServiceAccount) error

CreateServiceAccount adds a service account to the project named by its spec.

func (*Directory) CreateTeam

func (d *Directory) CreateTeam(ctx context.Context, t *Team) error

CreateTeam adds a team. An empty owner is the system.

func (*Directory) CreateUser

func (d *Directory) CreateUser(ctx context.Context, p *principal.Principal, u *User) error

CreateUser adds an account, minting its id when it has none. Roles on a new account go through the grant check like any role change; an account with no roles needs no principal, so p may be nil for self-registration. A non-nil p must be an admin to create an account carrying a password or identity.

func (*Directory) DeleteGroup

func (d *Directory) DeleteGroup(ctx context.Context, id string) error

DeleteGroup removes the group, refusing a managed one as UpdateGroup does. A binding naming it by name keeps the name, which may still match a group an identity provider asserts.

func (*Directory) DeleteProject

func (d *Directory) DeleteProject(ctx context.Context, id string) error

DeleteProject removes the project; its store takes the project's service accounts and the bindings scoped to it with it.

func (*Directory) DeleteRole

func (d *Directory) DeleteRole(ctx context.Context, id string) error

DeleteRole removes the role; its store takes every binding of it.

func (*Directory) DeleteRoleBinding

func (d *Directory) DeleteRoleBinding(ctx context.Context, id string) error

DeleteRoleBinding removes the binding. Taking a grant away needs no grant check.

func (*Directory) DeleteServiceAccount

func (d *Directory) DeleteServiceAccount(ctx context.Context, id string) error

DeleteServiceAccount removes the service account; its store drops it from every binding.

func (*Directory) DeleteTeam

func (d *Directory) DeleteTeam(ctx context.Context, id string) error

DeleteTeam removes the team; its store takes the team's projects, their service accounts, and every binding scoped to the team or one of its projects with it, so no binding outlives its scope.

func (*Directory) DeleteUser

func (d *Directory) DeleteUser(ctx context.Context, id string) error

DeleteUser removes the account; its store drops it from every group and binding, and its sessions end.

func (*Directory) DisableUser

func (d *Directory) DisableUser(ctx context.Context, id string) error

DisableUser disables the account: its token version is bumped and its sessions end. Disabling a disabled account does nothing.

func (*Directory) EnableUser

func (d *Directory) EnableUser(ctx context.Context, id string) error

EnableUser re-enables the account. The token version is bumped in the same write, so a token minted before the account was disabled stays dead.

func (*Directory) Provisioner

func (d *Directory) Provisioner(source string) (*Provisioner, error)

Provisioner returns the directory as source sees it. Every row it creates is stamped with source, so two clients sharing a source share their rows.

func (*Directory) RemoveGroupMember

func (d *Directory) RemoveGroupMember(ctx context.Context, groupID, userID string) error

RemoveGroupMember removes the user from the group; removing a non-member does nothing. Taking a membership away needs no grant check.

func (*Directory) RemoveIdentities

func (d *Directory) RemoveIdentities(ctx context.Context, userID string) error

RemoveIdentities unlinks every identity of the account in one write and kills its tokens and sessions; an account with none is left alone. An account without a password keeps them, so it keeps a way to sign in.

func (*Directory) RemoveIdentity

func (d *Directory) RemoveIdentity(ctx context.Context, userID string, id Identity) error

RemoveIdentity unlinks an identity from the account and kills its tokens and sessions, any of which may have signed in with it. The last identity of an account without a password stays, so the account keeps a way to sign in. Removing the primary makes the oldest remaining identity primary.

func (*Directory) Stores

func (d *Directory) Stores() Stores

Stores returns the stores the directory writes through, for reads.

func (*Directory) UnlinkedUsersByExternalID

func (d *Directory) UnlinkedUsersByExternalID(ctx context.Context, externalID string) ([]*User, error)

UnlinkedUsersByExternalID returns the accounts a provisioning source created with externalID that hold no identity yet, oldest first: the accounts a product may link a first sign-in to. Two sources may hold the same id, so more than one may come back.

func (*Directory) UpdateGroup

func (d *Directory) UpdateGroup(ctx context.Context, p *principal.Principal, g *Group) error

UpdateGroup replaces the group with id g.Meta.ID, members included; adding a member, renaming or re-enabling a group with members goes through the grant check as AddGroupMember does. A group a provisioning source manages is refused with ErrManaged unless the writer is that source or forced.

func (*Directory) UpdateProject

func (d *Directory) UpdateProject(ctx context.Context, p *Project) error

UpdateProject replaces the project with id p.Meta.ID; changing TeamID moves it to another team.

func (*Directory) UpdateRole

func (d *Directory) UpdateRole(ctx context.Context, p *principal.Principal, r *Role) error

UpdateRole replaces the role with id r.Meta.ID. The new rules change what every binding of the role grants, so p must pass the grant check at each scope the role is bound at, as creating those bindings would have required.

func (*Directory) UpdateRoleBinding

func (d *Directory) UpdateRoleBinding(ctx context.Context, p *principal.Principal, b *RoleBinding) error

UpdateRoleBinding replaces the binding with id b.Meta.ID, with the grant check of a create.

func (*Directory) UpdateServiceAccount

func (d *Directory) UpdateServiceAccount(ctx context.Context, sa *ServiceAccount) error

UpdateServiceAccount replaces the service account with id sa.Meta.ID; changing ProjectID moves it to another project.

func (*Directory) UpdateTeam

func (d *Directory) UpdateTeam(ctx context.Context, t *Team) error

UpdateTeam replaces the team with id t.Meta.ID.

func (*Directory) UpdateUser

func (d *Directory) UpdateUser(ctx context.Context, p *principal.Principal, u *User) error

UpdateUser replaces the account with id u.ID; a zero u.External keeps the stored one. The write is conditional on u.ResourceVersion, or on the version read here when it is empty, so a concurrent change fails with ErrStaleResourceVersion instead of being lost. A role change goes through the grant check for every role added or removed and ends the user's sessions, which carry the roles they logged in with. Changing the password or primary identity needs an admin p. Disabling, re-enabling or changing the password or primary identity bumps the token version in the same write, so no token minted before survives, and ends the sessions. u.TokenVersion is not refreshed and u.ResourceVersion is cleared; read the user back for them.

func (*Directory) UpdateUserRemovingIdentities

func (d *Directory) UpdateUserRemovingIdentities(ctx context.Context, p *principal.Principal, u *User) error

UpdateUserRemovingIdentities is UpdateUser for an account left with no identity: u.Identity must be zero, and every identity the account holds is unlinked in the same store write, so the edit and the removal land together or not at all. One it would leave without a password is ErrInvalid, so the account keeps a way to sign in.

func (*Directory) WithWriter

func (d *Directory) WithWriter(w Writer) *Directory

WithWriter returns a directory whose writes come from w. The receiver is left as it was.

type External

type External struct {
	Source string
	ID     string
}

External is the provisioning source, such as a SCIM client, a row came from and that source's id for it. Source scopes ID, so two sources may use the same id; a source may hold a row it sent no id for.

func (External) IsZero

func (e External) IsZero() bool

IsZero reports whether no source is set.

type GrantChecker

type GrantChecker interface {
	CheckGrant(ctx context.Context, p *principal.Principal, role rbac.Role, scope rbac.Scope, kinds, verbs []string) error
}

GrantChecker refuses a grant the caller could not make itself; *rbac.Engine satisfies it.

type Group

type Group struct {
	Meta Metadata
	Spec GroupSpec
}

Group is a named set of users that a binding can name as a subject.

func (*Group) IsEnabled

func (g *Group) IsEnabled() bool

IsEnabled reports whether the group is enabled.

type GroupSpec

type GroupSpec struct {
	// MemberIDs are user ids in the order they were added.
	MemberIDs []string
	// Enabled nil means enabled.
	Enabled *bool
	// External is the provisioning source that manages the group and its id there; see Writer. An update that leaves it zero keeps the stored one.
	External External
	// Attributes are product fields stored next to the spec, keyed by field name; the module round-trips them untouched.
	Attributes map[string]json.RawMessage
}

GroupSpec holds the members and the enabled flag.

type Hierarchy

type Hierarchy interface {
	// ProjectTeam returns the team a live project is in; found is false for a missing project.
	ProjectTeam(ctx context.Context, projectID string) (teamID string, found bool, err error)
	// TeamExists reports whether the team is live.
	TeamExists(ctx context.Context, teamID string) (bool, error)
}

Hierarchy answers the two lookups a scope chain needs. A product with the hierarchy in memory implements it over that; StoreHierarchy reads through the stores.

func StoreHierarchy

func StoreHierarchy(s Stores) Hierarchy

StoreHierarchy reads the hierarchy through the stores, one Get per lookup. A disabled team or project counts as not live, and so does a project whose team is not, so a disabled tenancy row grants nothing below it.

type Identity

type Identity struct {
	Issuer  string
	Subject string
}

Identity is the stable identity an external identity provider asserts for a user.

func (Identity) Canonical

func (i Identity) Canonical() Identity

Canonical is i with its issuer in canonical form; two identities with the same canonical form are one identity.

func (Identity) IsZero

func (i Identity) IsZero() bool

IsZero reports whether the identity is unset, as for a local-only account.

type Kind

type Kind string

Kind names a row kind in a change notification.

const (
	KindUser           Kind = "user"
	KindGroup          Kind = "group"
	KindTeam           Kind = "team"
	KindProject        Kind = "project"
	KindServiceAccount Kind = "serviceaccount"
	KindRole           Kind = "role"
	KindRoleBinding    Kind = "rolebinding"
)

type ManagedError

type ManagedError struct {
	Kind   string
	Name   string
	Source string
}

ManagedError is ErrManaged for one row: its kind and name, and the source that manages it.

func (*ManagedError) Error

func (e *ManagedError) Error() string

func (*ManagedError) Is

func (e *ManagedError) Is(target error) bool

Is matches ErrManaged.

type Metadata

type Metadata struct {
	// ID is the immutable primary key; a create mints a UUIDv7 when it is empty.
	ID string
	// Name is a DNS-1123 label, unique per kind; a create derives it from DisplayName when it is empty.
	Name        string
	DisplayName string
	Description string
	// Owner is who created or manages the row. Projects, service accounts and role bindings derive it from their spec.
	Owner       authz.Owner
	Labels      map[string]string
	Annotations map[string]string
	// Dirty marks a row an operator edited after a loader wrote it, so the loader can leave it alone.
	Dirty bool
	// ResourceVersion changes on every write. An update carrying it applies only while the stored row still has it; empty updates unconditionally.
	ResourceVersion string
	// CreatedAt and UpdatedAt are set by the store.
	CreatedAt time.Time
	UpdatedAt time.Time
}

Metadata is the identity every row except a user carries.

func (Metadata) ExpectedVersion

func (m Metadata) ExpectedVersion() (v int64, ok bool, err error)

ExpectedVersion returns the version a conditional update must match; ok is false when ResourceVersion is empty. A value no stored row can carry is ErrStaleResourceVersion.

type Notifier

type Notifier interface {
	Notify(ctx context.Context, c Change)
}

Notifier hears every committed write, so a product can drop state derived from the row. It runs synchronously after the write and must not block.

type Op

type Op string

Op is what happened to the row.

const (
	OpUpsert Op = "upsert"
	OpDelete Op = "delete"
	// OpDisable is a user being disabled; re-enabling is an OpUpsert.
	OpDisable Op = "disable"
)

type Project

type Project struct {
	Meta Metadata
	Spec ProjectSpec
}

Project lives in one team and owns the product's rows that carry it as their owner. Its owner is always its team.

func (*Project) IsEnabled

func (p *Project) IsEnabled() bool

IsEnabled reports whether the project is enabled.

func (*Project) StampOwner

func (p *Project) StampOwner()

StampOwner sets the owner to the project's team, so it never drifts from TeamID.

type ProjectSpec

type ProjectSpec struct {
	TeamID string
	// Enabled nil means enabled.
	Enabled *bool
	// Attributes are product fields stored next to the spec, keyed by field name; the module round-trips them untouched.
	Attributes map[string]json.RawMessage
}

ProjectSpec holds the parent team and the enabled flag.

type ProvisionedGroup

type ProvisionedGroup struct {
	DisplayName string
	// ExternalID is the source's own id for the group; empty for none.
	ExternalID string
	// MemberIDs are user ids, each one of the source's accounts or already a member.
	MemberIDs []string
}

ProvisionedGroup is what a source may set on a group.

type ProvisionedUser

type ProvisionedUser struct {
	Username string
	Email    string
	// ExternalID is the source's own id for the account; empty for none.
	ExternalID string
}

ProvisionedUser is what a source may set on an account.

type Provisioner

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

Provisioner is the directory as one provisioning source, such as a SCIM client, sees it. It reads and writes only the users and groups stamped with its source, never sets roles, passwords or sign-in identities, and has no operation on roles, bindings, teams, projects or service accounts. Membership of its own groups skips the grant check: the source decides who is in the groups it manages, and the bindings an operator makes on those groups decide what membership grants.

func (*Provisioner) CreateGroup

func (p *Provisioner) CreateGroup(ctx context.Context, in ProvisionedGroup) (*Group, error)

CreateGroup adds a group the source manages. Its name derives from the display name and never changes after, and it is one no stored group holds and no binding names, so the new group inherits no grant an operator made for another.

func (*Provisioner) CreateUser

func (p *Provisioner) CreateUser(ctx context.Context, in ProvisionedUser, disabled bool) (*User, error)

CreateUser adds an account stamped with the source, disabled when disabled is set. It holds no roles, password or identity.

func (*Provisioner) DeleteGroup

func (p *Provisioner) DeleteGroup(ctx context.Context, id string) error

DeleteGroup deletes one of the source's groups.

func (*Provisioner) DeleteUser

func (p *Provisioner) DeleteUser(ctx context.Context, id string) error

DeleteUser deletes one of the source's accounts.

func (*Provisioner) DisableUser

func (p *Provisioner) DisableUser(ctx context.Context, id string) error

DisableUser disables one of the source's accounts, as Directory.DisableUser does: its sessions end and its tokens die.

func (*Provisioner) EnableUser

func (p *Provisioner) EnableUser(ctx context.Context, id string) error

EnableUser re-enables one of the source's accounts.

func (*Provisioner) Group

func (p *Provisioner) Group(ctx context.Context, id string) (*Group, error)

Group returns one of the source's groups; a missing or foreign one is ErrNotFound.

func (*Provisioner) Groups

func (p *Provisioner) Groups(ctx context.Context) ([]*Group, error)

Groups returns every group the source manages, ordered by name.

func (*Provisioner) Source

func (p *Provisioner) Source() string

Source is the source the provisioner writes as.

func (*Provisioner) UpdateGroup

func (p *Provisioner) UpdateGroup(ctx context.Context, id string, in ProvisionedGroup, ifVersion string) (*Group, error)

UpdateGroup replaces the display name, external id and members of one of the source's groups, with no grant check on the members. A non-empty ifVersion refuses the write with ErrStaleResourceVersion unless the stored group still has it; either way the write is conditional on the version read here.

func (*Provisioner) UpdateUser

func (p *Provisioner) UpdateUser(ctx context.Context, id string, in ProvisionedUser) (*User, error)

UpdateUser sets the fields a source owns on one of its accounts and writes nothing else, so roles, password, identities and the disabled flag stay as stored even when an operator changes them while the source's request runs.

func (*Provisioner) User

func (p *Provisioner) User(ctx context.Context, id string) (*User, error)

User returns one of the source's accounts; a missing or foreign one is ErrNotFound.

func (*Provisioner) Users

func (p *Provisioner) Users(ctx context.Context) ([]*User, error)

Users returns every account the source provisioned, oldest first.

type Revoker

type Revoker interface {
	DestroyUser(ctx context.Context, userID string) error
}

Revoker ends every session a user holds; *session.Manager satisfies it.

type Role

type Role struct {
	Meta Metadata
	Spec RoleSpec
}

Role is a named rule set. It carries no scope; the binding that names it supplies one.

func (*Role) IsEnabled

func (r *Role) IsEnabled() bool

IsEnabled reports whether the role is enabled.

func (*Role) RBAC

func (r *Role) RBAC() rbac.Role

RBAC is the role as the engine reads it.

type RoleBinding

type RoleBinding struct {
	Meta Metadata
	Spec RoleBindingSpec
}

RoleBinding grants a role to its subjects at one scope; it applies to every resource whose scope chain holds that scope. Its owner is always its scope.

func (*RoleBinding) IsEnabled

func (b *RoleBinding) IsEnabled() bool

IsEnabled reports whether the binding is enabled.

func (*RoleBinding) StampOwner

func (b *RoleBinding) StampOwner()

StampOwner sets the owner to the binding's scope, so it never drifts from it.

type RoleBindingSpec

type RoleBindingSpec struct {
	RoleID string
	// Scope kinds are opaque; Global is the global scope and carries no id, any other kind needs one.
	Scope    rbac.Scope
	Subjects []Subject
	// Enabled nil means enabled.
	Enabled *bool
	// Attributes are product fields stored next to the spec, keyed by field name; the module round-trips them untouched.
	Attributes map[string]json.RawMessage
}

RoleBindingSpec holds the role, the scope, the subjects and the enabled flag.

type RoleSpec

type RoleSpec struct {
	Rules []rbac.Rule
	// Enabled nil means enabled.
	Enabled *bool
	// Attributes are product fields stored next to the spec, keyed by field name; the module round-trips them untouched.
	Attributes map[string]json.RawMessage
}

RoleSpec holds the rules and the enabled flag.

type ScopeResolver

type ScopeResolver struct {
	Hierarchy Hierarchy
}

ScopeResolver is the default rbac.ScopeResolver: a resource's owner, then the owner's team when the owner is a project, then Global. A team or project resource is its own innermost scope, since its owner names the scope outside it. An owner of any other kind, or a project or team that is not live, collapses to Global, which leaves the resource to global bindings. A product with scopes of its own wraps it.

func (ScopeResolver) ChainFor

func (r ScopeResolver) ChainFor(ctx context.Context, res authz.Resource) ([]rbac.Scope, error)

ChainFor returns res's scopes, most specific first, ending in Global.

type ServiceAccount

type ServiceAccount struct {
	Meta Metadata
	Spec ServiceAccountSpec
}

ServiceAccount is a machine principal that lives in one project. Its owner is always its project.

func (*ServiceAccount) IsEnabled

func (s *ServiceAccount) IsEnabled() bool

IsEnabled reports whether the service account is enabled.

func (*ServiceAccount) StampOwner

func (s *ServiceAccount) StampOwner()

StampOwner sets the owner to the account's project, so it never drifts from ProjectID.

type ServiceAccountSpec

type ServiceAccountSpec struct {
	ProjectID string
	// Enabled nil means enabled.
	Enabled *bool
	// Attributes are product fields stored next to the spec, keyed by field name; the module round-trips them untouched.
	Attributes map[string]json.RawMessage
}

ServiceAccountSpec holds the parent project and the enabled flag.

type Store

type Store[T any] interface {
	Get(ctx context.Context, id string) (*T, error)
	// List returns every row ordered by name.
	List(ctx context.Context) ([]*T, error)
	Upsert(ctx context.Context, row *T) error
	Delete(ctx context.Context, id string) error
}

Store is the storage of one row kind. Get returns (nil, nil) when no row has the id. Upsert inserts or replaces by Meta.ID; with Meta.ResourceVersion set it replaces only while the stored row still carries that version and returns ErrStaleResourceVersion otherwise, and a duplicate name is ErrConflict. Delete of a missing id is not an error.

type Stores

type Stores struct {
	Users           UserStore
	Groups          Store[Group]
	Teams           Store[Team]
	Projects        Store[Project]
	ServiceAccounts Store[ServiceAccount]
	Roles           Store[Role]
	RoleBindings    Store[RoleBinding]
}

Stores is every store the directory reads and writes. A delete cascades in the store, in the delete's transaction: a team takes its projects, a team or project its service accounts and the bindings scoped to it, a role its bindings, and a user or service account leaves every group and binding it was in.

type Subject

type Subject struct {
	Kind SubjectKind
	ID   string
	Name string
}

Subject is one grantee. User and service-account subjects carry an id; a group subject carries a name, because a group asserted by an identity provider has no row to point at and unions with a stored group of the same name.

func (Subject) Key

func (s Subject) Key() string

Key renders the subject as "<kind>:<id or name>", the string a binding source indexes it under and a principal lists in its subjects.

type SubjectKind

type SubjectKind string

SubjectKind is what a binding subject names.

const (
	SubjectUser           SubjectKind = "user"
	SubjectGroup          SubjectKind = "group"
	SubjectServiceAccount SubjectKind = "serviceaccount"
)

type Team

type Team struct {
	Meta Metadata
	Spec TeamSpec
}

Team is the outer tenancy scope; it owns projects. Membership is a role binding at the team's scope, so there is one place that grants access.

func (*Team) IsEnabled

func (t *Team) IsEnabled() bool

IsEnabled reports whether the team is enabled.

type TeamSpec

type TeamSpec struct {
	// Enabled nil means enabled.
	Enabled *bool
	// Attributes are product fields stored next to the spec, keyed by field name; the module round-trips them untouched.
	Attributes map[string]json.RawMessage
}

TeamSpec holds the enabled flag.

type User

type User struct {
	// ID is the account's durable id; a create mints a UUIDv7 when it is empty.
	ID       string
	Username string
	Email    string
	// PasswordHash is a password hash, never a password; empty means no password login.
	PasswordHash string
	// Identity is the account's primary identity; zero only for an account with no identities. Writing a different one replaces the primary in Identities; writing a zero one removes it and makes the oldest remaining identity primary. Its issuer is kept as written, which a reader matching it exactly still finds.
	Identity Identity
	// Identities are every identity the account signs in with, oldest first, the primary among them, each in canonical form. The store fills them on read and an upsert leaves them alone apart from the primary; Directory.AddIdentity and RemoveIdentity change them.
	Identities []UserIdentity
	// External is the provisioning source that created the account and its id there. An update that leaves it zero keeps the stored one.
	External External
	// Roles are role names the account holds directly. Changing them goes through the grant check.
	Roles    []string
	Disabled bool
	// TokenVersion is the generation every token the user holds must carry. The store owns it: BumpTokenVersion advances it, and so does every write that changes the password, identities or disabled flag.
	TokenVersion int
	// ResourceVersion changes on every write to the account. An update carrying it applies only while the stored account still has it; empty updates unconditionally.
	ResourceVersion string
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

User is an account. It carries no metadata envelope: its fields are its columns.

func (*User) ExpectedVersion

func (u *User) ExpectedVersion() (v int64, ok bool, err error)

ExpectedVersion is Metadata.ExpectedVersion for an account.

func (*User) HasIdentity

func (u *User) HasIdentity(id Identity) bool

HasIdentity reports whether id, with or without trailing slashes on its issuer, is one of the account's identities.

func (*User) Status

func (u *User) Status() principal.Status

Status is the account state a principal for this user carries.

type UserIdentity

type UserIdentity struct {
	Identity
	// ExternalID is the provider's own id for the user behind this identity, such as an object id behind a pairwise subject; empty for none. It is unique per issuer.
	ExternalID string
	// CreatedAt is set by the store.
	CreatedAt time.Time
}

UserIdentity is one identity a user signs in with.

type UserStore

type UserStore interface {
	Get(ctx context.Context, id string) (*User, error)
	ByUsername(ctx context.Context, username string) (*User, error)
	// ByIdentity finds the account holding id among its identities, primary or not.
	ByIdentity(ctx context.Context, id Identity) (*User, error)
	// ByExternalID returns every account a provisioning source created with externalID as that source's id for it, oldest first; two sources may hold the same id.
	ByExternalID(ctx context.Context, externalID string) ([]*User, error)
	// List returns every account, oldest first.
	List(ctx context.Context) ([]*User, error)
	// Upsert inserts or replaces by ID; a new account starts at TokenVersion 1, and a replace advances it only when the password hash, primary identity or disabled flag changes. With ResourceVersion set it replaces only while the stored account still carries that version and returns ErrStaleResourceVersion otherwise. It writes Identity as the primary identity, replacing the stored primary when it differs, and ignores Identities; a zero Identity on an account that holds other identities makes the oldest of them primary, so such an account always has one.
	Upsert(ctx context.Context, u *User) error
	// UpsertRemovingIdentities is Upsert of an account with a zero Identity that also unlinks every identity it holds, all in one atomic write.
	UpsertRemovingIdentities(ctx context.Context, u *User) error
	// SetDisabled sets the disabled flag alone and, in the same write, advances TokenVersion. It reports false, writing nothing, when the account is missing or already in that state.
	SetDisabled(ctx context.Context, id string, disabled bool) (bool, error)
	// UpdateProvisioned sets the username, email and external id alone, on an account whose External.Source is source; any other account, or none, is ErrNotFound.
	UpdateProvisioned(ctx context.Context, source, id string, in ProvisionedUser) error
	Delete(ctx context.Context, id string) error
	// BumpTokenVersion invalidates every token the user holds.
	BumpTokenVersion(ctx context.Context, id string) error
	// AddIdentity links id to the user, or updates its external id when the user already holds it, and advances TokenVersion. The first identity of an account with no primary becomes its primary.
	AddIdentity(ctx context.Context, userID string, id UserIdentity) error
	// AddFirstIdentity links id as the primary of a user that holds no identity, checking, writing and advancing TokenVersion in one atomic step: a user that holds one, or an identity another user holds, is ErrConflict.
	AddFirstIdentity(ctx context.Context, userID string, id Identity) error
	// RemoveIdentity unlinks id from the user and advances TokenVersion; one the user does not hold is not an error. Removing the primary makes the oldest remaining identity primary.
	RemoveIdentity(ctx context.Context, userID string, id Identity) error
	// RemoveIdentities unlinks every identity of the user at once, the primary included, and advances TokenVersion.
	RemoveIdentities(ctx context.Context, userID string) error
}

UserStore is the storage of accounts. Lookups return (nil, nil) when no account matches; a duplicate username, email, identity or external id is ErrConflict, and a duplicate email is the ErrEmailTaken form of it. Identities are stored, compared and looked up in canonical form (Identity.Canonical); only the primary keeps its issuer as written. Every write that changes how the account signs in or whether it may (its password hash, identities or disabled flag) advances TokenVersion in that same write, so no token outlives the change even when a later step fails.

type Writer

type Writer struct {
	// Source is the provisioning source writing; it may write the rows it manages.
	Source string
	// Force writes over a row another source manages, as an operator overriding it does.
	Force bool
}

Writer is who a write comes from. A group with an external source is managed by it: only that source, or a forced write, changes or deletes it.

Directories

Path Synopsis
Package memstore is an in-memory directory.Stores.
Package memstore is an in-memory directory.Stores.
Package storetest is the behaviour every directory.Stores implementation must share: lookups, unique names, resource versions, references and delete cascades.
Package storetest is the behaviour every directory.Stores implementation must share: lookups, unique names, resource versions, references and delete cascades.

Jump to

Keyboard shortcuts

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