accesstest

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: 17 Imported by: 0

Documentation

Overview

Package accesstest gives other modules' tests the real access module over a store: the authenticator, the permission evaluator and the token service that a running server builds, bound through access.New as app binds them, so that a test authenticates and authorises without importing access internals.

Role

access module, test support: the real access module for other modules' tests, and the access module's supported entry point for them (decision 0044). Any module's test files may import it, as test support (dependency rule 1). It imports its own module root under rule 7's one named exception, which lets a module's test kit <m>/<m>test import its own root <m> and nothing wider. Tests that need access's answers without a store use the access/api/accessapitest fakes instead.

Inputs

  • A testing.TB, which New and Over fail when the module cannot be built, and which Middleware reports a failed authorisation to.
  • A Store, access.Store with the instance identity, holding the users, groups, permissions, settings, tokens and API restrictions that every answer reads: a fresh in-memory store from New, the access module's and the platform's in-memory stores over one unit of work, or the test's own through Over.
  • The options: WithNow, WithTokens, WithTokenVerifier and WithSettings.

Outputs

  • Kit.API: the module's accessapi.API, as app's module publishes it.
  • Kit.Authorize: a context carrying an authorised principal and its decider.
  • Kit.Decide: a decider for a subject that no request authenticated.
  • Kit.Middleware: a middleware that authorises each request's principal.
  • Kit.Verify: the stored record of a token the kit's token service issued.
  • HashPassword and ErrLoginSuspended: cheap password hashes for the users a test stores, and the suspended-login sentinel, which the kernel does not declare.
  • The access records a test stores (User, Group, Permission, Token, Project, Role and the rest), the store ports a fake wraps (UserStore, PermissionStore with PermissionQuery, TokenStore with TokenFilter, and APIRestriction) and the constants a test sets (UserDisabled, UserLocked and RoleCustomGlobal): aliases of access/core/model and access/core/port, which a test outside access may not import.

Invariants

  • The kit builds the module as app does: the authenticator over the store's users and settings, with its groups, its API restrictions and the token verifier, then access.New. Only the costs differ, so tests stay fast: passwords hash with 64 KiB and one pass, and signing keys have 1024 bits.
  • Authorize and Middleware store a principal and its decider together, with accessapi.WithCaller, never the principal alone, so a handler finds the decider the server's middleware would have stored (decision 0006, "Once per request").
  • Middleware reports a failed authorisation with tb.Errorf and answers 500. It never calls tb.Fatal, which must not run off the goroutine running the test, where handlers may run.
  • Every answer reads the store when it is asked for, so what a test stores after building the kit applies from its next call.

References

  • Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md, "Dependency rules" (rule 7's named exception) and "Names the migration introduces".
  • Decision 0005: docs/research/decisions/0005-authentication-and-tokens.md: the kit's tokens are the real service's, so tests never mint them by hand.
  • Decision 0006: docs/research/decisions/0006-authorization-native-permission-model.md, "Once per request": the kit evaluates through the Authorizer the server uses, so test outcomes match production.
  • Decision 0015: docs/research/decisions/0015-testing-and-acceptance.md: tests run against the real module over an in-memory or SQL store, not a fake.
  • Plan: docs/implementation/plan.md#p9d-modular-monolith-migration, "ACC tickets (access module)".
  • https://github.com/weaveplatform/artifactweave/issues/1007

Status

Implemented P9d. Over takes the access Store with the instance identity (https://github.com/weaveplatform/artifactweave/issues/1073), and New builds over the access module's and the platform's in-memory adapters (https://github.com/weaveplatform/artifactweave/issues/1098). The record and port aliases serve the tests that named access internals (https://github.com/weaveplatform/artifactweave/issues/1100).

Testing

A test outside access that needs an authenticator, a decider or tokens builds them with this kit (Over, Authorize, Middleware, Decide, API, Verify, HashPassword) rather than from access internals; TestUnitTestsAvoidAccessInternals (internal/layout) enforces it outside the composition root and the server suites.

The kit's own tests:

  • TestUnitAuthorizeAndDecideReadTheTestStore: a permission the test stores allows a read through Authorize and Decide, and without it the read is denied; Over keeps the test's store and settings, and Authorize keeps the binding's error text.
  • TestUnitAnonymousAccessOffGrantsNothing: with anonymous access off, the anonymous principal gets nothing.
  • TestUnitMiddleware: the principal and decider the middleware stores read back through the kernel, access/api and authn.DeciderFrom; a failed authorisation is reported on the test and answers 500.
  • TestUnitWithTokens: the instance identity is created when missing and kept when present, the signing key exists once the kit is built, an issued token verifies, and a store that cannot give the identity or the keys fails the test; without the option every token is refused.
  • TestUnitVerify: the record of an issued token, on the kit's clock, and a failed test on a kit without a token service.
  • TestUnitWithTokenVerifier: the verifier answers the authenticator, with or without the token service, and a transient user joins the store's auto-join groups.
  • TestUnitHashPassword: the cheap hash passes Basic, and the store's API restrictions apply.
  • TestUnitErrLoginSuspended: a suspended login matches ErrLoginSuspended until the kit's clock passes the suspension.

Index

Constants

View Source
const (
	UserDisabled     = model.UserDisabled
	UserLocked       = model.UserLocked
	RoleCustomGlobal = model.RoleCustomGlobal
)

The account statuses and the role type those tests set.

Variables

View Source
var ErrLoginSuspended = authn.ErrLoginSuspended

ErrLoginSuspended is the error, matched with errors.Is, that Basic answers for any password while failed logins have the user name suspended. It is the authenticator's own sentinel, the same value, re-exported because the kernel declares no such sentinel: a test outside access asserts it without importing access internals.

Functions

func HashPassword

func HashPassword(tb testing.TB, password string) []byte

HashPassword returns password hashed at the kit's cheap cost, for the PasswordHash of a user a test stores. A hash records its own cost, so any authenticator verifies it. HashPassword fails tb with Fatal if hashing fails.

Types

type APIRestriction

type APIRestriction = port.APIRestriction

APIRestriction is an administrator's temporary restriction of one user's API calls.

type AccessLockSettings

type AccessLockSettings = model.AccessLockSettings

AccessLockSettings are the user lock policy's fields beyond the lock limit and the password expiry.

type Environment

type Environment = model.Environment

Environment is a deployment stage that repositories are assigned to.

type Grants

type Grants = model.Grants

Grants map principal names to the actions they hold.

type Group

type Group = model.Group

Group is a set of users that permissions and roles name.

type Kit

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

Kit is the access module a running server would build, over one store: the real authenticator, permission evaluator and, with WithTokens, token service, bound through access.New as app binds them. Its methods may be called from any goroutine, except Verify on a kit without a token service, which fails the test.

func New

func New(tb testing.TB, opts ...Option) *Kit

New is Over with a fresh in-memory store, which the test reaches through Store: the access module's in-memory stores and the platform's, over one unit of work.

func Over

func Over(tb testing.TB, st Store, opts ...Option) *Kit

Over builds the access module over st, the test's own store, as app does: the authenticator over st's users and settings, with st's groups (which a transient token's user joins) and API restrictions and the token verifier, then access.New over st, the authenticator and the token service. Every answer reads st when it is asked for, so the users, groups, permissions, settings, tokens and restrictions a test stores apply from its next call. Without WithTokens or WithTokenVerifier every token is refused and API().Tokens is nil, as in most route tests. Over fails tb with Fatal when the module cannot be built, so it must be called from the goroutine running the test.

func (*Kit) API

func (k *Kit) API() accessapi.API

API returns the module's published surface, as API() of the module app builds: every access/api contract bound over the store, Tokens nil without WithTokens, and the settings WithSettings gave. A test that needs the principal or decider an evaluation returns, rather than a context, calls API().Authorizer itself.

func (*Kit) Authorize

func (k *Kit) Authorize(
	ctx context.Context,
	p kernel.Principal,
	anonymousEnabled bool,
) (context.Context, error)

Authorize evaluates p's permissions as the server's middleware does once it knows the caller (decision 0006), through API().Authorizer.Authorize, with the anonymous user's grants applying only while anonymousEnabled holds. It returns ctx carrying the principal that evaluation returned, with admin and groups as evaluated, and its decider, stored together with accessapi.WithCaller, so that kernel.FromContext, accessapi.DeciderFrom and authn.DeciderFrom read them as a handler behind the server would. On error it returns ctx unchanged and the binding's error, unwrapped, whose text starts "auth: permissions:" as the server's does.

func (*Kit) Decide

func (k *Kit) Decide(
	ctx context.Context,
	s accessapi.Subject,
	anonymousEnabled bool,
) (accessapi.Decider, error)

Decide evaluates s, a subject no request authenticated, through API().Authorizer.Decide, with the anonymous user's grants applying only while anonymousEnabled holds. Its error is the evaluator's, unwrapped.

func (*Kit) Middleware

func (k *Kit) Middleware(
	tb testing.TB,
	anonymousEnabled bool,
	principal func(*http.Request) kernel.Principal,
) func(http.Handler) http.Handler

Middleware returns a middleware that authorises principal(r) for every request with Authorize and serves the next handler with the authorised context, as the server's middleware does once it knows the caller. The test keeps its own mapping from a request to its principal, such as a header that names the user. When Authorize fails, the middleware reports the error with tb.Errorf and answers 500 without serving the next handler: it never calls tb.Fatal, because handlers may run off the goroutine running the test, where Fatal must not be called. It serves concurrent requests.

func (*Kit) Store

func (k *Kit) Store() Store

Store returns the store the kit was built over: New's fresh in-memory store, or the one the test passed to Over.

func (*Kit) Verify

func (k *Kit) Verify(ctx context.Context, raw string) (model.Token, error)

Verify resolves an access or reference token to its stored record through the kit's token service, so that a test checks what a consumer issued: its description, scope, lifetime, revocability, registry grants and parent. It is the service's own Verify, so it records the token's last use as a request presenting it would, and its errors are the service's, unwrapped: a token that does not verify matches authn.ErrInvalidToken. On a kit built without WithTokens there is no service to ask, and Verify fails the kit's test with Fatal, so it must then be called from the goroutine running that test.

type Option

type Option func(*options)

Option configures New and Over.

func WithNow

func WithNow(now func() time.Time) Option

WithNow makes now the clock of the authenticator and the token service, in place of time.Now, so that a test can move time past a token's expiry, a login suspension or an API restriction. access.New is given it too.

func WithSettings

func WithSettings(s accessapi.Settings) Option

WithSettings publishes s as API().Settings. Without it the settings are the zero value, which behaves as the defaults do.

func WithTokenVerifier

func WithTokenVerifier(v authn.TokenVerifier) Option

WithTokenVerifier makes the authenticator verify access and reference tokens with v, such as a stub that answers a fixed token record. Without WithTokens, API().Tokens stays nil; with it, v still answers the authenticator, and the token service issues tokens and serves Verify.

func WithTokens

func WithTokens() Option

WithTokens builds the real token service over the store, with 1024-bit signing keys, and binds it as API().Tokens and as the authenticator's token verifier. A store without an instance identity first gets a fixed test identity, from which the service derives its issuer; an identity the store holds is kept. The service creates the first signing key while the kit is built, so a test that counts signing keys sees it before its own steps.

type Permission

type Permission = model.Permission

Permission is a stored permission in every wire form's one shape.

type PermissionQuery

type PermissionQuery = port.PermissionQuery

PermissionQuery asks PermissionStore.Page for one page of permissions.

type PermissionStore

type PermissionStore = port.PermissionStore

PermissionStore stores permissions.

type Project

type Project = model.Project

Project groups repositories, members and roles under a key.

type Resource

type Resource = model.Resource

Resource is one section of a Permission.

type Role

type Role = model.Role

Role is a named set of actions over environments.

type RoleFlags

type RoleFlags = model.RoleFlags

RoleFlags are the platform role switches on a user or group.

type Store

type Store interface {
	access.Store
	// Instance holds the instance identity, which WithTokens stores when
	// there is none.
	Instance() instance.InstanceStore
}

Store is what the kit builds the access module over: the module's Store plus the instance identity its token service names as its issuer. The in-memory store New makes satisfies it, as does the composite store a test holds; every call joins the transaction ctx carries.

type Target

type Target = model.Target

Target scopes a Resource to paths in one repository or special target.

type Token

type Token = model.Token

Token is the stored record of an access token.

type TokenFilter

type TokenFilter = port.TokenFilter

TokenFilter narrows TokenStore's listings.

type TokenStore

type TokenStore = port.TokenStore

TokenStore stores token records.

type User

type User = model.User

User is a user account.

type UserLockPolicy

type UserLockPolicy = model.UserLockPolicy

UserLockPolicy locks an account after repeated failed logins.

type UserStore

type UserStore = port.UserStore

UserStore stores users.

Jump to

Keyboard shortcuts

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