iam

package
v0.0.0-...-2d53558 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 8 Imported by: 3 modules, 2 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 iam - identity and access management interfaces for users, sessions, roles, grants, and tenants.

Index

Constants

View Source
const TenantNameMaxLen = 100

Variables

View Source
var (
	CapGrantsAdd    = NewCap("Grants_Add")
	CapGrantsRemove = NewCap("Grants_Remove")
	CapGrantsList   = NewCap("Grants_List")
)

Managing grants of any principal type is a single capability.

View Source
var (
	CapGroupsWrite            = NewCap("Groups_Write")
	CapGroupsGet              = NewCap("Groups_Get")
	CapGroupsDelete           = NewCap("Groups_Delete")
	CapGroupsList             = NewCap("Groups_List")
	CapGroupsListByTenant     = NewCap("Groups_ListByTenant")
	CapGroupsAddMember        = NewCap("Groups_AddMember")
	CapGroupsRemoveMember     = NewCap("Groups_RemoveMember")
	CapGroupsListMembers      = NewCap("Groups_ListMembers")
	CapGroupsListMemberGroups = NewCap("Groups_ListMemberGroups")
)
View Source
var (
	CapPasswordsSet = NewCap("Passwords_Set")
	CapPasswordsGet = NewCap("Passwords_Get")
)
View Source
var (
	CapRolesWrite        = NewCap("Roles_Write")
	CapRolesGet          = NewCap("Roles_Get")
	CapRolesDelete       = NewCap("Roles_Delete")
	CapRolesList         = NewCap("Roles_List")
	CapRolesListByTenant = NewCap("Roles_ListByTenant")
)
View Source
var (
	CapSystemGrantsAdd    = NewCap("SystemGrants_Add")
	CapSystemGrantsRemove = NewCap("SystemGrants_Remove")
	CapSystemGrantsList   = NewCap("SystemGrants_List")
)
View Source
var (
	CapTenantInvitationsCreate = NewCap("TenantInvitations_Create")
	CapTenantInvitationsRead   = NewCap("TenantInvitations_Read")
	CapTenantInvitationsDelete = NewCap("TenantInvitations_Delete")
)
View Source
var (
	CapTenantMembersAdd    = NewCap("TenantMembers_Add")
	CapTenantMembersRemove = NewCap("TenantMembers_Remove")
	CapTenantMembersRead   = NewCap("TenantMembers_Read")
)
View Source
var (
	ErrTenantIDEmpty     = errors.New("tenant id is empty")
	ErrTenantRootEmpty   = errors.New("tenant root is empty")
	ErrNotRootTenant     = errors.New("tenant is not a root")
	ErrRootInUse         = errors.New("tenant is the root of other tenants")
	ErrTenantNameEmpty   = errors.New("tenant name is empty")
	ErrTenantNameTooLong = errors.New("tenant name exceeds max length")
)
View Source
var (
	CapTenantsCreate = NewCap("Tenants_Create")
	// CapTenantsCreateRoot is the right to make a tenant its own root, with a
	// cap of its own. It is platform-only: it is held by provisioning and never
	// by a role, since each root brings a fresh allowance.
	CapTenantsCreateRoot = NewPlatformCap("Tenants_CreateRoot")
	CapTenantsRead       = NewCap("Tenants_Read")
	CapTenantsUpdate     = NewCap("Tenants_Update")
	CapTenantsDelete     = NewCap("Tenants_Delete")
)
View Source
var (
	ErrUserIDEmpty    = errors.New("user id is empty")
	ErrUserEmailEmpty = errors.New("user email is empty")
)
View Source
var (
	CapUsersSave       = NewCap("Users_Save")
	CapUsersGetByEmail = NewCap("Users_GetByEmail")
	CapUsersGet        = NewCap("Users_Get")
	CapUsersVerify     = NewCap("Users_Verify")
	CapUsersList       = NewCap("Users_List")
	CapUsersPrune      = NewCap("Users_Prune")
)
View Source
var CapAuditRead = NewCap("Audit_Read")
View Source
var CapSystemConsole = NewCap("SystemConsole")

CapSystemConsole shows the system section of the dashboard (cross-tenant views for staff). It must be held as a system grant; tenant-scoped grants are not sufficient. It only reveals the UI: every system page's data is still guarded by its own cap.

View Source
var ErrAlreadyExists = errors.New("already exists")
View Source
var ErrForbidden = errors.New("forbidden")
View Source
var ErrLastOwner = errors.New("cannot remove or demote the last owner of a tenant")
View Source
var ErrTenantNotFound = errors.New("tenant not found")
View Source
var ErrUnauthorized = errors.New("unauthorized")
View Source
var ErrUserNotFound = errors.New("user not found")

Functions

func CompareHash

func CompareHash(hash PasswordHash, password string) error

CompareHash checks a password against a stored hash. It doesn't touch a store, so callers can run the slow comparison outside a transaction.

func GetSessionKey

func GetSessionKey(ctx context.Context) string

func PutPrincipal

func PutPrincipal(ctx context.Context, p Principal) context.Context

func PutSessionKey

func PutSessionKey(ctx context.Context, key string) context.Context

PutSessionKey stores the session lookup key in the context for log correlation. The key identifies a session in logs without exposing the session secret.

func SetPassword

func SetPassword(ctx context.Context, store PasswordStore, userID core.ID, password string) error

Types

type AuditEntry

type AuditEntry struct {
	ID     core.ID
	Tenant core.ID
	// Subject is the user this entry concerns. Distinct from Actor: on a
	// password reset performed via emailed token, Subject is the account
	// owner while Actor is empty (anonymous).
	Subject core.ID
	Time    time.Time
	// Actor is the principal subject that performed the action.
	// Empty for anonymous actions (e.g. an invitee declining by token
	// before registering).
	Actor string
	// Action is the API operation name, e.g. "Tenants_Update".
	Action string
	// Resource identifies the affected resource: an ID, slug, or email,
	// depending on what the action operates on.
	Resource string
	// Detail is short human-readable context, e.g. the new name on a rename.
	Detail string
	// Request is the HTTP request ID, for correlation with request logs.
	Request string
}

AuditEntry is one record in the audit log: who did what to which resource, when. Entries are written in the same transaction as the mutation they describe, so the log never disagrees with the data.

Entries are scoped by Tenant, by Subject, or both. Tenant-scoped entries record administrative actions within a tenant. Subject-scoped entries record identity and account events concerning a user (login, registration, password reset) that have no tenant.

type AuditStore

type AuditStore interface {
	// Append writes an entry. ID and Time are filled if empty. Append has
	// no capability check: an entry is a side effect of an operation that
	// already passed its own check, and appending is never caller-chosen.
	Append(ctx context.Context, e *AuditEntry) error
	List(ctx context.Context, tenant core.ID, page core.PageReq, out *core.Page[AuditEntry]) error
	// ListByUser returns entries whose Subject is the given user. Allowed
	// for the user themselves, or with system-scoped Audit.Read.
	ListByUser(ctx context.Context, userID core.ID, page core.PageReq, out *core.Page[AuditEntry]) error
}

type BotGrant

type BotGrant struct {
	Tenant core.ID
	Bot    core.ID
	Role   string
	Path   core.Path
}

BotGrant grants a role to a bot, scoped to a tenant and path. Bots are not tenant members, so no membership is required.

type BotGrantStore

type BotGrantStore interface {
	Add(ctx context.Context, g BotGrant) error

	Remove(ctx context.Context, g BotGrant) error

	ListByTenant(ctx context.Context, tenant core.ID, page core.PageReq) (core.Page[BotGrant], error)
}

type Cap

type Cap string

Cap is an access capability.

func NewCap

func NewCap(s string) Cap

NewCap creates a Cap value.

func NewPlatformCap

func NewPlatformCap(s string) Cap

NewPlatformCap creates a Cap that tenant roles can never carry. Use it for caps that would let a tenant escalate (raising its own limits, minting roots): they are held only by provisioning and system contexts. Role stores reject them and access loading drops them, so a role definition can't smuggle one in.

func (Cap) IsPlatform

func (c Cap) IsPlatform() bool

IsPlatform reports whether the cap was created with NewPlatformCap.

type Group

type Group struct {
	Tenant core.ID
	Path   core.Path
	Name   string
}

type GroupGrant

type GroupGrant struct {
	Tenant core.ID
	Group  core.Path
	Role   string
	Path   core.Path
}

GroupGrant grants a role to a group (whose user members inherit it), scoped to a tenant and path.

type GroupGrantStore

type GroupGrantStore interface {
	Add(ctx context.Context, g GroupGrant) error

	Remove(ctx context.Context, g GroupGrant) error

	ListByTenant(ctx context.Context, tenant core.ID, page core.PageReq) (core.Page[GroupGrant], error)
}

type GroupStore

type GroupStore interface {
	Create(ctx context.Context, g *Group) error
	Update(ctx context.Context, g *Group) error

	Get(ctx context.Context, tenant core.ID, path core.Path, out *Group) error

	Delete(ctx context.Context, tenant core.ID, path core.Path) error

	List(ctx context.Context, tenant core.ID, page core.PageReq, out *core.Page[Group]) error

	AddMember(ctx context.Context, tenant core.ID, group core.Path, userID core.ID) error

	RemoveMember(ctx context.Context, tenant core.ID, group core.Path, userID core.ID) error

	ListMembers(ctx context.Context, tenant core.ID, group core.Path, page core.PageReq, out *core.Page[core.ID]) error

	ListMemberGroups(ctx context.Context, userID core.ID, page core.PageReq, out *core.Page[Group]) error
}

type OAuthStore

type OAuthStore interface {
	// AddProvider adds an OAuth provider to a user
	AddProvider(ctx context.Context, userID core.ID, provider, providerID string) error
	GetUserByProvider(ctx context.Context, provider, providerID string, out *User) error
}

type PasswordHash

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

PasswordHash is an opaque type representing a hashed password. It implements driver.Valuer and sql.Scanner for database storage.

func NewPasswordHash

func NewPasswordHash(hash string) PasswordHash

func (PasswordHash) MarshalJSON

func (p PasswordHash) MarshalJSON() ([]byte, error)

func (PasswordHash) MarshalText

func (p PasswordHash) MarshalText() ([]byte, error)

func (*PasswordHash) Scan

func (p *PasswordHash) Scan(src any) error

func (PasswordHash) String

func (p PasswordHash) String() string

func (*PasswordHash) UnmarshalJSON

func (p *PasswordHash) UnmarshalJSON([]byte) error

func (*PasswordHash) UnmarshalText

func (p *PasswordHash) UnmarshalText([]byte) error

func (PasswordHash) Value

func (p PasswordHash) Value() (driver.Value, error)

type PasswordStore

type PasswordStore interface {
	SetHash(ctx context.Context, userID core.ID, hash PasswordHash) error
	GetHash(ctx context.Context, userID core.ID) (PasswordHash, error)
}

PasswordStore is implemented by the app to persist password hashes.

type Principal

type Principal struct {
	Subject string
}

func GetPrincipal

func GetPrincipal(ctx context.Context) Principal

type Role

type Role struct {
	Tenant core.ID
	Slug   string
	Name   string
	Caps   []Cap
}

type RoleStore

type RoleStore interface {
	Create(ctx context.Context, role *Role) error
	Update(ctx context.Context, role *Role) error
	Delete(ctx context.Context, tenant core.ID, slug string) error

	Get(ctx context.Context, tenant core.ID, slug string, out *Role) error
	List(ctx context.Context, tenant core.ID, page core.PageReq, out *core.Page[Role]) error
}

type SystemGrant

type SystemGrant struct {
	Principal core.ID
	Role      string
}

SystemGrant grants a platform-operator role to a principal across the whole system — the "platform plane", distinct from tenant-scoped grants. It has no tenant or path: system access is global by nature. Managed out-of-band / gated, not through the tenant grant API.

type SystemGrantStore

type SystemGrantStore interface {
	Add(ctx context.Context, g SystemGrant) error

	Remove(ctx context.Context, g SystemGrant) error

	List(ctx context.Context, page core.PageReq) (core.Page[SystemGrant], error)
}

type Tenant

type Tenant struct {
	ID   core.ID
	Name string

	// Root is the tenant whose Tenants cap this tenant counts against. A root
	// tenant is its own Root. A tenant may only name a root, never another
	// non-root tenant, so there is at most one hop.
	Root core.ID
}

func (Tenant) Validate

func (t Tenant) Validate() error

type TenantInvitation

type TenantInvitation struct {
	Tenant    core.ID
	Email     string
	ExpiresAt time.Time
}

type TenantInvitationStore

type TenantInvitationStore interface {
	// Create inserts a new invitation and returns the combined "key.code" token
	// to embed in the email. Returns ErrAlreadyExists on (tenant, email) conflict.
	Create(ctx context.Context, tenantID core.ID, email string) (token string, err error)

	// GetByToken validates the token (timing-safe code compare + not expired)
	// and returns the invitation. Returns core.ErrNotFound on any failure mode
	// (missing, expired, wrong code) — the undifferentiated error is deliberate
	// and must not be split apart.
	GetByToken(ctx context.Context, token string, out *TenantInvitation) error

	// DeleteByToken removes the invitation whose token matches. Authorized by
	// valid token possession alone (no cap check). Used by self-service Accept
	// and Decline flows.
	DeleteByToken(ctx context.Context, token string) error

	// List returns pending invitations for a tenant. Owner-facing.
	List(ctx context.Context, tenantID core.ID, page core.PageReq, out *core.Page[TenantInvitation]) error

	// ListByEmail returns pending invitations addressed to an email. Allowed
	// when the principal's email matches the argument, or when the caller has
	// system access to CapTenantInvitationsRead.
	ListByEmail(ctx context.Context, email string, page core.PageReq, out *core.Page[TenantInvitation]) error

	// Delete rescinds an invitation by (tenant, email). Owner-facing.
	Delete(ctx context.Context, tenantID core.ID, email string) error
}

type TenantMember

type TenantMember struct {
	Tenant core.ID
	User   core.ID
	Owner  bool
}

TenantMember records that a user belongs to a tenant. Owner marks the one control tier that carries membership invariants (last-owner protection, tenant bootstrap); every other capability tier is a grant, not a member row.

type TenantMemberStore

type TenantMemberStore interface {
	Add(ctx context.Context, m TenantMember) error

	Remove(ctx context.Context, tenantID core.ID, userID core.ID) error

	Get(ctx context.Context, tenantID core.ID, userID core.ID) (TenantMember, error)

	ListByTenant(ctx context.Context, tenantID core.ID, page core.PageReq) (core.Page[TenantMember], error)

	ListByUser(ctx context.Context, userID core.ID, page core.PageReq) (core.Page[TenantMember], error)
}

type TenantStore

type TenantStore interface {
	Create(ctx context.Context, t *Tenant) error
	Update(ctx context.Context, t *Tenant) error
	Delete(ctx context.Context, id core.ID) error

	Get(ctx context.Context, id core.ID, out *Tenant) error
	// List returns the tenants the caller belongs to.
	List(ctx context.Context, page core.PageReq, out *core.Page[Tenant]) error
	// ListAll returns every tenant. It requires the system CapTenantsRead.
	ListAll(ctx context.Context, page core.PageReq, out *core.Page[Tenant]) error
}

type User

type User struct {
	ID    core.ID
	Email string
	// Name is the user's display name. Optional; typically supplied by an
	// identity provider at login or edited by the user.
	Name     string
	Verified bool
}

func NewUser

func NewUser(email string) User

func (*User) Valid

func (u *User) Valid() error

type UserGrant

type UserGrant struct {
	Tenant core.ID
	User   core.ID
	Role   string
	Path   core.Path
}

UserGrant grants a role to a user, scoped to a tenant and path. A user must be a member of the tenant (enforced by the FK to tenant_members); revoking membership cascades these away.

type UserGrantStore

type UserGrantStore interface {
	Add(ctx context.Context, g UserGrant) error

	Remove(ctx context.Context, g UserGrant) error

	ListByTenant(ctx context.Context, tenant core.ID, page core.PageReq) (core.Page[UserGrant], error)

	ListByUser(ctx context.Context, userID core.ID, page core.PageReq) (core.Page[UserGrant], error)
}

type UserStore

type UserStore interface {
	Save(ctx context.Context, user *User) error

	// GetUserByEmail gets a user by email.
	// Returns core.ErrNotFound if user doesn't exist
	GetByEmail(ctx context.Context, email string, out *User) error

	// Get gets a user by ID.
	// Returns core.ErrNotFound if user doesn't exist
	Get(ctx context.Context, id core.ID, out *User) error

	// Verify marks a user's email as verified.
	Verify(ctx context.Context, id core.ID) error

	List(ctx context.Context, page core.PageReq, out *core.Page[User]) error

	// DeleteUnverified deletes users who are still unverified and were created
	// before the cutoff, along with their dependent rows. It returns the number
	// of users deleted.
	// Access: CapUsersPrune.
	DeleteUnverified(ctx context.Context, createdBefore time.Time) (int64, error)

	// ListByTenant lists the users who are members of a tenant.
	// Access: CapTenantMembersRead — reading a tenant's membership includes
	// reading its members' user records.
	ListByTenant(ctx context.Context, tenant core.ID, page core.PageReq, out *core.Page[User]) error
}

UserStore provides access to user data

Source Files

  • audit.go
  • errors.go
  • grants.go
  • groups.go
  • guard.go
  • iam.go
  • oauth.go
  • passwords.go
  • principal.go
  • roles.go
  • system_grants.go
  • tenant_invitations.go
  • tenant_members.go
  • tenants.go
  • users.go

Jump to

Keyboard shortcuts

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