policy

package
v0.0.0-...-230ac96 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 16 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 implements the AgentMon database-access policy evaluator per docs/agentmon-db-access-spec.md §9–§10. The package is platform-agnostic and produces only data types and pure functions; events, approvals, and wire I/O belong to later plans (Plan 04+).

Index

Constants

This section is empty.

Variables

View Source
var ErrApproverNotConfigured = errors.New("policy: approver not configured")

ErrApproverNotConfigured is reserved for callers that require an explicit approver. The proxy default is NopApprover{}.

Functions

func Decode

func Decode(p *rootpolicy.Policy) (*RuleSet, []Warning, error)

Decode turns a parsed *internal/policy.Policy into a fully validated and compiled *RuleSet. It performs three phases per the design doc §5:

A. Decode each yaml.Node (db_services, database_rules,
   database_connection_rules) into typed shapes with KnownFields(true).
B. Validate the typed shapes (§9.4 errors + warnings).
C. Compile validated rules into the evaluator-ready *RuleSet.

Decode returns (rs, warnings, nil) on success. On error, warnings collected up to the point of failure are returned alongside the error.

Types

type ApprovalRequest

type ApprovalRequest struct {
	Timeout                  time.Duration
	ContributingApproveRules []string
}

ApprovalRequest carries data Plan 04 needs to spin up the approval flow. Plan 02 produces it but does not act on it.

type Approver

type Approver interface {
	Decide(ctx context.Context, cs effects.ClassifiedStatement, timeout time.Duration) (approved bool, err error)
}

Approver decides whether a statement awaiting approval should run.

type ConnectionInfo

type ConnectionInfo struct {
	Service         ServiceID
	MatchKind       ConnectionMatchKind
	DBUser          string
	Database        string
	ApplicationName string
	ClientIdentity  string
}

ConnectionInfo is the input to EvaluateConnection. Plan 04 populates it from StartupMessage parameters (or sentinel zero values under passthrough TLS).

type ConnectionMatchKind

type ConnectionMatchKind uint8

ConnectionMatchKind is the connection rule's match_kind field, used by EvaluateConnection.

const (
	MatchConnect ConnectionMatchKind = iota
	MatchCancel
	MatchReplication
)

type ConnectionRule

type ConnectionRule struct {
	Name            string        `yaml:"name"`
	DBService       string        `yaml:"db_service,omitempty"`
	MatchKind       string        `yaml:"match_kind,omitempty"`
	DBUser          []string      `yaml:"db_user,omitempty"`
	Database        string        `yaml:"database,omitempty"`
	ApplicationName string        `yaml:"application_name,omitempty"`
	ClientIdentity  string        `yaml:"client_identity,omitempty"`
	Decision        string        `yaml:"decision"`
	Message         string        `yaml:"message,omitempty"`
	Timeout         time.Duration `yaml:"timeout,omitempty"`
}

ConnectionRule is the on-disk shape of a database_connection_rules entry per §9.3.

type DBService

type DBService struct {
	Name                      string `yaml:"-"` // populated from map key
	Family                    string `yaml:"family"`
	Dialect                   string `yaml:"dialect"`
	Upstream                  string `yaml:"upstream"`
	TLSMode                   string `yaml:"tls_mode"`
	AllowFunctionCallProtocol bool   `yaml:"allow_function_call_protocol,omitempty"`
	AllowGSSEncryption        bool   `yaml:"allow_gss_encryption,omitempty"`
	TrustedNetwork            bool   `yaml:"trusted_network,omitempty"`
}

DBService is the on-disk shape of a db_services entry per §9.1.

type Decision

type Decision struct {
	Verb                   DecisionVerb
	RuleKind               RuleKind
	RuleName               string
	MatchingEffectIndex    int           // -1 for connection-level decisions
	MatchingEffectGroup    effects.Group // GroupUnknown for connection-level decisions
	Reason                 string
	ContributingAuditRules []string // populated only when Verb == VerbApprove
	Approval               *ApprovalRequest
	Redirect               *RedirectDecision
}

Decision is the output of Evaluate / EvaluateConnection.

Implicit deny (no rule covers an object in some effect) is encoded as Verb == VerbDeny with RuleName == "" and Reason == "no rule covers ..." — this matches the §8 DBEvent wire schema (decision.verb has only four values) while still letting tests assert on the distinction via RuleName.

func Evaluate

func Evaluate(stmt effects.ClassifiedStatement, rs *RuleSet, svc ServiceID) Decision

Evaluate applies the statement-rule policy to a classified statement per spec §10.2. Pure function; safe to call concurrently against the same *RuleSet (RuleSet is immutable after Decode).

func EvaluateConnection

func EvaluateConnection(info ConnectionInfo, rs *RuleSet) Decision

EvaluateConnection applies connection-rule policy to a candidate connection. Returns implicit deny if no rule matches.

type DecisionVerb

type DecisionVerb uint8

DecisionVerb mirrors the §10.1 verbs. Implicit deny is *not* a separate verb; it is encoded as Verb == VerbDeny with RuleName == "" (see §7 of the design doc and Decision below).

The numeric ordering (Allow < Audit < Redirect < Approve < Deny) encodes restrictiveness — the evaluator's hot path uses integer comparison (max(verb, ...)) to fold per-effect verdicts. Do not reorder these values.

const (
	VerbAllow DecisionVerb = iota
	VerbAudit
	VerbRedirect
	VerbApprove
	VerbDeny
)

func (DecisionVerb) String

func (v DecisionVerb) String() string

type EffectExplanation

type EffectExplanation struct {
	Index         int
	Group         effects.Group
	Subtype       effects.Subtype
	Resolution    effects.Resolution
	Coverage      []ObjectCoverage
	CoveringRules []RuleMatch
	DenyRules     []RuleMatch
}

type NopApprover

type NopApprover struct{}

NopApprover is the default. It blocks until context cancellation or timeout, then denies by returning approved=false.

func (NopApprover) Decide

type ObjectCoverage

type ObjectCoverage struct {
	Index           int
	Object          effects.ObjectRef
	ResolvedObject  *effects.ResolvedObjectRef
	Covered         bool
	CoveringRules   []RuleMatch
	UncoveredReason string
}

type RedactionConfig

type RedactionConfig struct {
	LogStatements            RedactionTier
	ApprovalStatementPreview RedactionTier
	ApprovalStatementChars   int

	// EscalateUnknownFunctions reflects policies.db.escalate_unknown_functions.
	// When true, classifier reclassifies SELECT calling a function NOT in
	// SafeFunctionAllowlist as procedural rather than read.
	EscalateUnknownFunctions bool

	// SafeFunctionAllowlist is the lowercase canonical function names that
	// stay classified as `read` when EscalateUnknownFunctions is on. When
	// the config omits the key but escalate is on, Decode populates this
	// with classify/postgres.DefaultSafeFunctionAllowlist() keys.
	SafeFunctionAllowlist []string
}

RedactionConfig is the policies.db block. See §10.3.

Defaults applied by Decode when a field is missing:

LogStatements:            RedactParametersRedacted
ApprovalStatementPreview: RedactParametersRedacted (named "redacted" in YAML)
ApprovalStatementChars:   200

type RedactionTier

type RedactionTier uint8

RedactionTier is the statement-text redaction tier per §10.3. It is locally defined (not imported from internal/db/events) so that internal/db/events can later import this package without a cycle.

const (
	RedactNone RedactionTier = iota
	RedactParametersRedacted
	RedactFull
)

func ParseRedactionTier

func ParseRedactionTier(s string) (RedactionTier, bool)

ParseRedactionTier parses the canonical lowercase tier name. Empty input returns ok=false (callers may want to apply a default at a higher level).

func (RedactionTier) String

func (r RedactionTier) String() string

type RedirectAction

type RedirectAction struct {
	Relation string `yaml:"relation"`
}

RedirectAction is the on-disk action metadata for statement rules with decision: redirect.

type RedirectDecision

type RedirectDecision struct {
	SourceRelation string
	TargetRelation string
}

RedirectDecision is the evaluator output metadata for redirect decisions.

type RuleKind

type RuleKind uint8

RuleKind labels which rule family produced a Decision; surfaced to DBEvent as decision.rule_kind in §8.

const (
	RuleKindStatement RuleKind = iota
	RuleKindConnection
	RuleKindCancel
)

func (RuleKind) String

func (k RuleKind) String() string

type RuleMatch

type RuleMatch struct {
	RuleName string
	Verb     DecisionVerb
	Selector string
}

type RuleSet

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

RuleSet is the immutable, evaluator-ready policy. Build via Decode. Internals are private; callers consume via Evaluate / EvaluateConnection / Redaction / Service.

func MustLoadSample

func MustLoadSample() *RuleSet

MustLoadSample returns a *RuleSet built from the embedded sample policy (testdata/sample-policy.yaml). Panics on any error — the file is part of the package and a parse failure indicates a development-time bug, not a runtime condition. Plan 03's golden corpus also calls this.

func (*RuleSet) AllServices

func (rs *RuleSet) AllServices() []DBService

AllServices returns a copy of every declared db_service. Order is not guaranteed; callers that need stable ordering should sort by Name. Returns nil when rs is nil.

func (*RuleSet) AllStatementRules

func (rs *RuleSet) AllStatementRules() []StatementRule

AllStatementRules returns a copy of every parsed StatementRule. Order is preserved from the source YAML. Returns nil when rs is nil. Used by the Extended Query state machine to look up the deny_mode_in_tx field for a matched rule.

func (*RuleSet) Redaction

func (rs *RuleSet) Redaction() RedactionConfig

Redaction returns the policies.db block configuration. Returns the zero value when rs is nil so startup code holding a not-yet-loaded *RuleSet does not panic.

func (*RuleSet) Service

func (rs *RuleSet) Service(id ServiceID) (DBService, bool)

Service returns the named db_service definition, if present.

func (*RuleSet) Unavoidability

func (rs *RuleSet) Unavoidability() service.Unavoidability

Unavoidability returns the policies.db.unavoidability mode. Returns UnavoidabilityOff when rs is nil so startup code holding a not-yet-loaded *RuleSet does not panic.

func (*RuleSet) UsesCanonicalSelectors

func (rs *RuleSet) UsesCanonicalSelectors(svc ServiceID) bool

UsesCanonicalSelectors reports whether any statement rule applicable to svc constrains catalog-backed relation or function selectors.

type ServiceID

type ServiceID string

ServiceID is the operator-supplied identifier of a db_service.

type StatementExplanation

type StatementExplanation struct {
	Decision        Decision
	ApplicableRules []string
	Effects         []EffectExplanation
}

type StatementRule

type StatementRule struct {
	Name                        string          `yaml:"name"`
	DBService                   string          `yaml:"db_service,omitempty"`
	DBFamily                    string          `yaml:"db_family,omitempty"`
	DBDialect                   string          `yaml:"db_dialect,omitempty"`
	Schemas                     []string        `yaml:"schemas,omitempty"`
	Objects                     []string        `yaml:"objects,omitempty"`
	Relations                   []string        `yaml:"relations,omitempty"`
	Functions                   []string        `yaml:"functions,omitempty"`
	Operations                  []string        `yaml:"operations"`
	Subtypes                    []string        `yaml:"subtypes,omitempty"`
	MatchObjectResolution       string          `yaml:"match_object_resolution,omitempty"`
	RequireWhere                bool            `yaml:"require_where,omitempty"`
	Decision                    string          `yaml:"decision"`
	Message                     string          `yaml:"message,omitempty"`
	Timeout                     time.Duration   `yaml:"timeout,omitempty"`
	Redirect                    *RedirectAction `yaml:"redirect,omitempty"`
	AcknowledgeAuditOnDangerous bool            `yaml:"acknowledge_audit_on_dangerous,omitempty"`
	DenyModeInTx                string          `yaml:"deny_mode_in_tx,omitempty"`
}

StatementRule is the on-disk shape of a database_rules entry per §9.2.

type Warning

type Warning struct {
	Rule    string // rule name, "" for service-level
	Field   string // YAML field, e.g. "decision"
	Code    string // stable identifier for callers / tests
	Message string
	Line    int // yaml.v3 node Line, for IDE-friendly output
}

Warning is a non-fatal issue surfaced by Decode. Errors abort load; warnings accumulate so operators can fix them at leisure.

Jump to

Keyboard shortcuts

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