Documentation
¶
Overview ¶
Package modeltest runs authorization-model tests declared by an ofga workspace (an ofga.yaml manifest and its *.test.yaml files).
Tests run against a pluggable Engine: by default an in-process, embedded OpenFGA server (hermetic — no external dependency, real store, or profile), or a specific OpenFGA version in a Docker container, or an already-running server over gRPC. Each test gets its own fresh store. The package also computes grant-based branch coverage against the model and can render human/JUnit/JSON/GitHub reports.
Index ¶
- Constants
- Variables
- func FileStem(path string) string
- func FindWorkspaceRoot(path string) (string, error)
- func FormatPercent(p float64) string
- func NewCountingEmbeddedEngine(serverOpts map[string]any) (Engine, *Counters, error)
- func Percent(covered, total int) float64
- func RenderExplain(w io.Writer, ar AssertionResult)
- func RepoPath(path string) string
- func Seed(ctx context.Context, ws *Workspace, sel string, opts Options) (endpoint, storeID, modelID string, stop func(), err error)
- func ToProtoTuples(tuples []TupleKey) ([]*openfgav1.TupleKey, error)
- func ValidateTestFile(data []byte) error
- func WithDispatchTags(ctx context.Context) (context.Context, func() float64)
- func WithReadCount(ctx context.Context) (context.Context, func() int64)
- func WorkspaceSchema() []byte
- func WriteReport(format string, w io.Writer, res *Results) error
- type AssertionResult
- type BranchCov
- type CheckCase
- type CheckReq
- type Counters
- type Coverage
- type CoverageDiff
- type DiffBranch
- type Engine
- type Explain
- type ExplainNode
- type ListObjectsCase
- type ListObjectsReq
- type ListUsersCase
- type ListUsersExpectation
- type ListUsersFilter
- type ListUsersReq
- type LoadedModel
- type Manifest
- type Options
- type RelCov
- type Resolver
- type Results
- type Scope
- type SetDiff
- type Summary
- type Test
- type TestFile
- type TestResult
- type TupleCond
- type TupleItem
- type TupleKey
- type TypeCov
- type Workspace
- type WorkspaceOptions
Constants ¶
const WorkspaceSchemaURL = "https://raw.githubusercontent.com/sergiught/openfga-cli/main/internal/modeltest/schema/workspace.v1.json"
WorkspaceSchemaURL is the canonical web URL editors can use for completion and validation without generating a local copy.
Variables ¶
var ErrWorkspaceNotFound = errors.New("model-test workspace not found")
ErrWorkspaceNotFound identifies manifest discovery failure without relying on error-message text. Callers can offer scaffold guidance only for this case.
Functions ¶
func FindWorkspaceRoot ¶
FindWorkspaceRoot discovers the nearest manifest directory without parsing the manifest. Watch mode uses it so a temporarily malformed ofga.yaml still watches the correct directory and recovers on the next save.
func FormatPercent ¶
FormatPercent renders a percentage without a trailing ".0" for whole numbers (e.g. "80%") while keeping one decimal place otherwise (e.g. "77.3%"). A value strictly below 100 that would round up to "100.0%" (e.g. 99.96) is floored to "99.9%" instead, so only genuine full coverage ever reads as 100.
func NewCountingEmbeddedEngine ¶ added in v0.269.0
NewCountingEmbeddedEngine is NewEmbeddedEngine with a datastore wrapper that counts tuple reads into the returned Counters.
func RenderExplain ¶
func RenderExplain(w io.Writer, ar AssertionResult)
RenderExplain writes a narrative of why a check / list_objects / list_users assertion failed to w, styled via internal/style (which downsamples to plain text under NO_COLOR/non-TTY at the writer layer). It only reads ar and never calls the engine.
It always starts with the expected-vs-got line. For a check assertion it then renders ar.Explain.Tree: the full dead-ended resolution tree (plus any nearest-miss suggestion) when the check unexpectedly came back false, or just the granting path when it unexpectedly came back true. For list_objects/list_users it renders ar.Explain.SetDiff.
func RepoPath ¶ added in v0.268.0
RepoPath is path relative to the repository root ($GITHUB_WORKSPACE, else the working directory) in slash form: how model test names files in GitHub annotations, so CI can place them. A path outside the root comes back as given.
func Seed ¶
func Seed(ctx context.Context, ws *Workspace, sel string, opts Options) (endpoint, storeID, modelID string, stop func(), err error)
Seed boots the embedded OpenFGA engine as a real localhost HTTP server serving a single test's world: it resolves the test selected by sel, loads its model, resolves its fixtures, seeds a fresh store on the engine's server, and exposes that same server over HTTP via the in-process grpc-gateway.
It returns the HTTP endpoint (http://127.0.0.1:<port>), the seeded store and model IDs, and an idempotent stop func that shuts the HTTP server down and, when Seed created the engine, closes it. Seed never writes any config or profile — it only starts an in-memory server.
sel selects one test by "<workspace-relative-file>/<test-name>" or bare test name (same matching as --run). When it matches more than one test, the first in workspace order is served.
func ToProtoTuples ¶ added in v0.269.0
ToProtoTuples converts workspace tuple keys, conditions included, into the proto form the engines expect.
func ValidateTestFile ¶
ValidateTestFile validates raw YAML test-file bytes against the test file schema. It is the same validation the CLI performs when loading a test file, exposed for callers (such as the playground editor) that only have unparsed bytes.
func WithDispatchTags ¶ added in v0.269.0
WithDispatchTags returns a ctx carrying fresh grpc_ctxtags, plus a func that reads the "dispatch_count" the server recorded after a Check (0 if absent).
func WithReadCount ¶ added in v0.269.0
WithReadCount returns a ctx that charges the datastore reads a Check issues under it to a counter of its own, plus a func that reads that counter. Unlike Counters, it never counts a read from another check, such as one an earlier check's abandoned branch issues late.
func WorkspaceSchema ¶
func WorkspaceSchema() []byte
WorkspaceSchema returns the embedded workspace JSON schema bytes, so a command can print it (e.g. to seed an editor's `$schema` binding). The returned slice backs the embedded schema and must not be mutated.
Types ¶
type AssertionResult ¶
type AssertionResult struct {
Kind string `json:"kind"` // one of kindCheck / kindListObjects / kindListUsers
Subject string `json:"subject"`
Expected any `json:"expected"`
Got any `json:"got"`
Passed bool `json:"passed"`
Explain *Explain `json:"explain,omitempty"`
// contains filtered or unexported fields
}
AssertionResult is the outcome of a single check/list_objects/list_users assertion within a test.
type BranchCov ¶
type BranchCov struct {
Label string `json:"label"`
Kind string `json:"kind"`
Covered bool `json:"covered"`
}
BranchCov is the per-branch detail underlying a RelCov: every branch the relation's rewrite enumerates, covered or not.
type CheckCase ¶
type CheckCase struct {
User string `yaml:"user"`
Users []string `yaml:"users"` // group form: share Assertions across many users
Object string `yaml:"object"`
Objects []string `yaml:"objects"` // group form: share Assertions across many objects
Context map[string]any `yaml:"context"`
ContextualTuples []TupleKey `yaml:"contextual_tuples"`
Assertions map[string]bool `yaml:"assertions"`
}
type CheckReq ¶
type CheckReq struct {
User string
Relation string
Object string
Context map[string]any
ContextualTuples []*openfgav1.TupleKey
}
CheckReq is a single Check query.
type Counters ¶ added in v0.269.0
type Counters struct {
// contains filtered or unexported fields
}
Counters tallies datastore tuple reads. The caller resets it between checks; Reads reports the total since the last Reset. Only the four Check-path tuple reads are counted: Read, ReadUserTuple, ReadUsersetTuples and ReadStartingWithUser.
type Coverage ¶
type Coverage struct {
Total int `json:"total"`
Covered int `json:"covered"`
Percent float64 `json:"percent"`
Complete bool `json:"complete"`
Types []TypeCov `json:"types"`
Unreachable []string `json:"unreachable,omitempty"`
Diff *CoverageDiff `json:"diff,omitempty"`
// Bounded reports that at least one assertion's resolution tree was truncated
// by the trace budget (deep/wide model), so this coverage may be
// under-reported. Callers gating on it (--coverage-min / --coverage-diff)
// should surface a warning rather than silently failing on partial data.
Bounded bool `json:"bounded,omitempty"`
}
Coverage summarizes how many rewrite branches (see branchDef) were exercised by a test run. Aggregation from traversed branches into this shape happens in coverage.go; this file only defines the result types.
type CoverageDiff ¶
type CoverageDiff struct {
Base string `json:"base"` // what the model was compared against (e.g. a git ref)
Added []DiffBranch `json:"added"` // branches present now but not in the base model
Uncovered int `json:"uncovered"` // how many Added branches are not covered
}
CoverageDiff reports the rewrite branches a change added versus a base model (e.g. the model on another git ref) and whether each is covered by a test — so a PR that adds an untested relation, arm, or condition can be caught.
type DiffBranch ¶
type DiffBranch struct {
Type string `json:"type"`
Relation string `json:"relation"`
Label string `json:"label"`
Covered bool `json:"covered"`
}
DiffBranch is a single branch that a change added, with its coverage status.
type Engine ¶
type Engine interface {
Resolver
Setup(ctx context.Context, model *openfgav1.AuthorizationModel, tuples []*openfgav1.TupleKey) (storeID, modelID string, err error)
ListObjects(ctx context.Context, s Scope, r ListObjectsReq) ([]string, error)
ListUsers(ctx context.Context, s Scope, r ListUsersReq) ([]string, error)
// DeleteStore removes a store created by Setup. The runner calls it after
// each test so a large suite's memory doesn't grow with the sum of every
// test's stores; it is best-effort (a cleanup failure never fails a test).
DeleteStore(ctx context.Context, storeID string) error
Close() error
}
Engine runs a test suite against an authorization model and tuple set: it sets up a fresh store, answers Check/ListObjects/ListUsers assertions, cleans up, and (via the embedded Resolver) supplies the read primitives the narrator/coverage need.
func NewContainerEngine ¶
NewContainerEngine starts an OpenFGA container from image, waits for it to be healthy, and runs tests against it over gRPC — so a model can be tested against a specific server version rather than the embedded one. Close terminates the container. Requires a running Docker daemon.
func NewEmbeddedEngine ¶
NewEmbeddedEngine builds an Engine backed by a single in-process OpenFGA server and in-memory datastore. serverOpts carries manifest `server:` options; an unknown key is an error. A nil/empty map uses the datastore/server defaults.
func NewRemoteEngine ¶
NewRemoteEngine builds an Engine that runs tests against an OpenFGA server already listening at addr (a gRPC "host:port"). The caller owns the server's lifecycle; Close only releases the connection.
type Explain ¶
type Explain struct {
Verdict bool `json:"verdict"`
Tree *ExplainNode `json:"tree,omitempty"`
NearestMiss string `json:"nearest_miss,omitempty"` // set on a failed check assertion, see explainCheck
SetDiff *SetDiff `json:"set_diff,omitempty"` // set on list_objects/list_users assertions, see setDiff
// Bounded reports that the resolution tree was truncated by the trace
// depth/node budget: some arms were never expanded, so coverage computed from
// this tree is partial (under-credited), not wrong. See fga.ExpandTree.
Bounded bool `json:"bounded,omitempty"`
// contains filtered or unexported fields
}
Explain is the resolution narrative for a single assertion: the engine's verdict plus a faithful tree of how that verdict was reached.
type ExplainNode ¶
type ExplainNode struct {
Label string `json:"label"`
Rel string `json:"rel,omitempty"` // this node's own "type#relation" key, e.g. "document#viewer"; empty for operator/union nodes
Result bool `json:"result"`
Reason string `json:"reason,omitempty"`
Children []*ExplainNode `json:"children,omitempty"`
// DirectMember reports that the queried user appears as a direct member of
// this node's own direct-user leaf (a literal tuple, or a public-wildcard
// tuple for the user's type). It is the signal coverage uses to tell a
// condition denial (Result==false while the user IS directly assigned, so
// only a failed ABAC condition can have denied) apart from a plain no-tuple
// denial (user not assigned at all) — only the former exercises a
// condition:<c>=false branch.
DirectMember bool `json:"direct_member,omitempty"`
// Conditions names the ABAC condition(s) carried by the direct tuple(s) that
// make the queried user a direct member of this leaf (empty for an
// unconditioned assignment). It is set only on a DirectMember leaf and lets
// coverage credit the specific condition:<name>=true/=false branch that was
// exercised, rather than every condition declared on the relation.
Conditions []string `json:"conditions,omitempty"`
}
ExplainNode is one node in the resolution tree: a relation being resolved or a leaf, with whether it granted and a short reason.
type ListObjectsCase ¶
type ListObjectsReq ¶
ListObjectsReq is a single ListObjects query.
type ListUsersCase ¶
type ListUsersCase struct {
Object string `yaml:"object"`
UserFilter []ListUsersFilter `yaml:"user_filter"`
Context map[string]any `yaml:"context"`
Assertions map[string]ListUsersExpectation `yaml:"assertions"`
}
type ListUsersExpectation ¶
type ListUsersExpectation struct {
Users []string `yaml:"users"`
}
func (*ListUsersExpectation) UnmarshalYAML ¶
func (e *ListUsersExpectation) UnmarshalYAML(value *yaml.Node) error
UnmarshalYAML accepts a list_users expectation as either the flat form (`relation: [user:anne, user:bob]`, parallel to list_objects) or the wrapped form (`relation: {users: [...]}`, matching the official OpenFGA CLI).
type ListUsersFilter ¶
type ListUsersReq ¶
type ListUsersReq struct {
Object string
Relation string
Filters []ListUsersFilter
Context map[string]any
}
ListUsersReq is a single ListUsers query.
type LoadedModel ¶
type LoadedModel struct {
Proto *openfgav1.AuthorizationModel
SDK *openfga.AuthorizationModel
}
LoadedModel holds an authorization model decoded into both the proto view (for the embedded engine) and the SDK view (for the narrator), built from a single transformer pass so both stay in sync.
func LoadModelBytes ¶
func LoadModelBytes(data []byte) (*LoadedModel, error)
LoadModelBytes decodes an authorization model from raw bytes (DSL or JSON), autodetecting the format. It backs loadModel and lets callers load a model that isn't on disk (e.g. one fetched from a git ref for coverage diffing).
type Manifest ¶
type Manifest struct {
Version int `yaml:"version"`
Model string `yaml:"model"`
Fixtures []string `yaml:"fixtures"` // glob patterns registering fixture files, like Tests
Tuples []string `yaml:"tuples"` // interchangeable alias for Fixtures; merged in at load
Tests []string `yaml:"tests"`
Server map[string]any `yaml:"server"`
// contains filtered or unexported fields
}
type Options ¶
type Options struct {
Run string
Parallel int
Explain string
Coverage bool
Dedupe bool
Engine Engine
// Timeout bounds the engine work of a single test (0 = no timeout). It guards
// against a pathological/cyclic model or a hung server wedging the run.
Timeout time.Duration
// FailFast stops the run after the first failing test rather than executing
// every matched test.
FailFast bool
// DiffBaseModel, when set, enables coverage diffing: branches present in the
// workspace model but not in this base model are reported as "added", with
// their coverage status. DiffBaseName labels it in output (e.g. a git ref).
DiffBaseModel *LoadedModel
DiffBaseName string
}
Options controls Run.
type RelCov ¶
type RelCov struct {
Relation string `json:"relation"`
Covered int `json:"covered"`
Total int `json:"total"`
Missed []string `json:"missed,omitempty"` // branchDef.Label values not covered
Branches []BranchCov `json:"branches,omitempty"` // full per-branch detail
}
RelCov is the per-relation rollup of Coverage.
type Resolver ¶
type Resolver interface {
Check(ctx context.Context, s Scope, r CheckReq) (bool, error)
// Expand returns the userset (resolution) tree for object#relation, used
// by the narrator to explain how a verdict was reached.
Expand(ctx context.Context, s Scope, object, relation string) (*openfgav1.UsersetTree, error)
// Read returns the "user" side of the tuples matching object#relation. It
// backs the narrator's tuple-to-userset resolution.
Read(ctx context.Context, s Scope, object, relation string) ([]string, error)
// ReadConditions returns, for object#relation, the ABAC condition name(s)
// attached to each user's direct tuple(s), keyed by user string (a user with
// no condition is absent from the map). It backs per-condition coverage
// attribution so a condition:<name>=true/=false branch is only credited when
// that specific condition was exercised.
ReadConditions(ctx context.Context, s Scope, object, relation string) (map[string][]string, error)
}
Resolver answers the read queries the trace narrator and coverage need to explain how a verdict was reached: the Check itself plus the raw Expand/Read/ReadConditions primitives. It is the narrow interface trace() depends on, kept separate from the full Engine so the "explain needs deeper access than running a test" seam is explicit.
type Results ¶
type Results struct {
SchemaVersion int `json:"schema_version"`
Summary Summary `json:"summary"`
Tests []TestResult `json:"tests"`
Coverage *Coverage `json:"coverage,omitempty"`
// CoverageError carries the reason coverage could not be aggregated when
// Options.Coverage was set (e.g. a multi-model workspace has no single
// model to enumerate against). It is set only when Coverage is nil; the
// tests themselves still ran. Empty on the successful (Coverage populated)
// path.
CoverageError string `json:"coverage_error,omitempty"`
// Label prefixes GitHub annotation titles; empty means "model test".
Label string `json:"-"`
}
Results is the outcome of running a set of tests.
type SetDiff ¶
type SetDiff struct {
Unexpected []string `json:"unexpected,omitempty"`
Missing []string `json:"missing,omitempty"`
}
SetDiff captures the difference between an expected and observed set of objects/users for list_objects/list_users assertions.
type Summary ¶
type Summary struct {
Total int `json:"total"`
Passed int `json:"passed"`
Failed int `json:"failed"`
MatchedFiles int `json:"matched_files"`
MatchedTests int `json:"matched_tests"`
// Incomplete reports that --fail-fast stopped the run before every matched
// test ran, so counts (and any coverage) reflect only the tests that ran.
Incomplete bool `json:"incomplete,omitempty"`
DurationMs int64 `json:"duration_ms"` // total wall-clock of the run (tests run in parallel, so this is NOT the sum of TestResult.DurationMs)
}
Summary aggregates counts across all matched tests.
type Test ¶
type Test struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Line int `yaml:"-"`
Column int `yaml:"-"`
// Fixtures and Tuples are interchangeable keywords for this test's setup
// tuples. Each entry is either a fixture reference (a string) or an inline
// tuple (a mapping); the two lists are merged at resolution.
Fixtures []TupleItem `yaml:"fixtures"`
Tuples []TupleItem `yaml:"tuples"`
Check []CheckCase `yaml:"check"`
ListObjects []ListObjectsCase `yaml:"list_objects"`
ListUsers []ListUsersCase `yaml:"list_users"`
}
type TestFile ¶
type TestFile struct {
Path string `yaml:"-"`
Model string `yaml:"model"`
// Fixtures / Tuples are interchangeable keywords for the file-level list of
// fixtures every test in this file uses; Tuples is merged into Fixtures at
// load. (This top-level Tuples is fixture references — distinct from a
// test's own inline Test.Tuples.)
Fixtures []string `yaml:"fixtures"`
Tuples []string `yaml:"tuples"`
Tests []Test `yaml:"tests"`
}
type TestResult ¶
type TestResult struct {
Name string `json:"name"` // "<workspace-relative-test-file>/<test-name>"
Description string `json:"description,omitempty"` // the test's optional `description:`, surfaced in the failure header
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
Passed bool `json:"passed"`
Assertions []AssertionResult `json:"assertions"`
DurationMs int64 `json:"duration_ms"`
// Error is set when the test could not be executed at all (model/fixture
// load, store setup, or an engine error mid-assertion) rather than an
// assertion simply failing. Such a test is reported as failed and errored,
// but — like go test / pytest — it is isolated to itself so the rest of the
// suite still runs and reports. Empty on a test that executed to completion.
Error string `json:"error,omitempty"`
// contains filtered or unexported fields
}
TestResult is the outcome of a single test.
type TupleItem ¶
TupleItem is one entry in a test's `fixtures`/`tuples` list: either a fixture reference (Ref — a registered fixture name, or a ./ or ../ path) or an inline tuple (Tuple). Exactly one is set, decided by whether the YAML entry is a scalar or a mapping.
type TupleKey ¶
type TupleKey struct {
User string `yaml:"user"`
Relation string `yaml:"relation"`
Object string `yaml:"object"`
Condition *TupleCond `yaml:"condition"`
}
func ResolveTestTuples ¶ added in v0.269.0
ResolveTestTuples resolves the tuple set for a single test (its file-level fixtures plus the test's own fixtures and inline tuples). It is the exported form of the resolution `ofga test` performs, for callers outside the package that build tuple sets from a workspace.
func (*TupleKey) UnmarshalYAML ¶
UnmarshalYAML lets a tuple be written either as a mapping ({user, relation, object, condition}) or as the compact string form "user relation object" (the same order as `ofga tuples write`). A conditioned tuple must use the mapping form. Unknown mapping keys are rejected.
type TypeCov ¶
type TypeCov struct {
Type string `json:"type"`
Covered int `json:"covered"`
Total int `json:"total"`
Relations []RelCov `json:"relations"`
}
TypeCov is the per-object-type rollup of Coverage.
type Workspace ¶
type Workspace struct {
Root string
Manifest *Manifest
TestFiles []*TestFile
// Fixtures maps a registered fixture's name (its filename without extension)
// to its absolute path, expanded from the manifest's `fixtures` glob
// patterns. Test files reference fixtures by that name. Nil for a bare test
// file loaded without a manifest.
Fixtures map[string]string
}
func LoadWorkspace ¶
LoadWorkspace loads and validates an ofga workspace rooted at path, using only what's on disk. See LoadWorkspaceWith to override or supply model, fixtures, or tests from flags.
func LoadWorkspaceWith ¶
func LoadWorkspaceWith(path string, opts WorkspaceOptions) (*Workspace, error)
LoadWorkspaceWith loads a workspace, applying opts. With no options it is identical to LoadWorkspace. With options, a discovered manifest's fields are overridden by any set option; if no manifest is found, the workspace is built entirely from the options (requiring at least Model and Tests).
func (*Workspace) ModelPath ¶
ModelPath returns the single model file the workspace's tests resolve to, erroring when test files override to more than one model. The CLI uses it to fetch the base model for a coverage diff.
func (*Workspace) TestFileID ¶
TestFileID returns a stable workspace-relative identifier without the .test.yaml/.test.yml suffix.
type WorkspaceOptions ¶
WorkspaceOptions supplies or overrides workspace configuration from CLI flags. A non-empty field replaces the corresponding manifest field. When no manifest is discovered, Model and Tests are required and a manifest-free workspace is built from these values (globs relative to path). Globs are relative to the discovered manifest's directory when a manifest is present.