Documentation
¶
Overview ¶
Package policy compiles bounded application policies independently of alerts.
Index ¶
- Constants
- Variables
- func EventFlow(e Event) (enforcer.Flow, error)
- func IntentID(i Intent) string
- func ValidateEvent(e Event) error
- type Bundle
- type CompileOptions
- type Compiled
- func (c *Compiled) Bundle() Bundle
- func (c *Compiled) Evaluate(e Event) (Decision, error)
- func (c *Compiled) EvaluateAt(ctx context.Context, e Event, now time.Time) (Decision, error)
- func (c *Compiled) Explain(e Event) (Explanation, error)
- func (c *Compiled) ExportState(ctx context.Context) ([]byte, error)
- func (c *Compiled) Fork() *Compiled
- func (c *Compiled) ImportState(ctx context.Context, raw []byte) error
- func (c *Compiled) Maintain() (StateStats, error)
- func (c *Compiled) RequiresBody(phase string) bool
- func (c *Compiled) Revision() string
- func (c *Compiled) Simulate(events []Event) ([]Decision, error)
- func (c *Compiled) StateDeadline() time.Time
- func (c *Compiled) StateProgramBytes() int
- func (c *Compiled) StateStats() StateStats
- func (c *Compiled) StateWatermark() time.Time
- type DNSEvent
- type Decision
- type Effect
- type Event
- type Explanation
- type FieldInfo
- type Intent
- type ModbusEvent
- type NetworkEvent
- type PhaseDefaults
- type RecordSchema
- type Rule
- type ScalarType
- type Sequence
- type StateStats
- type TLSEvent
- type Threshold
Constants ¶
const ( MaxBundleBytes = 1 << 20 MaxRules = 1024 MaxExpressionBytes = 4096 MaxEventBytes = 2 << 20 MaxGroups = 4096 )
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 )
const MaxCompiledWork uint64 = 65536
const MaxEffectTTL = 15 * time.Minute
const MaxEffects = 8
const MaxEvaluationWork uint64 = 128 << 20
const MaxSimulationWork uint64 = 1 << 30
const MaxSnapshotBytes = 8 << 20
Variables ¶
var ErrMissingStateField = errors.New("policy: state field unavailable")
var ErrSnapshot = errors.New("policy: invalid state snapshot")
var ErrStateCapacity = errors.New("policy: threshold state capacity exhausted")
var ErrStateClock = errors.New("policy: state clock moved backwards")
var ErrWorkBudget = errors.New("policy: evaluation work budget exceeded")
Functions ¶
func ValidateEvent ¶
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"`
}
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 ¶
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) Evaluate ¶
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 ¶
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 ¶
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) ImportState ¶
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 ¶
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) Simulate ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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.