Documentation
¶
Overview ¶
Package policy provides experimental, side-effect-free policy evaluation.
Callers supply already resolved, trusted rules and collected input snapshots. The explicit plan-directory loader and planfile subpackage support a narrow Terraform command gate. This package does not discover trusted tiers, resolve trust, collect CI facts, compute affected inventories, verify approvals or execute hooks. It must not be treated as an enforcement boundary on its own.
Evaluator adapters receive materialized JSON, never lazy configuration values or an automation host. NewEngine registers CEL, restricted Starlark, OPA, and JSON Schema adapters. Existing settings.validation behavior is unchanged.
Index ¶
- Constants
- func BeginExplanation(emit func(Explanation), rules []Rule) func()
- func DetectAgents() []string
- func DirectoryFromEnvironment() (string, error)
- func EnforceDecision(decision Decision) error
- func Explain(kind InputKind, rule, status string)
- func GitHubApprovers(head, author string, reviews []GitHubReview) ([]string, error)
- func InputSchema(kind InputKind) (*jsonschema.Schema, error)
- func IsAdmissionError(err error) bool
- func IsDestroyInvocation(path, args []string) bool
- func IsErrorEvent(kind InputKind) bool
- func ValidateTerraformPlan(data json.RawMessage) error
- type AffectedInput
- type ApprovalRequirement
- type AtmosFacts
- type AuthInput
- type Availability
- type Bundle
- type CEL
- type CICollector
- type CIRequirement
- type CISnapshot
- type ChangeAction
- type ClockFacts
- type CommandInput
- type ComponentCommandInput
- type ContextCheck
- type ContextProvider
- type Dataset
- type Decision
- type DecisionStatus
- type DetailedEvaluator
- type Diagnostic
- type DiskFacts
- type Effects
- type Engine
- type EngineOption
- type ErrorInput
- type Evaluation
- type EvaluationResult
- type Evaluator
- type ExecutionError
- type Explanation
- type FactCollector
- type FieldChange
- type FileChange
- type FileCheckOption
- type FileResult
- type FileSelector
- type Finding
- type FunctionInput
- type GitHubApprovalSpec
- type GitHubReview
- type HookRequirement
- type HostContextProvider
- type HostFacts
- type InputKind
- type InventorySnapshot
- type JSONSchema
- type MemoryFacts
- type OPA
- type OPAConfig
- type ObjectChange
- type ObjectIdentity
- type OperationInput
- type PluginInput
- type Provenance
- type Request
- type Revisions
- type Rule
- type RuntimeContext
- type SchemaConfig
- type Selector
- type SourceInput
- type Starlark
- type Subject
- type SubjectMetadata
- type TestCase
- type TestResult
- type UserFacts
- type Violation
Constants ¶
const CELEngine = "cel"
CELEngine is the explicit registry key for the CEL predicate adapter.
const JSONSchemaEngine = "jsonschema"
JSONSchemaEngine selects effects when the input fails schema validation.
const OPAEngine = "opa"
OPAEngine evaluates embedded, pure Rego policies.
const StarlarkEngine = "starlark"
StarlarkEngine is the registry key for restricted Starlark policy predicates.
Variables ¶
This section is empty.
Functions ¶
func BeginExplanation ¶
func BeginExplanation(emit func(Explanation), rules []Rule) func()
BeginExplanation installs an invocation-scoped, serialized diagnostic sink. The returned cleanup reports configured input kinds never reached by this invocation.
func DetectAgents ¶
func DetectAgents() []string
DetectAgents captures only agent names, never session IDs or arbitrary environment values. These inherited markers are advisory: a caller can remove or forge them.
func DirectoryFromEnvironment ¶
DirectoryFromEnvironment resolves an explicit override or the default policy.d directory. The default is the policy.d next to the configuration that atmos.yaml discovery selects, using the same precedence: --config/--config-path (then ATMOS_CONFIG and ATMOS_CONFIG_PATH), ATMOS_CLI_CONFIG_PATH, the working directory, then the Git root unless ATMOS_GIT_ROOT_BASEPATH=false, then the nearest ancestor holding atmos.yaml, which config loading also reads. The first of those directories holding a policy.d wins; the working directory is always considered. Discovery does not establish trust. A missing default is allowed; an explicit missing directory is returned so loading fails rather than falling back.
func EnforceDecision ¶
EnforceDecision converts a pure decision into a local gate. This executor has no approval verifier or hook executor: outstanding obligations must not become success. Denial explanations include only static rule identifiers and author-supplied reasons, never evaluated values.
func GitHubApprovers ¶
func GitHubApprovers(head, author string, reviews []GitHubReview) ([]string, error)
GitHubApprovers returns the latest decisive current-head approvals, excluding the author. The caller must verify freshness, pagination completeness and checkout binding.
func InputSchema ¶
func InputSchema(kind InputKind) (*jsonschema.Schema, error)
InputSchema returns the schema for an implemented input, never a proposed capability.
func IsAdmissionError ¶
IsAdmissionError reports whether err is a policy admission failure: a denial, an unmet requirement, or a policy that could not be loaded or evaluated. Admission fails closed, so callers must surface these errors unchanged rather than relabeling them as hook or execution failures.
func IsDestroyInvocation ¶
IsDestroyInvocation reports whether a command invocation destroys infrastructure. It derives the boolean exposed as `destroy` in command and component.command policy inputs, so rule authors never parse argument values themselves.
The path is the canonical command path (for example ["terraform", "apply"]), or the component type followed by the subcommand. The args are the raw command-line arguments of the invocation (positionals and flags in any order). They are only inspected for the Terraform family, and only for the `destroy` flag; no other argument value is derived or exposed.
The result is true when:
- the path is `terraform destroy` or `helmfile destroy`, or
- the path belongs to the terraform family (OpenTofu shares it) and any argument is the destroy flag: -destroy or --destroy, with or without a boolean value (-destroy=true, --destroy=1, -destroy=T, ...), including after the `--` separator.
A false boolean value such as -destroy=false, -destroy=0, or -destroy=F does not make a command a destroy. Values are parsed with strconv.ParseBool, like Go's flag package. The check fails closed: an unparseable value counts as true, and any true occurrence wins over a later false one, because the final argument order seen by the tool can differ from the order typed.
It cannot see destruction that was decided earlier, such as applying a saved plan created with `plan -destroy`. Terraform plan policies cover that case.
func IsErrorEvent ¶
IsErrorEvent accepts concrete error events and a component's subcommand wildcard.
func ValidateTerraformPlan ¶
func ValidateTerraformPlan(data json.RawMessage) error
ValidateTerraformPlan validates the native show -json plan envelope without replacing it with a summary or discarding unknown/sensitive/forward-compatible fields. It does not attest that supplied JSON came from a saved binary; the collector does that.
Types ¶
type AffectedInput ¶
type AffectedInput struct {
Complete bool `json:"complete"`
Reasons []string `json:"reasons"`
Files []FileChange `json:"files"`
Components []ObjectChange `json:"components"`
Instances []ObjectChange `json:"instances"`
Stacks []ObjectChange `json:"stacks"`
Changes []FieldChange `json:"changes"`
}
AffectedInput is a materialized analysis payload for Request.Input. The command collector compares unfiltered static inventories under active discovery settings; it does not reuse the filtered describe-affected presentation as its inventory. Empty, complete lists must be encoded as [] rather than unavailable/null lists. Evaluating this payload never computes inventories or schedules component work.
func BuildAffectedInput ¶
func BuildAffectedInput(before, after InventorySnapshot, files []FileChange, sourceAffected []ObjectIdentity) (AffectedInput, error)
BuildAffectedInput compares independently collected snapshots. SourceAffected identifies instances whose component files changed without a stack-value change.
type ApprovalRequirement ¶
type ApprovalRequirement struct {
ID string `json:"id"`
Provider string `json:"provider"`
Spec json.RawMessage `json:"spec"`
}
ApprovalRequirement remains outstanding until a trusted CI resolver verifies it. Spec is provider-owned data, not a universal team/review vocabulary.
type AtmosFacts ¶
AtmosFacts describes the running executable and active crypto mode.
type Availability ¶
type Availability string
Availability is explicit: an absent/zero state is never complete evidence.
const ( Available Availability = "available" Incomplete Availability = "incomplete" )
type Bundle ¶
Bundle contains governing rules and hook definitions, never workspace hooks. Hook payloads use the existing hook schema and are decoded by that executor.
func LoadDirectory ¶
LoadDirectory loads explicit, protected local policy documents. It performs no remote imports, template expansion, hook execution or automatic trust discovery. OPA modules and JSON Schemas are materialized from within the policy directory.
type CEL ¶
type CEL struct{}
CEL evaluates boolean predicates with no custom functions or I/O capabilities. The zero value uses a bounded default runtime cost. Compile size is bounded too.
type CICollector ¶
type CICollector interface {
Collect(ctx context.Context) (*CISnapshot, error)
}
CICollector is the provider adapter seam outside pure evaluation. Implementations must document schemas, token permissions, and capabilities. Native CI integration uses pkg/ci.PolicySnapshotProvider; the evaluator never invokes collectors.
type CIRequirement ¶
type CIRequirement struct {
Provider string `json:"provider" yaml:"provider"`
Schema string `json:"schema" yaml:"schema"`
Dataset string `json:"dataset" yaml:"dataset"`
Fact string `json:"fact,omitempty" yaml:"fact,omitempty"`
}
CIRequirement names an exact provider/schema and dataset required before evaluation. Dataset is metadata, event, or facts; Fact names the provider-specific fact for facts.
type CISnapshot ¶
type CISnapshot struct {
Provider string `json:"provider"`
Schema string `json:"schema"`
Metadata Dataset `json:"metadata"`
Event Dataset `json:"event"`
Facts map[string]Dataset `json:"facts"`
}
CISnapshot is a small envelope with provider-owned schemas and JSON payloads. Triggering Event is separate from subsequently fetched Facts (reviews, checks, etc.). This does not replace pkg/ci.Context or the boolean workflow/hook condition ci.
type ChangeAction ¶
type ChangeAction string
ChangeAction distinguishes additions, modifications, and removals. Collectors represent ambiguous moves conservatively as removal/addition, with Ambiguous set.
const ( Added ChangeAction = "add" Modified ChangeAction = "modify" Removed ChangeAction = "remove" )
type ClockFacts ¶
type ClockFacts struct {
Now string `json:"now,omitempty"`
Date string `json:"date,omitempty"`
Weekday string `json:"weekday,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
ClockFacts is one UTC instant shared by every rule in an evaluation.
type CommandInput ¶
type CommandInput struct {
Command string `json:"command"`
Path []string `json:"path"`
Destroy bool `json:"destroy"`
}
CommandInput is the canonical command path without argument values. Destroy is the only value derived from arguments: a normalized boolean, see IsDestroyInvocation.
type ComponentCommandInput ¶
type ComponentCommandInput struct {
Agents []string `json:"agents"`
Command string `json:"command"`
ComponentType string `json:"component_type"`
Component string `json:"component"`
Stack string `json:"stack"`
DryRun bool `json:"dry_run"`
Destroy bool `json:"destroy"`
Capabilities []string `json:"capabilities"`
}
ComponentCommandInput describes shared component admission.
type ContextCheck ¶
type ContextCheck struct {
Kind string `json:"kind" yaml:"kind"`
Path string `json:"path,omitempty" yaml:"path"`
Constraint string `json:"constraint,omitempty" yaml:"constraint"`
Format string `json:"format,omitempty" yaml:"format"`
Start string `json:"start,omitempty" yaml:"start"`
End string `json:"end,omitempty" yaml:"end"`
Timezone string `json:"timezone,omitempty" yaml:"timezone"`
Weekdays []string `json:"weekdays,omitempty" yaml:"weekdays"`
StartTime string `json:"start_time,omitempty" yaml:"start_time"`
EndTime string `json:"end_time,omitempty" yaml:"end_time"`
}
ContextCheck is a pure, engine-independent operation over the shared context. Path is an RFC 6901 JSON pointer. Ranges include start and exclude end.
type ContextProvider ¶
type ContextProvider interface {
Collect(context.Context) (*RuntimeContext, error)
}
ContextProvider collects evidence outside pure language evaluators. Callers can inject deterministic snapshots without changing engine behavior.
type Dataset ¶
type Dataset struct {
Data json.RawMessage `json:"data,omitempty"`
Status Availability `json:"status"`
Complete bool `json:"complete"`
Provenance Provenance `json:"provenance"`
Reason string `json:"reason,omitempty"`
}
Dataset keeps native data alongside its availability, completeness, and origin. Adapters must not mark truncated pagination complete or fabricate event payloads.
func ApproverDataset ¶
func ApproverDataset(names []string, provenance Provenance) Dataset
ApproverDataset encodes verified reviewer names with their collection provenance.
type Decision ¶
type Decision struct {
Status DecisionStatus `json:"status"`
Findings []Finding `json:"findings"`
}
Decision is a pure evaluation result, not a final CI or operation result. Error dominates deny, then awaiting approval, allow, and not applicable.
func ResolveGitHubApprovals ¶
func ResolveGitHubApprovals(decision Decision, head, author string, reviews []GitHubReview) (Decision, error)
ResolveGitHubApprovals is pure; the caller must supply complete, freshly fetched reviews bound to the current open PR and the revision being executed. The latest decisive review wins. Comments never grant or revoke approval.
type DecisionStatus ¶
type DecisionStatus string
DecisionStatus distinguishes authorization from missing evidence and errors.
const ( Allow DecisionStatus = "allow" Deny DecisionStatus = "deny" AwaitingApproval DecisionStatus = "awaiting_approval" NotApplicable DecisionStatus = "not_applicable" EvaluationError DecisionStatus = "error" )
type DetailedEvaluator ¶
type DetailedEvaluator interface {
EvaluateDetailed(ctx context.Context, evaluation Evaluation) (EvaluationResult, error)
}
DetailedEvaluator is an optional capability, preserving the boolean Evaluator API.
type Diagnostic ¶
type Diagnostic struct {
Message string `json:"message"`
Path string `json:"path,omitempty"`
SchemaPath string `json:"schema_path,omitempty"`
Details json.RawMessage `json:"details,omitempty"`
}
Diagnostic retains a validator's explanation and document location. Messages and details may contain input values; callers control their disclosure.
type DiskFacts ¶
type DiskFacts struct {
Path string `json:"path,omitempty"`
AvailableBytes *uint64 `json:"available_bytes"`
TotalBytes *uint64 `json:"total_bytes"`
}
DiskFacts names the sampled filesystem location explicitly.
type Effects ¶
type Effects struct {
Retry *schema.RetryConfig `json:"retry,omitempty"`
Deny bool `json:"deny"`
Reason string `json:"reason,omitempty"`
Approvals []ApprovalRequirement `json:"approvals,omitempty"`
Hooks []HookRequirement `json:"hooks,omitempty"`
}
Effects are obligations selected by a predicate. They cannot perform side effects.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine owns an instance-local language registry; it has no implicit evaluators. Its zero value is usable. Register adapters before evaluation for reproducibility.
func NewEngine ¶
func NewEngine(options ...EngineOption) *Engine
NewEngine returns an isolated registry with the supported pure evaluators.
type EngineOption ¶
type EngineOption func(*Engine)
EngineOption configures an engine before concurrent use.
func WithContextProvider ¶
func WithContextProvider(provider ContextProvider) EngineOption
WithContextProvider replaces host collection for embedding or deterministic tests.
func WithFactCollector ¶
func WithFactCollector(collector FactCollector) EngineOption
WithFactCollector configures the host's optional provider evidence collector.
type ErrorInput ¶
type ErrorInput struct {
Event string `json:"event"`
ComponentType string `json:"component_type"`
Command string `json:"command"`
Component string `json:"component"`
Stack string `json:"stack"`
Stage string `json:"stage"`
Attempt int `json:"attempt"`
ExitCode int `json:"exit_code"`
Output string `json:"output"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Error ExecutionError `json:"error"`
}
ErrorInput describes one failed invocation, not an entire component pipeline.
type Evaluation ¶
type Evaluation struct {
Checks map[string]bool `json:"checks,omitempty"`
Expression string `json:"expression"`
Parameters json.RawMessage `json:"parameters,omitempty"`
Request *Request `json:"request"`
OPA *OPAConfig `json:"opa,omitempty"`
Schema *SchemaConfig `json:"schema,omitempty"`
}
Evaluation contains detached, materialized data for a single predicate. Adapters must be concurrency-safe, honor cancellation, and perform no I/O.
type EvaluationResult ¶
type EvaluationResult struct {
Matched bool `json:"matched"`
Diagnostics []Diagnostic `json:"diagnostics,omitempty"`
}
EvaluationResult extends a predicate match with structured diagnostics.
type Evaluator ¶
type Evaluator interface {
Evaluate(ctx context.Context, evaluation Evaluation) (bool, error)
}
Evaluator is the language extension point for pure predicates, including CEL and restricted Starlark, without exposing the script automation engine.
type ExecutionError ¶
ExecutionError contains SDK or subprocess error facts without exposing arguments.
type Explanation ¶
type Explanation struct {
Kind InputKind `json:"kind"`
Rule string `json:"rule,omitempty"`
Status string `json:"status"`
}
Explanation describes evaluation without exposing input values or expression errors.
type FactCollector ¶
FactCollector materializes requested external evidence before pure evaluation.
type FieldChange ¶
type FieldChange struct {
Identity ObjectIdentity `json:"identity"`
Path string `json:"path"`
Action ChangeAction `json:"action"`
BeforePresent bool `json:"before_present"`
AfterPresent bool `json:"after_present"`
Before json.RawMessage `json:"before,omitempty"`
After json.RawMessage `json:"after,omitempty"`
}
FieldChange uses a JSON Pointer path and explicit presence to distinguish a missing field from a field whose value is null. Collectors populate both flags.
type FileChange ¶
type FileChange struct {
Path string `json:"path"`
PreviousPath string `json:"previous_path,omitempty"`
Action ChangeAction `json:"action"`
Ambiguous bool `json:"ambiguous"`
}
FileChange records both paths for detected renames without assuming object identity.
type FileCheckOption ¶
type FileCheckOption func(*fileCheckContext)
FileCheckOption configures optional host evidence for file policies.
func WithFileEvidence ¶
func WithFileEvidence(engine *Engine, snapshot *CISnapshot) FileCheckOption
WithFileEvidence supplies an engine and CI snapshot without coupling policy to CI providers.
type FileResult ¶
type FileResult struct {
File string `json:"file"`
Decision Decision `json:"decision"`
Error string `json:"error,omitempty"`
}
FileResult identifies the document independently of its unwrapped input contents.
func CheckFiles ¶
func CheckFiles(ctx context.Context, bundle *Bundle, directory string, options ...FileCheckOption) ([]FileResult, error)
CheckFiles evaluates file policies without loading Atmos configuration or executing effects. It returns all collected outcomes, including denials and input errors, before failing the check.
type FileSelector ¶
type FileSelector struct {
Include []string `json:"include" yaml:"include"`
Exclude []string `json:"exclude,omitempty" yaml:"exclude"`
}
FileSelector selects literal YAML/JSON documents relative to the check root.
type Finding ¶
type Finding struct {
RuleID string `json:"rule_id"`
Status DecisionStatus `json:"status"`
Effects Effects `json:"effects"`
Error string `json:"error,omitempty"`
Diagnostics []Diagnostic `json:"diagnostics,omitempty"`
}
Finding preserves each rule's outcome and obligations, including on aggregate denial.
type FunctionInput ¶
type FunctionInput = guard.FunctionInput
FunctionInput is the common function collector contract.
type GitHubApprovalSpec ¶
type GitHubApprovalSpec struct {
Reviewers []string `json:"reviewers"`
Minimum int `json:"minimum"`
}
GitHubApprovalSpec uses explicitly maintained logins, not live organization teams.
func ParseGitHubApproval ¶
func ParseGitHubApproval(requirement ApprovalRequirement) (GitHubApprovalSpec, error)
ParseGitHubApproval validates the supported provider-native approval contract.
type GitHubReview ¶
type GitHubReview struct {
ID int64 `json:"id"`
Login string `json:"login"`
State string `json:"state"`
CommitID string `json:"commit_id"`
SubmittedAt time.Time `json:"submitted_at"`
}
GitHubReview retains the provider fields required for review verification.
type HookRequirement ¶
type HookRequirement struct {
Ref string `json:"ref" yaml:"ref"`
Event string `json:"event" yaml:"event"`
Required bool `json:"required" yaml:"required"`
RequireSuccess bool `json:"require_success" yaml:"require_success"`
}
HookRequirement references a trusted hook definition resolved by the caller. Required (must execute) and RequireSuccess (must succeed if executed) are distinct. Neither an allow decision nor a selected hook is evidence of hook completion.
type HostContextProvider ¶
type HostContextProvider struct{}
HostContextProvider samples the process and its current working filesystem.
func (HostContextProvider) Collect ¶
func (HostContextProvider) Collect(ctx context.Context) (*RuntimeContext, error)
Collect reads OS facts without invoking commands, templates, or Atmos authentication.
type HostFacts ¶
type HostFacts struct {
OS string `json:"os,omitempty"`
Arch string `json:"arch,omitempty"`
User UserFacts `json:"user"`
Memory MemoryFacts `json:"memory"`
Disk DiskFacts `json:"disk"`
}
HostFacts identifies the executable platform and sampled resource capacity.
type InputKind ¶
type InputKind string
InputKind identifies a policy input contract, not a component or CI provider.
const ( Validation InputKind = "validation" File InputKind = "file" Plan InputKind = "plan" TerraformPlan InputKind = "terraform.plan" Operation InputKind = "operation" Command InputKind = "command" ComponentCommand InputKind = "component.command" Auth InputKind = "auth" Function InputKind = "function" Source InputKind = "source" Plugin InputKind = "plugin" GitChange InputKind = "git.change" AtmosAffected InputKind = "atmos.affected" GitHubEvent InputKind = "github.event" GitHubApproval InputKind = "github.approval" )
Well-known input kind names. Collectors and command integration are separate.
func ErrorEvent ¶
ErrorEvent normalizes aliases to the same canonical names as lifecycle hooks. Custom providers use their registered component name and actual subcommand.
type InventorySnapshot ¶
type InventorySnapshot struct {
Stacks map[string]map[string]map[string]json.RawMessage
}
InventorySnapshot is a complete, unfiltered resolved stack inventory. Callers must establish collection completeness before constructing a policy input.
type JSONSchema ¶
type JSONSchema struct{}
JSONSchema evaluates schemas without filesystem or network access.
func (*JSONSchema) Evaluate ¶
func (j *JSONSchema) Evaluate(ctx context.Context, evaluation Evaluation) (bool, error)
Evaluate implements the boolean adapter interface; true means invalid input.
func (*JSONSchema) EvaluateDetailed ¶
func (j *JSONSchema) EvaluateDetailed(ctx context.Context, evaluation Evaluation) (EvaluationResult, error)
EvaluateDetailed distinguishes validation failures from broken schemas.
type MemoryFacts ¶
type MemoryFacts struct {
AvailableBytes *uint64 `json:"available_bytes"`
TotalBytes *uint64 `json:"total_bytes"`
Scope string `json:"scope,omitempty"`
}
MemoryFacts reports available host memory and a detected container ceiling.
type OPA ¶
type OPA struct{}
OPA accepts a boolean predicate or an array/set of violation strings or objects.
func (*OPA) EvaluateDetailed ¶
func (o *OPA) EvaluateDetailed(ctx context.Context, evaluation Evaluation) (EvaluationResult, error)
EvaluateDetailed preserves violation messages and structured Rego values.
type OPAConfig ¶
type OPAConfig struct {
Query string `json:"query"`
Modules map[string]string `json:"modules"`
RegoVersion int `json:"rego_version"`
}
OPAConfig contains materialized module source, never paths to load at evaluation time. Version 0 supports existing Rego; version 1 opts into Rego v1 syntax.
type ObjectChange ¶
type ObjectChange struct {
Identity ObjectIdentity `json:"identity"`
Action ChangeAction `json:"action"`
Before json.RawMessage `json:"before,omitempty"`
After json.RawMessage `json:"after,omitempty"`
Reasons []string `json:"reasons"`
Ambiguous bool `json:"ambiguous"`
}
ObjectChange holds separate before/after objects; selectors must not merge them. Absent before/after fields differ from explicit JSON null values.
type ObjectIdentity ¶
type ObjectIdentity struct {
Name string `json:"name"`
ComponentType string `json:"component_type,omitempty"`
Stack string `json:"stack,omitempty"`
}
ObjectIdentity distinguishes shared components from configured instances. An instance uses Stack + ComponentType + Name; a shared component omits Stack.
type OperationInput ¶
type OperationInput struct {
Event string `json:"event"`
ComponentType string `json:"component_type"`
Command string `json:"command"`
Component string `json:"component"`
Stack string `json:"stack"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
DryRun bool `json:"dry_run"`
}
OperationInput describes a concrete lifecycle event.
type PluginInput ¶
type PluginInput = guard.PluginInput
PluginInput describes a plugin source or inspected executable package.
type Provenance ¶
type Provenance struct {
Source string `json:"source"`
CollectedAt time.Time `json:"collected_at"`
Revision string `json:"revision,omitempty"`
}
Provenance describes collection, not proof that the source was trusted.
type Request ¶
type Request struct {
Context *RuntimeContext `json:"context,omitempty"`
Subject *Subject `json:"subject,omitempty"`
Kind InputKind `json:"kind"`
Input json.RawMessage `json:"input"`
CI *CISnapshot `json:"ci,omitempty"`
Revisions Revisions `json:"revisions"`
File string `json:"file,omitempty"`
}
Request contains one explicitly selected input kind. File inputs may be any JSON value; all other inputs must be JSON objects. No input kind implicitly triggers collection of another kind (including affected).
type Revisions ¶
type Revisions struct {
Governing string `json:"governing"`
Base string `json:"base"`
Head string `json:"head"`
}
Revisions keeps the governing policy revision separate from the comparison base. Values are supplied by a trusted caller; the engine does not verify Git objects.
type Rule ¶
type Rule struct {
Checks map[string]ContextCheck `json:"checks,omitempty"`
AllowedRoots []string `json:"allowed_roots,omitempty"`
Match *Selector `json:"match,omitempty"`
ID string `json:"id"`
Description string `json:"description,omitempty"`
On InputKind `json:"on"`
Events []InputKind `json:"events,omitempty"`
Engine string `json:"engine"`
Expression string `json:"expression"`
Parameters json.RawMessage `json:"parameters,omitempty"`
RequiredCI []CIRequirement `json:"required_ci,omitempty"`
Effects Effects `json:"effects"`
OPA *OPAConfig `json:"opa,omitempty"`
Schema *SchemaConfig `json:"schema,omitempty"`
Files *FileSelector `json:"files,omitempty"`
}
Rule is an already resolved definition, not a policy manifest or trust assertion. A true predicate selects its effects; false means not applicable, never denial.
func LoadPlanDirectory ¶
LoadPlanDirectory loads plan manifests and their local evaluator resources. An explicit directory is required. No discovery, imports, templates or trust claims are made. Unsupported fields/capabilities are errors, not ignored declarations.
func (*Rule) MatchesKind ¶
MatchesKind selects a rule once even when several of its event selectors match.
type RuntimeContext ¶
type RuntimeContext struct {
Env map[string]string `json:"env"`
Atmos AtmosFacts `json:"atmos"`
Runtime HostFacts `json:"runtime"`
Time ClockFacts `json:"time"`
}
RuntimeContext is host-owned evidence, separate from the document being validated. Unknown measurements are null, never fabricated zeroes. Unavailable host strings are omitted so partial fixtures cannot manufacture present-but-empty facts. Environment values retain explicitly empty strings. Context can contain secrets.
type SchemaConfig ¶
type SchemaConfig struct {
Target string `json:"target,omitempty"`
Entry string `json:"entry"`
Resources map[string]json.RawMessage `json:"resources"`
}
SchemaConfig holds the entrypoint URI and all materialized local references.
type Selector ¶
type Selector struct {
Tags []string `json:"tags,omitempty" yaml:"tags"`
TagMode tags.TagMode `json:"tag_mode,omitempty" yaml:"-"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels"`
Components []string `json:"components,omitempty" yaml:"components"`
Stacks []string `json:"stacks,omitempty" yaml:"stacks"`
ComponentTypes []string `json:"component_types,omitempty" yaml:"component_types"`
}
Selector attaches a rule to instances. Fields combine with AND; label entries all match. Multiple tags use the same any/all convention as component selection.
type SourceInput ¶
type SourceInput = guard.SourceInput
SourceInput is the destination collector contract. Rules with allowed_roots also receive within_allowed_roots.
type Starlark ¶
type Starlark struct{}
Starlark evaluates boolean function bodies over detached, read-only JSON data. It has no automation host, module loader, filesystem, network, or logging API.
type Subject ¶
type Subject struct {
ObjectIdentity
Metadata SubjectMetadata `json:"metadata"`
// TemplateLeft identifies unresolved metadata under a configured delimiter.
TemplateLeft string `json:"template_left,omitempty"`
}
Subject identifies one instance and its resolved, inherited selector metadata. A nil subject means unavailable, not an instance with no labels.
func NewSubject ¶
func NewSubject(identity ObjectIdentity, metadata any, delimiters ...string) (*Subject, error)
NewSubject copies already resolved metadata without evaluating templates or functions. Malformed and unresolved metadata must not silently detach a policy.
type SubjectMetadata ¶
type SubjectMetadata struct {
Tags []string `json:"tags"`
Labels map[string]string `json:"labels"`
}
SubjectMetadata contains only data used for attachment, never executable configuration.
type TestCase ¶
type TestCase struct {
Name string `json:"name"`
Request Request `json:"request"`
Status DecisionStatus `json:"status"`
Error string `json:"error,omitempty"`
Hooks []HookRequirement `json:"hooks,omitempty"`
Approvals []ApprovalRequirement `json:"approvals,omitempty"`
}
TestCase is the offline fixture format shared with the distributed policy catalog.
type TestResult ¶
type TestResult struct {
Name string `json:"name"`
Passed bool `json:"passed"`
Expected DecisionStatus `json:"expected"`
Actual DecisionStatus `json:"actual"`
}
TestResult reports observable fixture outcomes without retaining sensitive inputs.
type UserFacts ¶
type UserFacts struct {
UID *int `json:"uid"`
GID *int `json:"gid"`
Username *string `json:"username"`
}
UserFacts uses effective process IDs, not environment-supplied identity.
type Violation ¶
type Violation struct {
RuleID string
Reason string
Diagnostics []Diagnostic
}
Violation identifies one rule that denied an execution, so reporters such as CI annotations can name the rule without parsing the rendered explanation. Reason is the author's static Markdown and is empty when the rule has none. Diagnostics may include input values and must not be automatically published by reporters.
func Violations ¶
Violations returns the rules that denied err, in decision order, or nil when err is not a policy denial. Wrapping err does not hide its violations.
Source Files
¶
- affected.go
- agents.go
- auth.go
- cel.go
- ci.go
- context_checks.go
- context_ci.go
- doc.go
- engine.go
- error_events.go
- explain.go
- files.go
- github_approvals.go
- input_schema.go
- inspect.go
- inventory.go
- json.go
- jsonschema.go
- opa.go
- plan_directory.go
- resources.go
- runtime_context.go
- runtime_memory.go
- selector.go
- selector_yaml.go
- source.go
- starlark.go
- terraform_plan.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admission enforces policy before execution, outside pure evaluators.
|
Package admission enforces policy before execution, outside pure evaluators. |
|
Package guard supplies dependency-free pre-I/O hooks to configuration loaders.
|
Package guard supplies dependency-free pre-I/O hooks to configuration loaders. |
|
Package planfile binds policy evaluation to saved Terraform artifacts.
|
Package planfile binds policy evaluation to saved Terraform artifacts. |
|
Package recovery executes retry obligations at individual component operation boundaries.
|
Package recovery executes retry obligations at individual component operation boundaries. |
|
recoverytest
Package recoverytest installs isolated, pinned retry policies for executor tests.
|
Package recoverytest installs isolated, pinned retry policies for executor tests. |