authztest

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package authztest provides a reusable authorization scenario test kit for HAIStack. The Go catalog (AllScenarios) exercises pkg/auth, pkg/smart, pkg/view, pkg/ai, and related seams with documented principal/policy fixtures and table-driven allow/deny expectations.

OAuth token exchange success is not authorization. Scenarios assert semantic access-control outcomes: restricted principals, patient-compartment boundaries, policy narrowing of SMART scopes, token expiry, and per-path denials across REST, search, views, AI tools, sync, and module install.

Machine-readable YAML catalogues (research/policy-semantics and testdata) are loaded with ParseYAML / LoadYAMLFile and executed through ScenariosFromYAML. YAML cases evaluate SMART scope grants ∩ pkg/auth policy allows, matching the policy-semantics research artefact. They call CanExecuteView / CanExecuteAITool through pkg/auth with SMART-derived RequiredPermissions; they do not load ViewDefinitions or run pkg/view / pkg/ai executors. Principals, roles, and policy documents are declared in the YAML and drive the SMART adapter. Tenant and kind are required (no TenantA or KindUser fallback). policyRoleGrants / roleGrants overlay extra role permissions per named policy or scenario. YAML catalogues run with RunYAML and do not construct Go BaseConfig kits. Scenario principal, scopes, action, resourceType, and policy are required (no clinician / user/*.read / read / Patient / base fallbacks).

Optional JSON fixtures under testdata/ (declarative-scenarios.json) can be loaded with LoadDeclarativeFile and RunDeclarative for compartment overlay and legacy BaseConfig cases; consent overlays are skipped. Track C publishes scenarios.yaml only.

This package is for tests and the Track C research CLI (research/policy-semantics), which issue #11 places in authztest. Other production packages must not import authztest.

Index

Constants

View Source
const (
	TenantA = "tenant-a"
	TenantB = "tenant-b"
)
View Source
const (
	ExpectAllow = true
	ExpectDeny  = false
)

ExpectAllow and ExpectDeny are the two authorization outcomes scenarios assert.

Variables

This section is empty.

Functions

func AssertDecision

func AssertDecision(name string, expectAllow bool, decision auth.Decision, err error) error

AssertDecision compares an authorization decision to the expected outcome.

func AssertDeniedError

func AssertDeniedError(name string, err error) error

AssertDeniedError reports when an error was expected but not returned.

func BackendServicePrincipal

func BackendServicePrincipal() auth.Principal

BackendServicePrincipal represents a validated SMART backend client.

func BaseConfig

func BaseConfig() auth.Config

BaseConfig returns a standard engine configuration for scenario tests.

func BaseDevices

func BaseDevices() []auth.DeviceIdentity

BaseDevices returns trusted and untrusted device fixtures.

func BasePolicy

func BasePolicy() *auth.PolicyDocument

BasePolicy is a deny-by-default policy with appointment, view, AI, device, and module rules.

func BaseRoles

func BaseRoles() []auth.Role

BaseRoles returns the standard role catalog for scenario engines.

func CatalogSize

func CatalogSize() int

CatalogSize returns the number of documented scenarios.

func DeclarativeFixturePath

func DeclarativeFixturePath() (string, error)

DeclarativeFixturePath returns the authztest JSON compartment-overlay fixture.

func DefaultEngine

func DefaultEngine(t *testing.T) *auth.Engine

DefaultEngine returns an engine with BaseConfig.

func MustEngine

func MustEngine(t *testing.T, cfg auth.Config) *auth.Engine

MustEngine constructs an auth.Engine or fails the test.

func MustEngineFromConfig

func MustEngineFromConfig(cfg auth.Config) *auth.Engine

MustEngineFromConfig builds an engine without a testing.T (for inline scenario configs).

func NarrowEngineConfigWithDenyFirst

func NarrowEngineConfigWithDenyFirst() auth.Config

func NarrowObservationPolicy

func NarrowObservationPolicy() *auth.PolicyDocument

NarrowObservationPolicy allows only Observation reads (policy narrows SMART patient/*.read).

func PatientScopedTenant

func PatientScopedTenant(patientID string) auth.TenantContext

PatientScopedTenant scopes access to one patient id.

func PatientScopedUser

func PatientScopedUser() auth.Principal

PatientScopedUser is a clinician bound to a single patient compartment.

func RestrictedClinician

func RestrictedClinician() auth.Principal

RestrictedClinician may read/write appointments only.

func Run

func Run(t *testing.T, scenarios []Scenario, kit *Kit)

Run executes every scenario, failing the test on the first error.

func RunAll

func RunAll(t *testing.T, kit *Kit)

RunAll executes the full documented scenario catalog.

func RunDeclarative

func RunDeclarative(ctx context.Context, scenarios []DeclarativeScenario) error

RunDeclarative executes portable scenarios that do not declare consent.

func RunYAML

func RunYAML(t *testing.T, scenarios []Scenario)

RunYAML executes catalogue scenarios that carry their own engine and SMART adapter from the YAML file. It does not construct Go BaseConfig fixtures.

func SmartAdapter

func SmartAdapter() *smart.AuthAdapter

SmartAdapter returns a configured SMART → auth adapter for scenario tests.

func TenantAdmin

func TenantAdmin() auth.Principal

TenantAdmin may install modules and has broader permissions.

func TenantContextA

func TenantContextA() auth.TenantContext

TenantContextA is an unrestricted tenant binding.

func ValidateCatalog

func ValidateCatalog(scenarios []Scenario) error

ValidateCatalog ensures every scenario has a name and run function.

Types

type DeclarativeScenario

type DeclarativeScenario struct {
	ID            string          `json:"id"`
	Doc           string          `json:"doc"`
	Principal     string          `json:"principal"`
	Policy        string          `json:"policy"`
	Scopes        string          `json:"scopes,omitempty"`
	LaunchPatient string          `json:"launchPatient,omitempty"`
	PatientScope  string          `json:"patientScope,omitempty"`
	Tenant        string          `json:"tenant,omitempty"`
	PurposeOfUse  string          `json:"purposeOfUse,omitempty"`
	Action        string          `json:"action"`
	ResourceType  string          `json:"resourceType,omitempty"`
	ResourceID    string          `json:"resourceId,omitempty"`
	Resource      json.RawMessage `json:"resource,omitempty"`
	ToolName      string          `json:"toolName,omitempty"`
	Consent       json.RawMessage `json:"consent,omitempty"`
	ExpectAllow   bool            `json:"expectAllow"`
}

DeclarativeScenario is a portable principal+policy+request case for tests. The canonical Track C artefact is research/policy-semantics/scenarios.yaml. JSON fixtures (testdata/declarative-scenarios.json) exercise compartment overlay via resource bodies and legacy BaseConfig policies in tests only. Consent overlays are skipped by RunDeclarative.

func LoadDeclarativeFile

func LoadDeclarativeFile(path string) ([]DeclarativeScenario, error)

LoadDeclarativeFile reads a JSON scenario fixture from disk.

type Kit

type Kit struct {
	Engine  *auth.Engine
	Adapter *smart.AuthAdapter
}

Kit holds shared fixtures for running authorization scenarios.

func NewDefaultKit

func NewDefaultKit(eng *auth.Engine) *Kit

NewDefaultKit returns a Kit backed by the given engine and a default SMART adapter.

type Scenario

type Scenario struct {
	// Name is a stable identifier used in test output and CI matrices.
	Name string
	// Doc explains the principal, action, resource, and expected outcome.
	Doc string
	// Run executes the scenario against a Kit and returns an error on failure.
	Run func(ctx context.Context, kit *Kit) error
}

Scenario documents one authorization outcome test.

func AllScenarios

func AllScenarios() []Scenario

AllScenarios returns the documented authorization scenario catalog (≥30 cases).

func ScenariosFromYAML

func ScenariosFromYAML(file YAMLFile) ([]Scenario, error)

ScenariosFromYAML converts machine-readable cases into runnable Scenario values.

type YAMLFile

type YAMLFile struct {
	Version          string                                  `yaml:"version"`
	Roles            []auth.Role                             `yaml:"roles"`
	Principals       map[string]YAMLPrincipal                `yaml:"principals"`
	PolicyRoleGrants map[string]map[string][]auth.Permission `yaml:"policyRoleGrants"`
	Policies         map[string]auth.PolicyDocument          `yaml:"policies"`
	Scenarios        []YAMLScenario                          `yaml:"scenarios"`
}

YAMLFile is a machine-readable authorization scenario catalogue.

func LoadYAMLFile

func LoadYAMLFile(path string) (YAMLFile, error)

LoadYAMLFile reads a YAML scenario catalogue from disk.

func ParseYAML

func ParseYAML(data []byte) (YAMLFile, error)

ParseYAML unmarshals a YAML scenario catalogue.

type YAMLPrincipal

type YAMLPrincipal struct {
	ID       string   `yaml:"id"`
	Kind     string   `yaml:"kind"`
	ClientID string   `yaml:"clientId"`
	Tenant   string   `yaml:"tenant"`
	Roles    []string `yaml:"roles"`
}

YAMLPrincipal is a SMART identity declared in the catalogue (not a Go fixture). Tenant and kind are required; there is no fallback to authztest.TenantA or KindUser.

type YAMLScenario

type YAMLScenario struct {
	Name           string                       `yaml:"name"`
	Doc            string                       `yaml:"doc"`
	Principal      string                       `yaml:"principal"`
	Scopes         string                       `yaml:"scopes"`
	Policy         string                       `yaml:"policy"`
	PolicyDocument *auth.PolicyDocument         `yaml:"policyDocument"`
	RoleGrants     map[string][]auth.Permission `yaml:"roleGrants"`
	Action         string                       `yaml:"action"`
	ResourceType   string                       `yaml:"resourceType"`
	ResourceID     string                       `yaml:"resourceId"`
	ViewName       string                       `yaml:"viewName"`
	ToolName       string                       `yaml:"toolName"`
	PatientID      string                       `yaml:"patientId"`
	PatientScope   string                       `yaml:"patientScope"`
	Resource       map[string]interface{}       `yaml:"resource,omitempty"`
	Tenant         string                       `yaml:"tenant"`
	ExpectAllow    bool                         `yaml:"expectAllow"`
}

YAMLScenario is one vendor-neutral policy × SMART-scope test case.

ExpectAllow is the intersection of SMART scope grants and pkg/auth policy allows. A case is allowed only when both layers permit the action.

Policy names a document in YAMLFile.Policies. PolicyDocument embeds a portable pkg/auth policy inline. Named Go policy enums are not used. Principal names YAMLFile.Principals. RoleGrants overlay extra permissions for this scenario only (in addition to PolicyRoleGrants). Principal, scopes, action, resourceType, and policy (or PolicyDocument) are required.

Jump to

Keyboard shortcuts

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