port

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package port declares the access module's store ports: users, groups, permissions, tokens, keys, projects and API restrictions, the values their listings take and return, and Store, every store the module owns.

Role

access module, core layer, store ports. The module's adapters implement them: adapters/sql, which seals the secret columns, and adapters/inmem. The metadata store's SQL and in-memory stores delegate their user, group, permission, token, key, project and API restriction accessors to those adapters, so both satisfy Store. The ports take and return the module's core/model values, its api's key pairs, certificates and resource types, and kernel.Page.

Inputs

  • Users, groups and their memberships, permissions, token records, key pairs, certificates, trusted and signing keys, projects with their roles, environments, members and repository assignments, and API restrictions, to store; names, ids, digests and keys to look up.
  • An IdentityFilter, UserFilter or TokenFilter with a kernel.Page to narrow a listing.
  • The context of the caller's transaction, which every call joins.

Outputs

  • UserStore, GroupStore and PermissionStore; TokenStore with DigestKind and its Digest* constants; KeyStore; ProjectStore; and APIRestrictionStore.
  • IdentityFilter, IdentityResource, UserFilter, UserSummary, TokenFilter, and APIRestriction with Validate.
  • Store: tx.Runner, Users, Groups, Permissions, Tokens, Keys, Projects and APIRestrictions.

Invariants

  • Every store joins the caller's unit of work: a call made with a context inside Tx is part of that transaction, and is rolled back with it.
  • Errors are the kernel's sentinels, wrapped: kernel.ErrConflict for a name, id, digest or alias that exists, kernel.ErrNotFound for a missing record or a named group, member or project that does not exist, and kernel.ErrInvalid for an API restriction the stores cannot hold.
  • Secrets are given and returned in plain text, and sealed at rest (decision 0017): key pairs' private keys and passphrases, signing keys' private keys and passphrases, and a purposed token's secret. Other tokens are never stored, only their digests.
  • A user summary leaves out password hashes, credentials and memberships, so a listing cannot leak them.
  • API restriction changes append to an audit that outlives the user.

References

  • Decision 0005: docs/research/decisions/0005-authentication-and-tokens.md.
  • Decision 0006: docs/research/decisions/0006-authorization-native-permission-model.md (permissions mirrored by principal and by target).
  • Decision 0013: docs/research/decisions/0013-projects-and-environments.md.
  • Decision 0017: docs/research/decisions/0017-sealed-columns-and-master-key.md.
  • Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md ("Persistence" and "Names the migration introduces", which lists Store).
  • Target layout: docs/research/architecture-options/5-modular-monolith.md, lines 272 to 276 (the access module's core/port/store.go), lines 296 and 297 (its sql, inmem and storetest adapters), lines 577 and 578 (each module owns its store ports) and line 1055 (the metadata store split into each module's core/port/store.go).
  • Plan: docs/implementation/plan.md#p2-stores, task 1, #p4-identity-and-authorization and #p9d-modular-monolith-migration, epic STO (https://github.com/weaveplatform/artifactweave/issues/939).
  • https://github.com/weaveplatform/artifactweave/issues/1054

Status

Implemented P2: UserStore, GroupStore, PermissionStore, TokenStore, KeyStore and ProjectStore, with the metadata store's in-memory, SQLite and PostgreSQL stores (pull request 3). The identity listings and APIRestrictionStore came with retry safety and bounded API execution (pull request 905). Moved here in P9d, where Store is declared.

Testing

The package declares only ports, so it has no tests of its own. The module's contract (adapters/storetest), with its Users, UserLockout, Groups, Memberships, Permissions, IdentityPages, Tokens, Keypairs, Certificates, TrustedKeys, SigningKeys, Projects, Roles, Environments, ProjectMembers, Assignments, APIRestrictions and APIRestrictionConcurrentAudit subtests, runs the ports on the module's in-memory and SQL adapters and on the metadata store's in-memory, SQLite and PostgreSQL stores. Each factory returns a Store, so the tests compile only while every one of those stores satisfies it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIRestriction

type APIRestriction struct {
	User, Actor, Reason string
	Until, Changed      time.Time
	Sequence            int64
}

APIRestriction is an administrator's temporary restriction of one managed user's authenticated API calls. A zero Until clears it. Changed and Actor describe the administrative change, not a client's request parameters.

func (APIRestriction) Validate

func (r APIRestriction) Validate() error

Validate reports an error wrapping kernel.ErrInvalid unless r can be stored: User, Actor and Reason set, User and Actor at most 255 bytes and Reason at most 1024, Changed set, and a non-zero Until after Changed at the microsecond precision the stores keep. Both stores check it in Put before they write anything.

type APIRestrictionStore

type APIRestrictionStore interface {
	Get(ctx context.Context, user string) (APIRestriction, error)
	// Put replaces current state and appends an audit row in one transaction.
	// The user must exist. The returned Sequence is assigned by the store.
	Put(ctx context.Context, restriction APIRestriction) (APIRestriction, error)
	// History pages newest first by Sequence; an empty user includes all users.
	History(ctx context.Context, user string, page kernel.Page) ([]APIRestriction, string, error)
}

APIRestrictionStore keeps current restrictions and a durable, append-only audit of changes. Deleting a user removes its current state but preserves the audit; recreating the name does not inherit the deleted user's restriction.

type DigestKind

type DigestKind int

DigestKind selects which token digest ByDigest matches.

const (
	DigestAccess DigestKind = iota + 1
	DigestRefresh
	DigestReference
)

Token digests.

type GroupStore

type GroupStore interface {
	// Create stores g and its members; kernel.ErrConflict when the name exists,
	// kernel.ErrNotFound when a member does not.
	Create(ctx context.Context, g model.Group) error
	// Get returns the group with Members sorted.
	Get(ctx context.Context, name string) (model.Group, error)
	// Update replaces the group's fields and members.
	Update(ctx context.Context, g model.Group) error
	// Delete removes the group and its memberships.
	Delete(ctx context.Context, name string) error
	// List returns groups ordered by name.
	List(ctx context.Context, p kernel.Page) ([]model.Group, string, error)
	// ListNames filters and pages group names without loading member lists.
	ListNames(ctx context.Context, f IdentityFilter, p kernel.Page) ([]string, string, error)
	// AddMembers adds users to the group; adding a member twice is not an
	// error. kernel.ErrNotFound when the group or a user does not exist.
	AddMembers(ctx context.Context, group string, users ...string) error
	// RemoveMembers removes users from the group; removing a non-member is
	// not an error.
	RemoveMembers(ctx context.Context, group string, users ...string) error
	// AutoJoin returns the names of groups new users join, ordered.
	AutoJoin(ctx context.Context) ([]string, error)
}

GroupStore persists groups.

type IdentityFilter

type IdentityFilter struct {
	NameContains string
	Descending   bool
	Resource     *IdentityResource
}

IdentityFilter narrows a name-ordered identity listing before pagination. NameContains is a literal, Unicode-lowercased substring, not a SQL pattern. Resource selects exact permission targets with nonzero grants; it does not evaluate artifact include/exclude patterns or expand wildcard targets.

type IdentityResource

type IdentityResource struct {
	Type api.ResourceType
	Name string
}

IdentityResource selects a permission resource and its exact target name.

type KeyStore

type KeyStore interface {
	// CreateKeypair stores k; kernel.ErrConflict when the name exists.
	CreateKeypair(ctx context.Context, k api.Keypair) error
	// Keypair returns the key pair called name.
	Keypair(ctx context.Context, name string) (api.Keypair, error)
	// Keypairs returns every key pair ordered by name.
	Keypairs(ctx context.Context) ([]api.Keypair, error)
	// UpdateKeypair replaces a key pair.
	UpdateKeypair(ctx context.Context, k api.Keypair) error
	// DeleteKeypair removes a key pair. Refusing to remove one a repository
	// still uses (RepoStore.UsingKeypair) is the caller's decision.
	DeleteKeypair(ctx context.Context, name string) error

	// PutCertificate creates or replaces the certificate with c.Alias.
	PutCertificate(ctx context.Context, c api.Certificate) error
	// Certificate returns the certificate with alias.
	Certificate(ctx context.Context, alias string) (api.Certificate, error)
	// Certificates returns every certificate ordered by alias.
	Certificates(ctx context.Context) ([]api.Certificate, error)
	// DeleteCertificate removes a certificate.
	DeleteCertificate(ctx context.Context, alias string) error

	// CreateTrustedKey stores k; kernel.ErrConflict when the kid or alias
	// exists.
	CreateTrustedKey(ctx context.Context, k model.TrustedKey) error
	// TrustedKey returns the trusted key with kid.
	TrustedKey(ctx context.Context, kid string) (model.TrustedKey, error)
	// TrustedKeys returns every trusted key ordered by kid.
	TrustedKeys(ctx context.Context) ([]model.TrustedKey, error)
	// DeleteTrustedKey removes a trusted key.
	DeleteTrustedKey(ctx context.Context, kid string) error

	// PutSigningKey creates or replaces the signing key with k.Alias. A key
	// stored with IsDefault clears the flag on every other key.
	PutSigningKey(ctx context.Context, k model.SigningKey) error
	// SigningKey returns the signing key with alias.
	SigningKey(ctx context.Context, alias string) (model.SigningKey, error)
	// SigningKeys returns every signing key ordered by alias.
	SigningKeys(ctx context.Context) ([]model.SigningKey, error)
	// DefaultSigningKey returns the key marked IsDefault.
	DefaultSigningKey(ctx context.Context) (model.SigningKey, error)
	// DeleteSigningKey removes a signing key.
	DeleteSigningKey(ctx context.Context, alias string) error
}

KeyStore persists key material: repository key pairs, trusted CA certificates, trusted release-bundle keys and Distribution signing keys. Private keys and passphrases are sealed.

type PermissionQuery

type PermissionQuery struct {
	// After is the name the page starts after; "" starts at the first.
	After string
	// Limit is the page's size, at least 1.
	Limit int
	// Granting, when set, keeps only the permissions that grant some action
	// to one of Users or one of Groups, as ForPrincipal does for one user.
	Granting bool
	// Users and Groups are the principals Granting matches, by their
	// stored names: a user's folded name, a group's exact one.
	Users  []string
	Groups []string
}

PermissionQuery asks PermissionStore.Page for one page of permissions.

type PermissionStore

type PermissionStore interface {
	// Create stores p; kernel.ErrConflict when the name exists.
	Create(ctx context.Context, p model.Permission) error
	// Get returns the permission.
	Get(ctx context.Context, name string) (model.Permission, error)
	// Update replaces the permission.
	Update(ctx context.Context, p model.Permission) error
	// Delete removes the permission.
	Delete(ctx context.Context, name string) error
	// List returns permissions ordered by name.
	List(ctx context.Context, p kernel.Page) ([]model.Permission, string, error)
	// ForPrincipal returns the permissions that grant any action to user or
	// to any of groups, ordered by name.
	ForPrincipal(ctx context.Context, user string, groups []string) ([]model.Permission, error)
	// WithTarget returns the permissions naming target (a repository key, a
	// build repository, or an ANY target) in any resource, ordered by name.
	WithTarget(ctx context.Context, target string) ([]model.Permission, error)
	// Page returns, ordered by name, up to q.Limit permissions named after
	// q.After, and whether more follow: the store reads one past the page.
	// Unlike List it neither encodes its position nor caps Limit, because
	// Access v2's cursor is a bare permission name and its limit reaches
	// 99,999 (getpermissions).
	Page(ctx context.Context, q PermissionQuery) ([]model.Permission, bool, error)
}

PermissionStore persists permissions in the Access v2 shape (decision 0006). Grants and targets are mirrored into their own tables so the authorizer looks permissions up by principal and by target.

type ProjectStore

type ProjectStore interface {
	// Create stores p; kernel.ErrConflict when the key exists.
	Create(ctx context.Context, p model.Project) error
	// Get returns the project.
	Get(ctx context.Context, key string) (model.Project, error)
	// Update replaces the project.
	Update(ctx context.Context, p model.Project) error
	// Delete removes the project with its roles, environments, members,
	// the assignments of repositories it owns and its shares of others.
	Delete(ctx context.Context, key string) error
	// List returns every project ordered by key.
	List(ctx context.Context) ([]model.Project, error)

	// PutRole creates or replaces the role (r.ProjectKey, r.Name).
	PutRole(ctx context.Context, r model.Role) error
	// Role returns one role.
	Role(ctx context.Context, projectKey, name string) (model.Role, error)
	// Roles returns a project's roles, or the global ones for "", by name.
	Roles(ctx context.Context, projectKey string) ([]model.Role, error)
	// DeleteRole removes a role.
	DeleteRole(ctx context.Context, projectKey, name string) error

	// CreateEnvironment stores e. Environment names are unique across the
	// instance, global and project alike, so kernel.ErrConflict when the name
	// is taken anywhere.
	CreateEnvironment(ctx context.Context, e model.Environment) error
	// Environments returns a project's environments, or the global ones for
	// "", by name.
	Environments(ctx context.Context, projectKey string) ([]model.Environment, error)
	// RenameEnvironment renames an environment and every reference to it in
	// roles and repository assignments; kernel.ErrConflict when to is taken.
	RenameEnvironment(ctx context.Context, projectKey, from, to string) error
	// DeleteEnvironment removes an environment.
	DeleteEnvironment(ctx context.Context, projectKey, name string) error

	// PutMember creates or replaces a membership.
	PutMember(ctx context.Context, m model.ProjectMember) error
	// Member returns one membership.
	Member(
		ctx context.Context, projectKey string, typ model.PrincipalType, name string,
	) (model.ProjectMember, error)
	// Members returns a project's members of one principal type by name.
	Members(
		ctx context.Context, projectKey string, typ model.PrincipalType,
	) ([]model.ProjectMember, error)
	// DeleteMember removes a membership.
	DeleteMember(ctx context.Context, projectKey string, typ model.PrincipalType, name string) error

	// PutAssignment creates or replaces a repository's assignment and
	// shares. SharedWith comes back sorted and without duplicates.
	PutAssignment(ctx context.Context, a model.RepositoryAssignment) error
	// Assignment returns a repository's assignment.
	Assignment(ctx context.Context, repoKey string) (model.RepositoryAssignment, error)
	// Assignments returns the assignments of repositories assigned to or
	// shared with projectKey (including shared with all), by repository
	// key.
	Assignments(ctx context.Context, projectKey string) ([]model.RepositoryAssignment, error)
	// DeleteAssignment removes a repository's assignment and shares.
	DeleteAssignment(ctx context.Context, repoKey string) error
}

ProjectStore persists projects with their roles, environments, members and repository assignments. Global roles and environments are those with an empty ProjectKey. Writes that name a project (a project role or environment, a membership, an assignment's owner) return kernel.ErrNotFound when that project does not exist.

type Store

type Store interface {
	tx.Runner
	Users() UserStore
	Groups() GroupStore
	Permissions() PermissionStore
	Tokens() TokenStore
	Keys() KeyStore
	Projects() ProjectStore
	APIRestrictions() APIRestrictionStore
}

Store is every store the access module owns. All of them take part in the caller's unit of work (tx.Runner).

type TokenFilter

type TokenFilter struct {
	Subject string
	// Purpose, when set, lists only tokens of that purpose.
	Purpose string
}

TokenFilter narrows token listings.

type TokenStore

type TokenStore interface {
	// Create stores t; kernel.ErrConflict when the ID or a digest exists, or
	// when the subject already has a token of t's purpose.
	Create(ctx context.Context, t model.Token) error
	// Get returns the token with id.
	Get(ctx context.Context, id string) (model.Token, error)
	// ByDigest returns the token whose digest of the given kind is digest,
	// which is how revocation by value and refresh find the record.
	ByDigest(ctx context.Context, kind DigestKind, digest []byte) (model.Token, error)
	// List returns tokens ordered by (IssuedAt, ID).
	List(ctx context.Context, f TokenFilter, p kernel.Page) ([]model.Token, string, error)
	// Delete removes the token, revoking it.
	Delete(ctx context.Context, id string) error
	// Touch sets LastUsed.
	Touch(ctx context.Context, id string, at time.Time) error
	// DeleteExpired removes tokens that expired before t and returns how
	// many; tokens that never expire are kept.
	DeleteExpired(ctx context.Context, before time.Time) (int64, error)
}

TokenStore persists access token records. The tokens themselves are never stored, except a purposed token's Secret, which stores seal.

type UserFilter

type UserFilter struct {
	IdentityFilter
	Status     model.UserStatus
	OnlyAdmins bool
}

UserFilter adds account status and effective administrator selection.

type UserStore

type UserStore interface {
	// Create stores u and its memberships; kernel.ErrConflict when the name
	// exists, kernel.ErrNotFound when a named group does not.
	Create(ctx context.Context, u model.User) error
	// Get returns the user with Groups sorted.
	Get(ctx context.Context, name string) (model.User, error)
	// Update replaces the user's fields and memberships.
	Update(ctx context.Context, u model.User) error
	// Delete removes the user and its memberships.
	Delete(ctx context.Context, name string) error
	// List returns users ordered by name.
	List(ctx context.Context, p kernel.Page) ([]model.User, string, error)
	// ListSummaries filters and pages public fields without hydrating secrets
	// or memberships. The cursor is the last name, in the requested order.
	ListSummaries(ctx context.Context, f UserFilter, p kernel.Page) ([]UserSummary, string, error)
	// RecordLogin sets LastLoggedIn and resets FailedLogins.
	RecordLogin(ctx context.Context, name string, at time.Time) error
	// RecordFailedLogin adds one to FailedLogins in one atomic step and,
	// when lockAt is positive and the count reaches it, sets an enabled
	// user's Status to locked. It reports whether the user is locked
	// afterwards. kernel.ErrNotFound when the user does not exist.
	RecordFailedLogin(ctx context.Context, name string, lockAt int) (bool, error)
	// Unlock sets locked users among names back to enabled and resets
	// their FailedLogins; with no names it unlocks every locked user.
	// Unknown names are ignored.
	Unlock(ctx context.Context, names ...string) error
	// Locked returns the names of locked users, ordered.
	Locked(ctx context.Context) ([]string, error)
	// LockedPage pages the names of locked users in Locked's order, so a
	// caller can write the list as it reads it. The cursor is the last name.
	LockedPage(ctx context.Context, p kernel.Page) ([]string, string, error)
}

UserStore persists users. A user's Groups are its memberships, kept in the group_members table shared with GroupStore.

type UserSummary

type UserSummary struct {
	Name   string
	Realm  string
	Status model.UserStatus
}

UserSummary is the public listing projection. It deliberately excludes password hashes, credentials and membership lists.

Jump to

Keyboard shortcuts

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