policy

package
v0.16.7 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package policy compiles bounded application policies independently of alerts.

Index

Constants

View Source
const (
	MaxBundleBytes     = 1 << 20
	MaxRules           = 1024
	MaxExpressionBytes = 4096
	MaxEventBytes      = 2 << 20
	MaxGroups          = 4096
)
View Source
const (
	// Sliding event windows retain the nearest Count timestamps; distinct windows
	// retain every live value up to MaxDistinct and reject overflow without eviction.
	MaxMatches      = 10000
	MaxDistinct     = 256
	MaxStateEntries = 131072
	MaxStateBytes   = 64 << 20
)
View Source
const MaxCompiledWork uint64 = 65536
View Source
const MaxEffectTTL = 15 * time.Minute
View Source
const MaxEffects = 8
View Source
const MaxEvaluationWork uint64 = 128 << 20
View Source
const MaxSimulationWork uint64 = 1 << 30
View Source
const MaxSnapshotBytes = 8 << 20

Variables

View Source
var ErrMissingStateField = errors.New("policy: state field unavailable")
View Source
var ErrSnapshot = errors.New("policy: invalid state snapshot")
View Source
var ErrStateCapacity = errors.New("policy: threshold state capacity exhausted")
View Source
var ErrStateClock = errors.New("policy: state clock moved backwards")
View Source
var ErrWorkBudget = errors.New("policy: evaluation work budget exceeded")

Functions

func EventFlow

func EventFlow(e Event) (enforcer.Flow, error)

func IntentID

func IntentID(i Intent) string

IntentID excludes timestamps so repeated matches do not renew an active lease.

func ValidateEvent

func ValidateEvent(e Event) error

ValidateEvent checks the bounded typed environment without advancing state.

Types

type Bundle

type Bundle struct {
	Version  string         `json:"version" yaml:"version"`
	ID       string         `json:"id" yaml:"id"`
	Mode     string         `json:"mode" yaml:"mode"`
	Default  string         `json:"default" yaml:"default"`
	Rules    []Rule         `json:"rules" yaml:"rules"`
	Defaults *PhaseDefaults `json:"defaults,omitempty" yaml:"defaults,omitempty"`
}

func Parse

func Parse(data []byte) (Bundle, error)

Parse accepts exactly one YAML or JSON object, rejecting unknown and duplicate keys at every schema level. YAML mappings are decoded lazily so aliases cannot expand arbitrary object graphs. Compile performs semantic validation.

type CompileOptions

type CompileOptions struct{ AllowEffects bool }

CompileOptions is trusted host admission, never parsed from a policy bundle.

type Compiled

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

Compiled owns an immutable, normalized bundle and revision-local counter state. It is safe for concurrent Evaluate calls. Create a new revision with Compile. Separate Compiled instances never share counters, even with identical revisions.

func Compile

func Compile(b Bundle) (*Compiled, error)

Compile validates versions 1/v1/netcap-policy/v1 and requires explicit mode/default. Expressions support comparisons, boolean/string operators, literal RE2 patterns and arrays, header indexing, and len/lower/upper/trim; iteration and dynamic calls are denied.

func CompileWithOptions

func CompileWithOptions(b Bundle, options CompileOptions) (*Compiled, error)

CompileWithOptions admits response effects only when the host explicitly opts in.

func (*Compiled) Bundle

func (c *Compiled) Bundle() Bundle

Bundle returns a deep copy; changing it cannot alter the compiled policy.

func (*Compiled) Evaluate

func (c *Compiled) Evaluate(e Event) (Decision, error)

Evaluate counts every matching enabled rule in the event's phase, then picks highest priority, deny before allow on ties, then lexicographically first ID. Default applies to both phases unless Defaults overrides it. Errors must be handled by the caller's fail-closed policy; they are never allows.

func (*Compiled) EvaluateAt

func (c *Compiled) EvaluateAt(ctx context.Context, e Event, now time.Time) (Decision, error)

EvaluateAt is for trusted authoritative processors. Event data never selects the clock. Callers must serialize import/evaluate/export as one transaction.

func (*Compiled) Explain

func (c *Compiled) Explain(e Event) (Explanation, error)

Explain evaluates once, advancing counters just like Evaluate. Its output includes no request data, header values, body, or expression source.

func (*Compiled) ExportState

func (c *Compiled) ExportState(ctx context.Context) ([]byte, error)

ExportState emits a versioned, deterministic binary snapshot bound to Revision. Only rule labels, opaque digests and timestamps are stored, never event values. The checksum detects corruption; private storage, not this checksum, authorizes state. Snapshots are private processor state, not metrics or untrusted client input.

func (*Compiled) Fork

func (c *Compiled) Fork() *Compiled

Fork shares immutable programs and starts with empty revision-local state.

func (*Compiled) ImportState

func (c *Compiled) ImportState(ctx context.Context, raw []byte) error

ImportState validates revision, descriptors, times, keys and allocation budgets before atomically replacing state. It refuses an older watermark on a live instance. Restore into a fresh Fork inside the authoritative DB transaction.

func (*Compiled) Maintain

func (c *Compiled) Maintain() (StateStats, error)

Maintain expires idle state without requiring matching traffic. The host may call it periodically; Compiled starts no goroutines. Sliding lower boundaries are exclusive. Fixed distinct sets expire together at the original deadline.

func (*Compiled) RequiresBody

func (c *Compiled) RequiresBody(phase string) bool

RequiresBody reports syntactic Body dependencies of enabled rules and sequence steps in the exact phase, regardless of priority, action or constant branches. Empty/unknown phases and nil receivers return false.

func (*Compiled) Revision

func (c *Compiled) Revision() string

func (*Compiled) Simulate

func (c *Compiled) Simulate(events []Event) ([]Decision, error)

Simulate starts with fresh state and never changes live threshold counters. Events are evaluated in slice order at one frozen instant (no elapsed time).

func (*Compiled) StateDeadline

func (c *Compiled) StateDeadline() time.Time

StateDeadline is the latest live group expiry, or the last evaluation watermark for stateless policies. It permits reclamation without forgetting a live group.

func (*Compiled) StateProgramBytes

func (c *Compiled) StateProgramBytes() int

StateProgramBytes is the conservative immutable-program reservation used by authoritative state/cache admission, including source copies and VM work.

func (*Compiled) StateStats

func (c *Compiled) StateStats() StateStats

func (*Compiled) StateWatermark

func (c *Compiled) StateWatermark() time.Time

type DNSEvent

type DNSEvent struct {
	Name string `json:"name" yaml:"name"`
	Type int    `json:"type" yaml:"type"`
}

type Decision

type Decision struct {
	Effects  []Intent `json:"effects,omitempty"`
	Verdict  string   `json:"verdict"`
	Status   int      `json:"status"`
	RuleID   string   `json:"rule_id"`
	Revision string   `json:"revision"`
	Monitor  bool     `json:"monitor"`
}

type Effect

type Effect struct {
	Profile  string `json:"profile,omitempty" yaml:"profile,omitempty"`
	Kind     string `json:"kind" yaml:"kind"`
	Duration string `json:"duration" yaml:"duration"`
	Target   string `json:"target" yaml:"target"`
	Scope    string `json:"scope" yaml:"scope"`
}

type Event

type Event struct {
	Network NetworkEvent `json:"network" yaml:"network"`
	TLS     TLSEvent     `json:"tls" yaml:"tls"`
	// Attributes is the protocol adapter interface: named scalar strings only.
	// Fields holds native audit-record scalar strings; RecordType names its schema.
	Attributes map[string]string   `json:"attributes,omitempty" yaml:"attributes,omitempty"`
	RecordType string              `json:"record_type,omitempty" yaml:"record_type,omitempty"`
	Fields     map[string]string   `json:"fields,omitempty" yaml:"fields,omitempty"`
	Protocol   string              `json:"protocol" yaml:"protocol"`
	Modbus     ModbusEvent         `json:"modbus" yaml:"modbus"`
	DNS        DNSEvent            `json:"dns" yaml:"dns"`
	Method     string              `json:"method" yaml:"method"`
	Host       string              `json:"host" yaml:"host"`
	Path       string              `json:"path" yaml:"path"`
	RawQuery   string              `json:"raw_query" yaml:"raw_query"`
	ClientIP   string              `json:"client_ip" yaml:"client_ip"`
	Body       string              `json:"body" yaml:"body"`
	Headers    map[string][]string `json:"headers" yaml:"headers"`
	Status     int                 `json:"status" yaml:"status"`
	Phase      string              `json:"phase" yaml:"phase"`
}

Event is also the typed expression environment; header keys are canonical HTTP names. Callers must not mutate Headers, Attributes or Fields during evaluation.

type Explanation

type Explanation struct {
	Decision Decision `json:"decision"`
	Reason   string   `json:"reason"`
}

Explanation contains policy metadata only, never event values or expressions.

type FieldInfo

type FieldInfo struct{ Name, Type string }

func DiscoverFields

func DiscoverFields() []FieldInfo

DiscoverFields returns expression names, including map element types. Dynamic keys are adapter-defined; missing map keys evaluate as the empty string.

type Intent

type Intent struct {
	Profile   string        `json:"profile,omitempty"`
	Flow      enforcer.Flow `json:"flow,omitempty"`
	ID        string        `json:"id"`
	Kind      string        `json:"kind"`
	Target    string        `json:"target"`
	Source    string        `json:"source"`
	Scope     string        `json:"scope"`
	Revision  string        `json:"revision"`
	RuleID    string        `json:"rule_id"`
	TTL       time.Duration `json:"ttl"`
	IssuedAt  time.Time     `json:"issued_at"`
	ExpiresAt time.Time     `json:"expires_at"`
}

Intent is inert data. Only a trusted-source broker may dispatch it.

type ModbusEvent

type ModbusEvent struct {
	Function       int  `json:"function" yaml:"function"`
	UnitID         int  `json:"unit_id" yaml:"unit_id"`
	Address        int  `json:"address" yaml:"address"`
	Quantity       int  `json:"quantity" yaml:"quantity"`
	EndAddress     int  `json:"end_address" yaml:"end_address"`
	IsWrite        bool `json:"is_write" yaml:"is_write"`
	ReadAddress    int  `json:"read_address" yaml:"read_address"`
	ReadQuantity   int  `json:"read_quantity" yaml:"read_quantity"`
	ReadEndAddress int  `json:"read_end_address" yaml:"read_end_address"`
}

ModbusEvent describes validated request ranges, including both sides of FC23. Address/Quantity is the write range for writes and the read range otherwise.

type NetworkEvent

type NetworkEvent struct {
	SrcIP     string `json:"src_ip" yaml:"src_ip"`
	DstIP     string `json:"dst_ip" yaml:"dst_ip"`
	SrcPort   int    `json:"src_port" yaml:"src_port"`
	DstPort   int    `json:"dst_port" yaml:"dst_port"`
	Transport string `json:"transport" yaml:"transport"`
	IPVersion int    `json:"ip_version" yaml:"ip_version"`
	TCPFlags  int    `json:"tcp_flags" yaml:"tcp_flags"`
	Direction string `json:"direction" yaml:"direction"`
}

type PhaseDefaults

type PhaseDefaults struct {
	Request  string `json:"request,omitempty" yaml:"request,omitempty"`
	Response string `json:"response,omitempty" yaml:"response,omitempty"`
}

PhaseDefaults overrides Default for either phase; empty fields inherit Default.

type RecordSchema

type RecordSchema struct {
	RecordType string
	Fields     map[string]ScalarType
}

func (RecordSchema) Validate

func (s RecordSchema) Validate(e Event) error

Validate checks native record mappings before policy evaluation. Missing fields are permitted (partial records); unknown fields and noncanonical scalars fail. Expressions access Fields["name"] as strings, including numeric encodings.

type Rule

type Rule struct {
	ID         string     `json:"id" yaml:"id"`
	Phase      string     `json:"phase" yaml:"phase"`
	Expression string     `json:"expression" yaml:"expression"`
	Action     string     `json:"action" yaml:"action"`
	Status     int        `json:"status" yaml:"status"`
	Priority   int        `json:"priority" yaml:"priority"`
	Enabled    *bool      `json:"enabled,omitempty" yaml:"enabled,omitempty"`
	Threshold  *Threshold `json:"threshold,omitempty" yaml:"threshold,omitempty"`
	Sequence   *Sequence  `json:"sequence,omitempty" yaml:"sequence,omitempty"`
	Effects    []Effect   `json:"effects,omitempty" yaml:"effects,omitempty"`
}

type ScalarType

type ScalarType string

ScalarType describes a native audit field's textual encoding. The event stays scalar-only; schemas are adapter-owned and never execute legacy rule code.

const (
	StringField ScalarType = "string"
	IntField    ScalarType = "int"
	BoolField   ScalarType = "bool"
)

type Sequence

type Sequence struct {
	Name          string   `json:"name" yaml:"name"`
	Steps         []string `json:"steps" yaml:"steps"`
	Window        string   `json:"window" yaml:"window"`
	GroupBy       string   `json:"group_by" yaml:"group_by"`
	GroupByFields []string `json:"group_by_fields,omitempty" yaml:"group_by_fields,omitempty"`
}

Sequence matches 2..16 ordered step expressions within one total fixed window. One event advances at most one step. Unrelated events are ignored; a first-step match restarts an incomplete sequence if it does not match the expected step. Expression, when present, filters all steps. Threshold counts completions. Steps can span protocols and native audit records within one phase; use a shared source/tenant grouping tuple rather than grouping by Protocol.

type StateStats

type StateStats struct {
	Groups         int `json:"groups"`
	Entries        int `json:"entries"`
	AccountedBytes int `json:"accounted_bytes"`
}

StateStats contains counts only, never grouping values, hashes or timestamps.

type TLSEvent

type TLSEvent struct {
	ServerName string `json:"server_name" yaml:"server_name"`
	ALPN       string `json:"alpn" yaml:"alpn"`
	JA4        string `json:"ja4" yaml:"ja4"`
	Encrypted  bool   `json:"encrypted" yaml:"encrypted"`
}

type Threshold

type Threshold struct {
	Count         int      `json:"count" yaml:"count"`
	Window        string   `json:"window" yaml:"window"`
	GroupBy       string   `json:"group_by" yaml:"group_by"`
	Mode          string   `json:"mode,omitempty" yaml:"mode,omitempty"`
	Distinct      string   `json:"distinct,omitempty" yaml:"distinct,omitempty"`
	GroupByFields []string `json:"group_by_fields,omitempty" yaml:"group_by_fields,omitempty"`
}

Threshold matches while Count is reached. Mode defaults to fixed (first-match window); sliding uses (now-Window, now] on the evaluator's clock. Distinct selects a scalar field instead of counting events. GroupByFields is an ordered tuple, exclusive with GroupBy. Static Attributes.key/Fields.key references are allowed; Body is not. Missing map fields and exhausted capacity return errors, never silently evict live state.

Jump to

Keyboard shortcuts

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