Documentation
¶
Index ¶
- Constants
- Variables
- func BuildEnv(pol ResolvedEnvPolicy, baseEnv []string, addKeys map[string]string) ([]string, error)
- func DefaultProjectMarkers() []string
- func EnsureRedirectDir(redirectPath string) error
- func ExpandVariables(s string, vars map[string]string) (string, error)
- func ResolvePolicyPath(dir, name string) (string, error)
- func SetAllowInsecureHTTPServiceUpstreamForTest(v bool)
- func ValidateEnvPolicy(p EnvPolicy) error
- func ValidateHTTPServices(svcs []HTTPService) error
- func ValidateHTTPServicesWithProviders(svcs []HTTPService, providers map[string]yaml.Node) error
- type AuditSettings
- type Bundle
- type CachingSource
- type ChainConditionConfig
- type ChainRuleConfig
- type CommandOverrideConfig
- type CommandRedirect
- type CommandRule
- type ConnectRedirectResult
- type ConnectRedirectRule
- type ConnectRedirectTLSConfig
- type ConsecutiveMatchConfig
- type ContextConfig
- type ContextEngine
- type ContextEngineConfig
- type Decision
- type DnsRedirectResult
- type DnsRedirectRule
- type Engine
- func (e *Engine) CheckCommand(command string, args []string) Decision
- func (e *Engine) CheckCommandCtx(ctx context.Context, command string, args []string) Decision
- func (e *Engine) CheckCommandWithExecve(command string, args []string, execveEnforcementActive bool, ...) Decision
- func (e *Engine) CheckCommandWithExecveCtx(ctx context.Context, command string, args []string, ...) Decision
- func (e *Engine) CheckEnv(name string) EnvDecision
- func (e *Engine) CheckExecve(filename string, argv []string, depth int) Decision
- func (e *Engine) CheckExecveCtx(ctx context.Context, filename string, argv []string, depth int) Decision
- func (e *Engine) CheckFile(p string, operation string) Decision
- func (e *Engine) CheckHTTPService(service, method, reqPath string) Decision
- func (e *Engine) CheckMCPTool(server, tool string) Decision
- func (e *Engine) CheckNetwork(domain string, port int) Decision
- func (e *Engine) CheckNetworkCtx(ctx context.Context, domain string, port int) (dec Decision)
- func (e *Engine) CheckNetworkIP(domain string, ip net.IP, port int) (dec Decision)
- func (e *Engine) CheckUnixSocket(path string, operation string) Decision
- func (e *Engine) DeclaredHTTPServiceAllowsDirect(host string) bool
- func (e *Engine) DeclaredHTTPServiceHost(host string) (serviceName, envVar string, ok bool)
- func (e *Engine) EnvPolicy() EnvPolicy
- func (e *Engine) EvaluateConnectRedirect(hostPort string) *ConnectRedirectResult
- func (e *Engine) EvaluateDnsRedirect(hostname string) *DnsRedirectResult
- func (e *Engine) GetEnvInject() map[string]string
- func (e *Engine) HTTPServices() []HTTPService
- func (e *Engine) HasSoftDeleteFileRule() bool
- func (e *Engine) Inspector() InspectChecker
- func (e *Engine) Limits() Limits
- func (e *Engine) NetworkRules() []NetworkRule
- func (e *Engine) PackageRules() []PackageRule
- func (e *Engine) Policy() *Policy
- func (e *Engine) RequiresInspection() bool
- func (e *Engine) SetInspector(ic InspectChecker)
- func (e *Engine) SetThreatStore(store ThreatChecker, action string)
- func (e *Engine) SetTorPolicy(tc TorChecker)
- func (e *Engine) SignalEngine() signalEngineType
- func (e *Engine) ThreatStore() (ThreatChecker, string)
- func (e *Engine) TorPolicy() TorChecker
- func (e *Engine) TransparentOverrides() *TransparentCommandsConfig
- type EnvDecision
- type EnvPolicy
- type FileRule
- type FileSource
- type HTTPService
- type HTTPServiceInject
- type HTTPServiceInjectHeader
- type HTTPServiceRule
- type HTTPServiceSecret
- type InspectChecker
- type InspectRequest
- type InspectSpec
- type InspectVerdict
- type InspectionConfig
- type InspectionProfile
- type InspectionQuery
- type LicenseSPDXMatch
- type Limits
- type MCPCrossServerYAML
- type MCPInspectRule
- type MCPRulesConfig
- type MCPServerRuleYAML
- type MCPSubRuleEnabled
- type MCPToolRuleYAML
- type MCPVersionPinningYAML
- type Manager
- func (m *Manager) Cached() *Policy
- func (m *Manager) Get() (*Policy, error)
- func (m *Manager) Reload() (*Policy, error)
- func (m *Manager) ReloadContext(ctx context.Context) (*Policy, error)
- func (m *Manager) SelectedName() string
- func (m *Manager) SetSigningConfig(mode, trustStorePath string)
- func (m *Manager) SetSource(src Source)
- func (m *Manager) SourceDescription() string
- type NetworkRule
- type PackageMatch
- type PackageRule
- type PathRedirectRule
- type PathRedirector
- type PlatformMatchConfig
- type Policy
- type ProcessContext
- type ProcessIdentityConfig
- type ProjectRoots
- type RacePolicyConfig
- type RemoteSource
- type ResolvedEnvPolicy
- type ResourceLimits
- type RuleMetadata
- type ShellCOpaqueMode
- type SignalRule
- type SignalTargetSpec
- type Source
- type ThreatCheckResult
- type ThreatChecker
- type TorChecker
- type TorVerdict
- type TransparentCommandsConfig
- type UnixSocketRule
Constants ¶
const DefaultCommandInspectTimeout = 2 * time.Second
DefaultCommandInspectTimeout bounds inspection of a command's argv when the rule sets no `inspect.timeout`.
Command inspection is the one place the engine resolves an inspect decision itself, which means it runs inside whatever is waiting on the check: an API exec call, a seccomp USER_NOTIF, or a macOS ES_AUTH_EXEC callback. The seccomp path has no deadline of its own -- the process simply stays blocked -- so an unbounded inspector would hang an exec indefinitely with nothing in the log to explain it.
Two seconds because that is already the tightest deadline in the tree: macos/AgentMon/ESFClient.swift's execDecisionTimeout, whose watchdog denies the exec if no verdict arrives. A command rule asking for longer than that is denied on macOS whatever this constant says, so matching it keeps the two platforms answering the same way.
const DefaultRemoteMaxBytes int64 = 4 << 20
DefaultRemoteMaxBytes caps a fetched policy document.
The server is untrusted -- the signing key is the trust root, not the transport -- so an unbounded read is a denial-of-service surface against the daemon. 4 MiB is far above any policy this schema produces; the largest in-tree example is a few kilobytes.
const SignatureHeader = "X-Agentmon-Policy-Signature"
SignatureHeader carries the detached signature JSON, base64-free: the .sig file is JSON already, so it goes in the header as-is.
Variables ¶
var ErrNotModified = errors.New("policy: not modified")
ErrNotModified is returned by a Source whose content has not changed since the last Fetch. The Manager keeps the policy it has.
It is a distinct error rather than a nil bundle so a caller cannot mistake "unchanged" for "nothing came back", which on a conditional GET is the difference between a working poll and one that silently stopped enforcing.
Functions ¶
func BuildEnv ¶
BuildEnv constructs the child environment per policy. baseEnv should already be minimal; addKeys are merged after allow/deny filtering. Supports glob patterns in allow/deny lists (e.g., "AWS_*", "*_TOKEN").
func DefaultProjectMarkers ¶
func DefaultProjectMarkers() []string
DefaultProjectMarkers returns the default set of project markers to detect.
func EnsureRedirectDir ¶
EnsureRedirectDir creates the parent directory for a redirected path if needed.
func ExpandVariables ¶
ExpandVariables expands ${VAR} and ${VAR:-fallback} syntax in a string. Variables are looked up in vars map first, then environment. If a variable is undefined and has no fallback, returns an error.
func ResolvePolicyPath ¶
func SetAllowInsecureHTTPServiceUpstreamForTest ¶
func SetAllowInsecureHTTPServiceUpstreamForTest(v bool)
SetAllowInsecureHTTPServiceUpstreamForTest enables the test-only relaxation of the upstream scheme check so tests can point declared services at an httptest.Server listening on http://. This function exists so test files in other packages can flip the toggle without touching package-private state. Not thread-safe. Never call from production code.
func ValidateEnvPolicy ¶
ValidateEnvPolicy performs simple sanity checks.
func ValidateHTTPServices ¶
func ValidateHTTPServices(svcs []HTTPService) error
ValidateHTTPServices checks an HTTPServices list for well-formedness. It is called from Policy.Validate. Errors include the offending service name (and rule name, when applicable) to aid debugging.
func ValidateHTTPServicesWithProviders ¶
func ValidateHTTPServicesWithProviders(svcs []HTTPService, providers map[string]yaml.Node) error
ValidateHTTPServicesWithProviders runs structural validation via ValidateHTTPServices, then validates credential-related fields against the declared providers. It checks that secret refs parse, reference a declared provider scheme, use a valid fake format, and that inject templates contain the {{secret}} placeholder.
Types ¶
type AuditSettings ¶
type AuditSettings struct {
LogAllowed bool `yaml:"log_allowed"`
LogDenied bool `yaml:"log_denied"`
LogApproved bool `yaml:"log_approved"`
IncludeStdout bool `yaml:"include_stdout"`
IncludeStderr bool `yaml:"include_stderr"`
IncludeFileContent bool `yaml:"include_file_content"`
RetentionDays int `yaml:"retention_days"`
}
type Bundle ¶
type Bundle struct {
// Data is the policy YAML.
Data []byte
// Signature is the detached .sig JSON. Nil when the source has none;
// the Manager's signing mode decides whether that is fatal.
Signature []byte
// Name identifies the bundle in error messages -- a path for a file
// source, a URL for a remote one.
Name string
// Version is an opaque token the source uses to detect a change. For
// HTTP it is the ETag.
Version string
}
Bundle is a policy document and its detached signature.
The two travel together because verification needs both, and because the signature does not always arrive as a file: pushed over the wire it is in the same message, fetched from a server it is a sibling response. Splitting fetch from verify is what lets the same verification run over either.
type CachingSource ¶
type CachingSource struct {
// contains filtered or unexported fields
}
CachingSource keeps the last bundle its inner Source returned, so a daemon that restarts while the policy server is unreachable comes up enforcing what that server last published.
Without it, a policy server outage plus any daemon restart is a daemon that will not start. With it, the fallback is not "some other local policy" but the exact document the server served, and it is verified by the same Manager.verifyBundle as a fresh fetch -- a tampered cache file fails there.
The cache is only consulted before anything has been fetched in this process. Once a fetch has succeeded, a later failure is reported and the Manager keeps the policy already in memory; falling back to disk there would silently reinstall an older document.
func NewCachingSource ¶
func NewCachingSource(src Source, dir string, logger *slog.Logger) *CachingSource
NewCachingSource wraps src with an on-disk last-known-good copy in dir.
func (*CachingSource) Describe ¶
func (c *CachingSource) Describe() string
Describe implements Source.
type ChainConditionConfig ¶
type ChainConditionConfig struct {
// Via chain conditions
ViaIndex *int `yaml:"via_index,omitempty"` // Check specific via position (0-indexed)
ViaIndexValue string `yaml:"via_index_value,omitempty"` // Value to match at ViaIndex
ViaContains []string `yaml:"via_contains,omitempty"` // Any of these patterns in via
ViaNotContains []string `yaml:"via_not_contains,omitempty"` // None of these patterns in via
ViaMatches []string `yaml:"via_matches,omitempty"` // Pattern match against via entries
// Class-based conditions
ClassContains []string `yaml:"class_contains,omitempty"` // Any of these classes in chain
ClassNotContains []string `yaml:"class_not_contains,omitempty"` // None of these classes in chain
// Consecutive pattern detection (shell laundering)
ConsecutiveClass *ConsecutiveMatchConfig `yaml:"consecutive_class,omitempty"` // Consecutive class occurrences
ConsecutiveComm *ConsecutiveMatchConfig `yaml:"consecutive_comm,omitempty"` // Consecutive comm occurrences
// Depth conditions
DepthEQ *int `yaml:"depth_eq,omitempty"` // Depth equals
DepthGT *int `yaml:"depth_gt,omitempty"` // Depth greater than
DepthLT *int `yaml:"depth_lt,omitempty"` // Depth less than
DepthGE *int `yaml:"depth_ge,omitempty"` // Depth greater or equal
DepthLE *int `yaml:"depth_le,omitempty"` // Depth less or equal
// Taint flags
IsTainted *bool `yaml:"is_tainted,omitempty"` // Is descended from AI tool
IsAgent *bool `yaml:"is_agent,omitempty"` // Is detected as agent
// Execution context conditions
EnvContains []string `yaml:"env_contains,omitempty"` // Environment variable patterns
ArgsContain []string `yaml:"args_contain,omitempty"` // Command argument patterns
CommMatches []string `yaml:"comm_matches,omitempty"` // Command name patterns
PathMatches []string `yaml:"path_matches,omitempty"` // Executable path patterns
// Source conditions
SourceName []string `yaml:"source_name,omitempty"` // Source process name patterns
SourceContext []string `yaml:"source_context,omitempty"` // Source context name patterns
// Logical composition
Or []*ChainConditionConfig `yaml:"or,omitempty"` // OR sub-conditions (any must match)
And []*ChainConditionConfig `yaml:"and,omitempty"` // AND sub-conditions (all must match)
Not *ChainConditionConfig `yaml:"not,omitempty"` // NOT sub-condition (must not match)
}
ChainConditionConfig is the YAML-friendly version of ancestry.ChainCondition.
type ChainRuleConfig ¶
type ChainRuleConfig struct {
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
Priority int `yaml:"priority"` // Higher = evaluated first
Condition *ChainConditionConfig `yaml:"condition"` // When this rule applies
Action string `yaml:"action"` // allow_normal_policy, apply_context_policy, deny, approve, mark_as_agent, allow
Message string `yaml:"message,omitempty"`
Continue bool `yaml:"continue"` // Keep evaluating after this rule
}
ChainRuleConfig is the YAML-friendly version of ancestry.ChainRule.
type CommandOverrideConfig ¶
type CommandOverrideConfig struct {
ArgsAllow []string `yaml:"args_allow,omitempty"` // Allowed argument patterns
ArgsDeny []string `yaml:"args_deny,omitempty"` // Denied argument patterns
Default string `yaml:"default,omitempty"` // Default decision if no patterns match
}
CommandOverrideConfig provides per-command argument filtering.
type CommandRedirect ¶
type CommandRule ¶
type CommandRule struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Commands []string `yaml:"commands"`
ArgsPatterns []string `yaml:"args_patterns"`
Decision string `yaml:"decision"`
Message string `yaml:"message"`
RedirectTo *CommandRedirect `yaml:"redirect_to,omitempty"`
Context ContextConfig `yaml:"context"`
EnvAllow []string `yaml:"env_allow"`
EnvDeny []string `yaml:"env_deny"`
EnvMaxBytes int `yaml:"env_max_bytes"`
EnvMaxKeys int `yaml:"env_max_keys"`
EnvBlockIteration *bool `yaml:"env_block_iteration,omitempty"`
Inspect *InspectSpec `yaml:"inspect,omitempty"`
}
func (*CommandRule) UnmarshalYAML ¶
func (r *CommandRule) UnmarshalYAML(value *yaml.Node) error
UnmarshalYAML implements custom unmarshaling for CommandRule to set default context.
type ConnectRedirectResult ¶
type ConnectRedirectResult struct {
Matched bool
Rule string
RedirectTo string
RedirectToUnix string
TLSMode string
SNI string
Visibility string
Message string
OnFailure string
}
ConnectRedirectResult contains the result of connect redirect evaluation
type ConnectRedirectRule ¶
type ConnectRedirectRule struct {
Name string `yaml:"name"`
Match string `yaml:"match"` // regex pattern for host:port
RedirectTo string `yaml:"redirect_to,omitempty"`
RedirectToUnix string `yaml:"redirect_to_unix,omitempty"`
TLS *ConnectRedirectTLSConfig `yaml:"tls,omitempty"`
Visibility string `yaml:"visibility,omitempty"` // silent, audit_only, warn
Message string `yaml:"message,omitempty"`
OnFailure string `yaml:"on_failure,omitempty"` // fail_closed, fail_open, retry_original
}
ConnectRedirectRule redirects TCP connections for matching host:port. Exactly one target must be set:
- redirect_to for TCP host:port targets
- redirect_to_unix for Unix-socket targets
type ConnectRedirectTLSConfig ¶
type ConnectRedirectTLSConfig struct {
Mode string `yaml:"mode,omitempty"` // passthrough, rewrite_sni
SNI string `yaml:"sni,omitempty"` // required if mode is rewrite_sni
}
ConnectRedirectTLSConfig controls TLS handling for connect redirects
type ConsecutiveMatchConfig ¶
type ConsecutiveMatchConfig struct {
Value string `yaml:"value"` // Class name or comm pattern
CountGE int `yaml:"count_ge,omitempty"` // Count must be >= this
CountLE int `yaml:"count_le,omitempty"` // Count must be <= this (0 = no limit)
}
ConsecutiveMatchConfig specifies a consecutive occurrence requirement.
type ContextConfig ¶
type ContextConfig struct {
MinDepth int `yaml:"min_depth"`
MaxDepth int `yaml:"max_depth"` // -1 means unlimited
}
ContextConfig defines depth constraints for rule matching. It enables depth-aware policy rules - allowing different policies for "direct" (user-typed, depth 0) vs "nested" (script-spawned, depth 1+) commands.
func DefaultContext ¶
func DefaultContext() ContextConfig
DefaultContext returns a context matching all depths.
func (*ContextConfig) MatchesDepth ¶
func (c *ContextConfig) MatchesDepth(depth int) bool
MatchesDepth returns true if depth falls within the configured range.
func (*ContextConfig) UnmarshalYAML ¶
func (c *ContextConfig) UnmarshalYAML(unmarshal func(interface{}) error) error
UnmarshalYAML handles both array syntax [direct, nested] and object syntax.
type ContextEngine ¶
type ContextEngine struct {
*Engine
// contains filtered or unexported fields
}
ContextEngine extends Engine with taint-aware policy evaluation.
func NewContextEngine ¶
func NewContextEngine(p *Policy, enforceApprovals bool, enforceRedirects bool, cfg ContextEngineConfig) (*ContextEngine, error)
NewContextEngine creates a context-aware policy engine.
func (*ContextEngine) CheckCommandWithContext ¶
func (ce *ContextEngine) CheckCommandWithContext(ctx context.Context, pid int, command string, args []string) Decision
CheckCommandWithContext evaluates a command with taint awareness.
func (*ContextEngine) Matcher ¶
func (ce *ContextEngine) Matcher() *identity.ProcessMatcher
Matcher returns the process matcher for external access.
func (*ContextEngine) TaintCache ¶
func (ce *ContextEngine) TaintCache() *ancestry.TaintCache
TaintCache returns the taint cache for external access.
type ContextEngineConfig ¶
type ContextEngineConfig struct {
TaintCache *ancestry.TaintCache
Matcher *identity.ProcessMatcher
}
ContextEngineConfig configures the context engine.
type Decision ¶
type Decision struct {
PolicyDecision types.Decision
EffectiveDecision types.Decision
Rule string
Message string
Approval *types.ApprovalInfo
Redirect *types.RedirectInfo
FileRedirect *types.FileRedirectInfo
EnvPolicy ResolvedEnvPolicy
ThreatFeed string
ThreatMatch string
ThreatAction string // "deny" or "audit" — set when a threat feed matched
Tor *TorVerdict // non-nil when a Tor vector matched (deny or audit)
// Inspect is set when the matched rule defers to content inspection,
// either as the decision itself or as a precondition. While it is set
// and unresolved, EffectiveDecision is deny.
Inspect *types.InspectInfo
}
type DnsRedirectResult ¶
type DnsRedirectResult struct {
Matched bool
Rule string
ResolveTo string
Visibility string
OnFailure string
}
DnsRedirectResult contains the result of DNS redirect evaluation
type DnsRedirectRule ¶
type DnsRedirectRule struct {
Name string `yaml:"name"`
Match string `yaml:"match"` // regex pattern for hostname
ResolveTo string `yaml:"resolve_to"` // IP address to return
Visibility string `yaml:"visibility,omitempty"` // silent, audit_only, warn
OnFailure string `yaml:"on_failure,omitempty"` // fail_closed, fail_open, retry_original
}
DnsRedirectRule redirects DNS resolution for matching hostnames
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
func NewEngineWithVariables ¶
func NewEngineWithVariables(p *Policy, enforceApprovals bool, enforceRedirects bool, vars map[string]string) (*Engine, error)
NewEngineWithVariables creates an engine with variable expansion. Variables in policy paths are expanded before glob compilation.
func (*Engine) CheckCommand ¶
CheckCommand evaluates a command against the policy with no assumption of runtime execve interception (opaque shell-c scripts are pre-denied when a restrictive command rule is present). See CheckCommandWithExecve for callers on an execve-policed execution path.
func (*Engine) CheckCommandCtx ¶
CheckCommandCtx is CheckCommand with a caller context bounding content inspection.
A command rule carrying `decision: inspect` or `inspect: {require: true}` is resolved here, not deferred to the caller. For a command the engine already holds the content -- the argv IS the content -- and resolving in one place is what makes every enforcement layer agree. See resolveCommandInspection.
ctx bounds the inspector call, and the rule's own inspect.timeout (or DefaultCommandInspectTimeout) bounds it again, tighter, from inside.
func (*Engine) CheckCommandWithExecve ¶
func (e *Engine) CheckCommandWithExecve(command string, args []string, execveEnforcementActive bool, opaqueMode ShellCOpaqueMode) Decision
CheckCommandWithExecve is CheckCommand for callers whose execution path has runtime execve interception active (seccomp USER_NOTIF or ptrace), so every inner execve is policed by CheckExecve. When execveEnforcementActive is true the opaque shell-c pre-deny is skipped — the script runs and its inner commands are enforced precisely at exec time. Issue #375.
func (*Engine) CheckCommandWithExecveCtx ¶
func (e *Engine) CheckCommandWithExecveCtx(ctx context.Context, command string, args []string, execveEnforcementActive bool, opaqueMode ShellCOpaqueMode) Decision
CheckCommandWithExecveCtx is CheckCommandWithExecve with a caller context bounding content inspection.
func (*Engine) CheckEnv ¶
func (e *Engine) CheckEnv(name string) EnvDecision
CheckEnv evaluates the env policy against an environment variable name. Returns whether the variable is allowed and what matched. Logic: deny patterns are checked first (deny wins), then allow patterns. If no allow patterns defined, default is allow (unless denied). If allow patterns defined, default is deny (unless allowed).
func (*Engine) CheckExecve ¶
CheckExecve evaluates an execve call against command rules with depth context support. Returns the decision from the first matching rule, or default deny if none match. The depth parameter represents the ancestry depth: 0 = direct (user-typed), 1+ = nested (script-spawned).
func (*Engine) CheckExecveCtx ¶
func (e *Engine) CheckExecveCtx(ctx context.Context, filename string, argv []string, depth int) Decision
CheckExecveCtx is CheckExecve with a caller context bounding content inspection. The seccomp path has no deadline of its own -- the process stays blocked until the verdict arrives -- so this is where a caller supplies one.
func (*Engine) CheckHTTPService ¶
CheckHTTPService evaluates method+reqPath against the rules for service. reqPath is the path portion AFTER the /svc/<name> prefix has been stripped and the query string removed. The gateway is responsible for stripping both before calling this method.
A single trailing slash is permitted on reqPath for usability — the upstream API often accepts both forms — and is stripped before the rule matcher runs so policy authors only have to write the non-slashed form.
Returns a wrapped Decision in the same shape as CheckNetworkCtx. First- match-wins on rules. If no rule matches, the service's Default applies (the compiler defaults empty to "deny"). Unknown services always deny.
func (*Engine) CheckMCPTool ¶
CheckMCPTool evaluates mcp_inspect_rules against one MCP tool call and returns the decision its arguments must satisfy.
A match yields an inspect-bearing Decision whose EffectiveDecision is deny until a caller that holds the arguments runs inspection and resolves it -- the same contract every other rule kind's inspect decision has. See internal/inspect.Resolve.
No match yields allow, not the default deny every other Check* returns. This rule kind selects what is inspected; it does not decide whether a tool may be called. That decision belongs to mcp_rules / sandbox.mcp and is made by mcpinspect.PolicyEvaluator, which fails closed on its own under `tool_policy: allowlist`. Returning deny here would mean an operator who adds a single inspection rule silently blocks every tool call the rule does not name. Validate refuses `decision: deny` on this rule kind so the fall-through cannot be mistaken for an allowlist.
func (*Engine) CheckNetwork ¶
CheckNetwork evaluates network_rules against a domain and port. Deprecated: Use CheckNetworkCtx for proper cancellation support.
func (*Engine) CheckNetworkCtx ¶
CheckNetworkCtx evaluates network_rules against a domain and port with context support. If a rule requires CIDR matching and the domain is not an IP literal, DNS resolution will be performed using the provided context for cancellation.
func (*Engine) CheckNetworkIP ¶
CheckNetworkIP evaluates network_rules using a known destination IP (no DNS resolution). If domain is empty, only CIDR/port-based rules can match.
func (*Engine) CheckUnixSocket ¶
CheckUnixSocket evaluates unix_socket_rules against a path and operation (connect|bind|listen|sendto). Paths for abstract sockets should be passed as "@name".
func (*Engine) DeclaredHTTPServiceAllowsDirect ¶
DeclaredHTTPServiceAllowsDirect returns true when the declared service matching host has allow_direct: true set in its YAML. Callers of DeclaredHTTPServiceHost should query this before denying direct access in the fail-closed netmonitor path — a true result means the service opted out of the gateway-only constraint.
host follows the same canonicalization rules as DeclaredHTTPServiceHost (case, trailing dot, bracketed or bare IPv6, optional port). Returns false for unknown hosts — the caller already gated on DeclaredHTTPServiceHost.
func (*Engine) DeclaredHTTPServiceHost ¶
DeclaredHTTPServiceHost reports whether host belongs to a declared http_services entry. host may include a port (bracket-aware strip), be in any case, end in a trailing dot, or be a bracketed IPv6 literal. It also accepts a bare IPv6 literal (e.g. from net.SplitHostPort on a bracketed authority), which callers may produce when dealing with post-parsed HTTP Host headers. Returns the canonical service name and the env var name used by the gateway.
func (*Engine) EvaluateConnectRedirect ¶
func (e *Engine) EvaluateConnectRedirect(hostPort string) *ConnectRedirectResult
EvaluateConnectRedirect checks if a connection should be redirected. The host portion of hostPort is normalized (lowercased, trailing dot removed) to ensure case-insensitive matching consistent with DNS semantics.
func (*Engine) EvaluateDnsRedirect ¶
func (e *Engine) EvaluateDnsRedirect(hostname string) *DnsRedirectResult
EvaluateDnsRedirect checks if a hostname should be redirected. The hostname is normalized (lowercased, trimmed, trailing dot removed) to ensure case-insensitive matching consistent with DNS semantics.
func (*Engine) GetEnvInject ¶
GetEnvInject returns the env_inject map from the policy. Returns an empty map if engine, policy, or EnvInject is nil.
func (*Engine) HTTPServices ¶
func (e *Engine) HTTPServices() []HTTPService
HTTPServices returns a deep copy of the source HTTPService list. Used by the proxy to enumerate declared services for EnvVars() injection and by tests. Callers may mutate the returned slice and its contents without affecting engine state.
func (*Engine) HasSoftDeleteFileRule ¶
HasSoftDeleteFileRule reports whether any compiled file rule uses the soft_delete decision. Used to decide whether the FUSE layer needs a trash divert wired in even when the global audit mode is not soft_delete.
func (*Engine) Inspector ¶
func (e *Engine) Inspector() InspectChecker
Inspector returns the installed inspector, or nil.
func (*Engine) NetworkRules ¶
func (e *Engine) NetworkRules() []NetworkRule
NetworkRules returns the raw network rules for read-only inspection (e.g., ebpf allowlist).
func (*Engine) PackageRules ¶
func (e *Engine) PackageRules() []PackageRule
PackageRules returns the package install check rules from the loaded policy.
func (*Engine) Policy ¶
Policy returns the underlying policy for read-only inspection (e.g., Landlock path derivation).
func (*Engine) RequiresInspection ¶
RequiresInspection reports whether the engine's policy needs an inspector.
func (*Engine) SetInspector ¶
func (e *Engine) SetInspector(ic InspectChecker)
SetInspector installs the optional content inspector. Pass nil to disable.
The engine is usable without one: wrapRuleDecision resolves every inspect-bearing rule to an effective deny, because it runs at rule-match time and has no content. Wiring an inspector does not change that; it is the content-holding callers, added in later work, that consult it.
func (*Engine) SetThreatStore ¶
func (e *Engine) SetThreatStore(store ThreatChecker, action string)
SetThreatStore configures an optional threat feed store for domain checking. action must be "deny" or "audit"; defaults to "deny" if invalid.
func (*Engine) SetTorPolicy ¶
func (e *Engine) SetTorPolicy(tc TorChecker)
SetTorPolicy installs the optional Tor coordinator. Pass nil to disable.
func (*Engine) SignalEngine ¶
func (e *Engine) SignalEngine() signalEngineType
SignalEngine returns the signal policy engine, or nil if no signal rules.
func (*Engine) ThreatStore ¶
func (e *Engine) ThreatStore() (ThreatChecker, string)
func (*Engine) TorPolicy ¶
func (e *Engine) TorPolicy() TorChecker
TorPolicy returns the installed Tor coordinator, or nil.
It exists so a caller can tell "no coordinator" from "one that was installed deliberately". A session put into Tor-deny gets a coordinator of its own, and the app-wide one must not replace it.
func (*Engine) TransparentOverrides ¶
func (e *Engine) TransparentOverrides() *TransparentCommandsConfig
TransparentOverrides returns the policy's transparent command overrides (Add/Remove slices), or nil if no transparent commands config is set. The caller is responsible for converting to the appropriate handler type.
type EnvDecision ¶
type EnvDecision struct {
Allowed bool
MatchedBy string // "allow", "deny", "default-allow", "default-deny"
Pattern string // The pattern that matched, if any
}
CheckRegistry evaluates registry_rules against a path and operation. EnvDecision represents the result of CheckEnv with additional metadata.
type FileRule ¶
type FileRule struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Paths []string `yaml:"paths"`
Operations []string `yaml:"operations"`
Decision string `yaml:"decision"`
Message string `yaml:"message"`
Timeout duration `yaml:"timeout"`
// Redirect configuration for file operations
RedirectTo string `yaml:"redirect_to,omitempty"` // Target directory for redirected files
PreserveTree bool `yaml:"preserve_tree,omitempty"` // Preserve directory structure under target
Inspect *InspectSpec `yaml:"inspect,omitempty"`
}
type FileSource ¶
FileSource reads a policy from a directory, with the optional SHA256SUMS manifest check.
The manifest check lives here rather than in the Manager because it is a property of the local policy directory: it maps a basename to a digest, and a bundle that never came from that directory can never be listed in it.
func (*FileSource) Fetch ¶
func (f *FileSource) Fetch(context.Context) (*Bundle, error)
Fetch implements Source.
A missing signature is not an error here. The Manager's signing mode is what decides whether an unsigned policy may load, and reporting the absence as a read failure would turn `signing: off` into a hard error for every policy nobody signed.
type HTTPService ¶
type HTTPService struct {
Name string `yaml:"name"`
Upstream string `yaml:"upstream"` // https://api.github.com
ExposeAs string `yaml:"expose_as,omitempty"` // env var name; derived from Name if empty
Aliases []string `yaml:"aliases,omitempty"` // extra hostnames for the fail-closed check
AllowDirect bool `yaml:"allow_direct,omitempty"` // escape hatch; default false
Default string `yaml:"default,omitempty"` // allow | deny; default depends on Rules presence
Rules []HTTPServiceRule `yaml:"rules,omitempty"`
// Credential substitution (unified from old services: section).
Secret *HTTPServiceSecret `yaml:"secret,omitempty"`
Inject *HTTPServiceInject `yaml:"inject,omitempty"`
ScrubResponse *bool `yaml:"scrub_response,omitempty"` // nil = default based on Secret presence
}
HTTPService declares an HTTP service that a cooperating child process can reach through the proxy gateway. Requests are matched to the service by a URL path prefix (/svc/<name>/), then evaluated against Rules in declaration order. First-match-wins; if no rule matches, Default applies (empty or "deny" means deny).
type HTTPServiceInject ¶
type HTTPServiceInject struct {
Header *HTTPServiceInjectHeader `yaml:"header,omitempty"`
}
HTTPServiceInject defines how the credential is injected into requests.
type HTTPServiceInjectHeader ¶
type HTTPServiceInjectHeader struct {
Name string `yaml:"name"` // e.g. "Authorization"
Template string `yaml:"template"` // e.g. "Bearer {{secret}}"
}
HTTPServiceInjectHeader defines header injection config.
type HTTPServiceRule ¶
type HTTPServiceRule struct {
Name string `yaml:"name"`
Methods []string `yaml:"methods,omitempty"` // empty or "*" means any method
Paths []string `yaml:"paths"` // gobwas/glob patterns, '/' separator
Decision string `yaml:"decision"` // allow | deny | approve | audit
Message string `yaml:"message,omitempty"`
Timeout duration `yaml:"timeout,omitempty"` // parsed but not wired in v1
}
HTTPServiceRule is a single method+path matching rule for an HTTP service.
type HTTPServiceSecret ¶
type HTTPServiceSecret struct {
Ref string `yaml:"ref"` // e.g. "vault://kv/data/github#token"
Format string `yaml:"format"` // e.g. "ghp_{rand:36}"
}
HTTPServiceSecret defines how to fetch and fake a credential.
type InspectChecker ¶
type InspectChecker interface {
Inspect(ctx context.Context, req InspectRequest) (InspectVerdict, error)
}
InspectChecker is the optional content inspector, mirroring ThreatChecker and TorChecker: the policy package declares the interface and keeps zero dependency on any implementation.
type InspectRequest ¶
type InspectRequest struct {
// Profiles are the profile names from the matched rule's spec.
Profiles []string
// Kind describes where the content came from: file, command, network,
// proxy_body, mcp_args. Providers use it to pick a strictness, and the
// audit log records it.
Kind string
// Content is the text to inspect.
Content string
}
InspectRequest is the content handed to an inspector.
type InspectSpec ¶
type InspectSpec struct {
// Require makes inspection a precondition on a non-inspect decision.
// Without it, an inspect block on e.g. `decision: allow` would be
// inert, so Validate rejects that combination rather than silently
// ignoring the block.
Require bool `yaml:"require,omitempty"`
// Profiles names entries in inspection.profiles. At least one.
Profiles []string `yaml:"profiles"`
// OnViolation is applied when inspection reports a finding.
// Defaults to deny.
OnViolation string `yaml:"on_violation,omitempty"`
// OnFailure is applied when inspection cannot run, errors, or times
// out. Defaults to fail_closed.
OnFailure string `yaml:"on_failure,omitempty"`
// Timeout bounds a single inspection. Zero leaves it to the inspector.
Timeout duration `yaml:"timeout,omitempty"`
}
InspectSpec is a rule's `inspect:` block. It is the decision itself when the rule's decision is "inspect", and a precondition on the rule's decision when Require is true.
type InspectVerdict ¶
type InspectVerdict struct {
// Violation is true when at least one profile reported a finding.
Violation bool
// Profile names the profile that produced the finding.
Profile string
// Detail is a short human-readable reason for the audit log. It must
// not contain the inspected content — that content is exactly the
// sensitive material inspection exists to keep from leaking.
Detail string
// Redacted is the rewritten content, set only when the resolved action
// is redact.
Redacted string
}
InspectVerdict is an inspector's answer.
type InspectionConfig ¶
type InspectionConfig struct {
Profiles map[string]InspectionProfile `yaml:"profiles"`
}
InspectionConfig is the policy's `inspection:` block: a set of named, reusable inspection profiles that rules refer to by name. Defining the provider and its parameters once, away from the rules, is what lets a single profile change apply to every rule that names it.
type InspectionProfile ¶
type InspectionProfile struct {
// Provider names the inspector implementation, e.g. privacy_filter.
Provider string `yaml:"provider"`
// Categories restricts a span classifier to a subset of its labels.
Categories []string `yaml:"categories,omitempty"`
// Action is the profile's own default outcome on a finding. A rule's
// on_violation overrides it.
Action string `yaml:"action,omitempty"`
// Instruct is the context and strictness given to a safety classifier.
Instruct string `yaml:"instruct,omitempty"`
// Queries are the yes/no questions a safety classifier answers.
Queries []InspectionQuery `yaml:"queries,omitempty"`
}
InspectionProfile describes one way of inspecting content. The fields a given provider reads differ: a span classifier reads Categories, a question-answering safety classifier reads Instruct and Queries. Validation checks the shape of what is present, not which provider will consume it — no providers exist yet, and hardcoding a provider whitelist here would have to be edited every time one is added.
type InspectionQuery ¶
type InspectionQuery struct {
ID string `yaml:"id"`
Text string `yaml:"text"`
Threshold float64 `yaml:"threshold,omitempty"`
}
InspectionQuery is one yes/no question put to a safety classifier.
type LicenseSPDXMatch ¶
type LicenseSPDXMatch struct {
Allow []string `yaml:"allow,omitempty"`
Deny []string `yaml:"deny,omitempty"`
}
LicenseSPDXMatch defines allow/deny lists for SPDX license identifiers.
type MCPCrossServerYAML ¶
type MCPCrossServerYAML struct {
Enabled bool `yaml:"enabled"`
SubRules map[string]MCPSubRuleEnabled `yaml:",inline"`
}
MCPCrossServerYAML represents cross-server config in generated YAML.
type MCPInspectRule ¶
type MCPInspectRule struct {
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
// Servers matches the MCP server ID, as glob patterns. Empty matches
// every server.
Servers []string `yaml:"servers,omitempty"`
// Tools matches the tool name, as glob patterns. Empty matches every
// tool.
Tools []string `yaml:"tools,omitempty"`
// Decision must be "inspect".
Decision string `yaml:"decision"`
Message string `yaml:"message,omitempty"`
Inspect *InspectSpec `yaml:"inspect,omitempty"`
}
MCPInspectRule selects MCP tool calls whose arguments are inspected.
It is deliberately NOT an authorisation mechanism, and `decision` accepts only `inspect`. Whether a tool may be called at all is decided by mcp_rules / sandbox.mcp, evaluated by mcpinspect.PolicyEvaluator, which already fails closed under `tool_policy: allowlist`. Every other rule kind in this schema falls through to a default deny; this one falls through to no inspection, because a second default deny here would block every tool call in every existing deployment the moment an operator added one inspection rule. Refusing `decision: deny` is what keeps that default from being read as an allowlist that leaks.
type MCPRulesConfig ¶
type MCPRulesConfig struct {
EnforcePolicy bool `yaml:"enforce_policy"`
ToolPolicy string `yaml:"tool_policy,omitempty"`
AllowedTools []MCPToolRuleYAML `yaml:"allowed_tools,omitempty"`
AllowedServers []MCPServerRuleYAML `yaml:"allowed_servers,omitempty"`
ServerPolicy string `yaml:"server_policy,omitempty"`
VersionPinning MCPVersionPinningYAML `yaml:"version_pinning"`
CrossServer *MCPCrossServerYAML `yaml:"cross_server,omitempty"`
}
MCPRulesConfig mirrors the MCP policy fields generated by policygen. It uses the same YAML field names as config.SandboxMCPConfig for compatibility.
type MCPServerRuleYAML ¶
type MCPServerRuleYAML struct {
ID string `yaml:"id"`
}
MCPServerRuleYAML represents a server rule in generated YAML.
type MCPSubRuleEnabled ¶
type MCPSubRuleEnabled struct {
Enabled bool `yaml:"enabled"`
}
MCPSubRuleEnabled represents a sub-rule with just an enabled flag.
type MCPToolRuleYAML ¶
type MCPToolRuleYAML struct {
Server string `yaml:"server"`
Tool string `yaml:"tool"`
ContentHash string `yaml:"content_hash,omitempty"`
}
MCPToolRuleYAML represents a tool rule in generated YAML.
type MCPVersionPinningYAML ¶
type MCPVersionPinningYAML struct {
Enabled bool `yaml:"enabled"`
OnChange string `yaml:"on_change,omitempty"`
AutoTrustFirst bool `yaml:"auto_trust_first,omitempty"`
}
MCPVersionPinningYAML represents version pinning config in generated YAML.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager selects and loads a policy once, based on config and env.
func NewManager ¶
NewManager binds the policy name but defers file I/O until first Get(). envName is the value of AGENTMON_POLICY_NAME (already read from environment).
func (*Manager) Cached ¶
Cached returns the policy already loaded, without fetching. It is nil before the first load.
A poller uses it to learn what is already in force: calling Get() for that would fetch, and the document it fetched would then never be reported as a change.
func (*Manager) Reload ¶
Reload forces the next Get() to re-read the policy file from disk. Used when the policy has been replaced out-of-band (e.g. a fresh snapshot was pushed by the operator via WTP SessionAck). Subsequent Get() calls return the new policy; in-flight callers that already captured a *Policy are unaffected.
Returns the new policy or the parse/validate error. A Reload error also installs itself as the cached err so subsequent Get() calls surface the same failure without a re-read.
func (*Manager) ReloadContext ¶
ReloadContext is Reload with a caller context bounding the fetch. A remote source needs one; a file source ignores it.
ErrNotModified is not a failure and does not replace the cached policy: a conditional GET answering 304 means the agent already has the current document, and installing an error there would take enforcement down on the first quiet poll.
No failure replaces a policy that already loaded. A reload that cannot fetch, cannot verify or cannot parse returns the cached policy alongside the error, so the caller reports the failure while Get() keeps answering with the last document that was actually good. Installing the error instead would mean one unreachable poll made every subsequent session creation fail against a policy that never changed -- and, on the WTP push path, a single malformed push poisoned the Manager for the life of the process.
Callers must treat a non-nil error as a failed reload even when a policy comes back with it: the policy is the old one.
func (*Manager) SelectedName ¶
SelectedName returns the bound policy name (without suffix).
func (*Manager) SetSigningConfig ¶
SetSigningConfig configures signature verification for this manager. mode is "enforce", "warn", or "off". trustStorePath is a directory of public key JSON files.
func (*Manager) SetSource ¶
SetSource replaces where the policy is fetched from. Pass nil to go back to the local directory.
func (*Manager) SourceDescription ¶
SourceDescription names where the policy comes from, for logs.
type NetworkRule ¶
type NetworkRule struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Domains []string `yaml:"domains"`
Ports []int `yaml:"ports"`
CIDRs []string `yaml:"cidrs"`
Decision string `yaml:"decision"`
Message string `yaml:"message"`
Timeout duration `yaml:"timeout"`
Inspect *InspectSpec `yaml:"inspect,omitempty"`
}
type PackageMatch ¶
type PackageMatch struct {
Packages []string `yaml:"packages,omitempty"` // Exact package names
NamePatterns []string `yaml:"name_patterns,omitempty"` // Glob patterns for package names
FindingType string `yaml:"finding_type,omitempty"` // vulnerability, license, etc.
Severity string `yaml:"severity,omitempty"` // critical, high, medium, low, info
Reasons []string `yaml:"reasons,omitempty"` // Match specific reason codes
LicenseSPDX *LicenseSPDXMatch `yaml:"license_spdx,omitempty"` // SPDX license matching
Ecosystem string `yaml:"ecosystem,omitempty"` // npm, pypi
Options map[string]any `yaml:"options,omitempty"` // Provider-specific options
}
PackageMatch specifies conditions for matching packages in policy rules.
type PackageRule ¶
type PackageRule struct {
Match PackageMatch `yaml:"match"`
Action string `yaml:"action"` // allow, warn, approve, block
Reason string `yaml:"reason,omitempty"`
}
PackageRule defines a policy rule for package install checks.
type PathRedirectRule ¶
type PathRedirectRule struct {
Name string `yaml:"name"`
SourcePattern string `yaml:"source_pattern"` // Glob pattern for source path
TargetBase string `yaml:"target_base"` // Base directory for redirected files
Operations []string `yaml:"operations"` // write, create, delete, etc.
PreserveTree bool `yaml:"preserve_tree"` // Preserve directory structure under target
}
PathRedirectRule defines a path redirect rule.
type PathRedirector ¶
type PathRedirector struct {
// contains filtered or unexported fields
}
PathRedirector redirects file paths based on configured rules. It is typically used by FUSE or other file system interceptors.
func NewPathRedirector ¶
func NewPathRedirector(rules []PathRedirectRule) (*PathRedirector, error)
NewPathRedirector creates a PathRedirector from a list of rules.
func (*PathRedirector) Redirect ¶
func (pr *PathRedirector) Redirect(path string, operation string) (string, bool)
Redirect checks if a path should be redirected for the given operation. Returns the new path and true if redirected, or the original path and false if not.
func (*PathRedirector) RedirectWithInfo ¶
func (pr *PathRedirector) RedirectWithInfo(path string, operation string) *types.FileRedirectInfo
RedirectWithInfo is like Redirect but returns full redirect information.
type PlatformMatchConfig ¶
type PlatformMatchConfig struct {
Comm []string `yaml:"comm,omitempty"` // Process name patterns
ExePath []string `yaml:"exe_path,omitempty"` // Executable path patterns
Cmdline []string `yaml:"cmdline,omitempty"` // Command line patterns
BundleID []string `yaml:"bundle_id,omitempty"` // macOS bundle ID
}
PlatformMatchConfig defines platform-specific process matching rules.
type Policy ¶
type Policy struct {
Version int `yaml:"version"`
Name string `yaml:"name"`
Description string `yaml:"description"`
Metadata []RuleMetadata `yaml:"metadata,omitempty"`
FileRules []FileRule `yaml:"file_rules"`
NetworkRules []NetworkRule `yaml:"network_rules"`
CommandRules []CommandRule `yaml:"command_rules"`
UnixRules []UnixSocketRule `yaml:"unix_socket_rules"`
SignalRules []SignalRule `yaml:"signal_rules"`
DnsRedirectRules []DnsRedirectRule `yaml:"dns_redirects,omitempty"`
ConnectRedirectRules []ConnectRedirectRule `yaml:"connect_redirects,omitempty"`
ResourceLimits ResourceLimits `yaml:"resource_limits"`
EnvPolicy EnvPolicy `yaml:"env_policy"`
Audit AuditSettings `yaml:"audit"`
EnvInject map[string]string `yaml:"env_inject"`
// MCP rules (generated by policygen for MCP tool/server allowlists)
MCPRules *MCPRulesConfig `yaml:"mcp_rules,omitempty"`
// MCPInspectRules select which MCP tool calls have their arguments
// inspected. They do not authorise a tool call — see MCPInspectRule.
MCPInspectRules []MCPInspectRule `yaml:"mcp_inspect_rules,omitempty"`
// Process context-based rules (parent-conditional policies)
ProcessContexts map[string]ProcessContext `yaml:"process_contexts,omitempty"`
ProcessIdentities map[string]ProcessIdentityConfig `yaml:"process_identities,omitempty"`
// Package install check rules
PackageRules []PackageRule `yaml:"package_rules,omitempty"`
// Inspection defines reusable content-inspection profiles referenced by
// rules with `decision: inspect` or an `inspect:` precondition block.
Inspection *InspectionConfig `yaml:"inspection,omitempty"`
// Transparent command overrides (add/remove from built-in defaults)
TransparentCommands *TransparentCommandsConfig `yaml:"transparent_commands,omitempty"`
// External secrets: provider definitions.
Providers map[string]yaml.Node `yaml:"providers,omitempty"`
// Services is a migration tripwire. The old "services:" key has been
// replaced by "http_services:". If this field is non-zero after YAML
// parsing, Validate emits a clear migration error.
Services yaml.Node `yaml:"services,omitempty"`
// HTTP services: unified path/verb filtering + credential substitution.
HTTPServices []HTTPService `yaml:"http_services,omitempty"`
// DB access (Phase 1, Plan 02). Stored opaquely as yaml.Node so this
// package does not depend on internal/db/policy. Decoding and validation
// live in internal/db/policy.Decode.
DBServices yaml.Node `yaml:"db_services,omitempty"`
DatabaseRules yaml.Node `yaml:"database_rules,omitempty"`
DatabaseConnectionRules yaml.Node `yaml:"database_connection_rules,omitempty"`
// Policies stores the opaque policies: block so KnownFields(true) in
// LoadFromBytes accepts YAML containing sub-blocks owned by other packages
// (e.g. policies.db is owned by internal/db/policy). Each sub-package
// reads its own slice via yaml.Marshal/Unmarshal round-trip.
Policies yaml.Node `yaml:"policies,omitempty"`
}
func LoadFromBytes ¶
LoadFromBytes parses and validates a policy from raw YAML bytes.
func LoadFromFile ¶
func ParseAndValidate ¶
ParseAndValidate decodes a policy document with unknown fields refused and runs Validate. It is exported so a policy server can apply the same bar before serving a bundle as an agent applies before installing one; a document only one side accepts is a fleet-wide fail-closed discovered by the fleet.
func (Policy) InspectionProfilesUsed ¶
InspectionProfilesUsed returns every profile name any rule refers to, sorted and deduplicated. A caller uses it to check up front that each one can actually run, rather than discovering at the first request that the rule fails closed.
func (Policy) RequiresInspection ¶
RequiresInspection reports whether any rule in the policy names an inspection profile. A server that cannot provide an inspector should refuse to install such a policy rather than run it, because every inspect-bearing rule would otherwise resolve to a deny the operator did not write.
type ProcessContext ¶
type ProcessContext struct {
Description string `yaml:"description,omitempty"`
Identities []string `yaml:"identities"` // Process identities that trigger this context
// Chain rules for escape hatch detection (evaluated before context rules)
ChainRules []ChainRuleConfig `yaml:"chain_rules,omitempty"`
// Rules that apply within this context (override global rules)
CommandRules []CommandRule `yaml:"command_rules,omitempty"`
FileRules []FileRule `yaml:"file_rules,omitempty"`
NetworkRules []NetworkRule `yaml:"network_rules,omitempty"`
UnixRules []UnixSocketRule `yaml:"unix_socket_rules,omitempty"`
EnvPolicy *EnvPolicy `yaml:"env_policy,omitempty"`
// Quick command lists (simpler alternative to full CommandRules)
AllowedCommands []string `yaml:"allowed_commands,omitempty"` // Commands allowed without restriction
DeniedCommands []string `yaml:"denied_commands,omitempty"` // Commands always denied
RequireApproval []string `yaml:"require_approval,omitempty"` // Commands requiring approval
// Per-command argument filtering
CommandOverrides map[string]CommandOverrideConfig `yaml:"command_overrides,omitempty"`
// Default decision when no rules match
DefaultDecision string `yaml:"default_decision,omitempty"` // allow, deny, approve (default: deny)
// Race condition handling
RacePolicy *RacePolicyConfig `yaml:"race_policy,omitempty"`
// Propagation settings
MaxDepth int `yaml:"max_depth,omitempty"` // Max ancestry depth (0 = unlimited)
StopAt []string `yaml:"stop_at,omitempty"` // Stop propagation at these process classes
PassThrough []string `yaml:"pass_through,omitempty"` // Classes that inherit but don't count toward depth
}
ProcessContext defines rules that apply to processes spawned from specific parents. This enables parent-conditional policies for AI tool sandboxing.
type ProcessIdentityConfig ¶
type ProcessIdentityConfig struct {
Description string `yaml:"description,omitempty"`
Linux *PlatformMatchConfig `yaml:"linux,omitempty"`
Darwin *PlatformMatchConfig `yaml:"darwin,omitempty"`
AllPlatforms *PlatformMatchConfig `yaml:"all_platforms,omitempty"`
}
ProcessIdentityConfig defines how to identify a process in policy configuration. This is the YAML-friendly version of identity.ProcessIdentity.
type ProjectRoots ¶
type ProjectRoots struct {
ProjectRoot string // Nearest project marker or workspace
GitRoot string // Nearest .git, or empty if not in git repo
}
ProjectRoots holds detected project root paths.
func DetectProjectRoots ¶
func DetectProjectRoots(workspace string, markers []string) (*ProjectRoots, error)
DetectProjectRoots walks up from workspace to find project markers. Returns ProjectRoot (nearest language marker or workspace) and GitRoot (nearest .git).
type RacePolicyConfig ¶
type RacePolicyConfig struct {
OnMissingParent string `yaml:"on_missing_parent,omitempty"` // deny, allow, approve (default: deny)
OnPIDMismatch string `yaml:"on_pid_mismatch,omitempty"` // deny, allow, approve (default: deny)
OnValidationError string `yaml:"on_validation_error,omitempty"` // deny, allow, approve (default: deny)
LogRaceConditions bool `yaml:"log_race_conditions,omitempty"` // Log race condition events
}
RacePolicyConfig defines how to handle race conditions in taint validation.
type RemoteSource ¶
type RemoteSource struct {
// URL is the policy endpoint.
URL string
// Client is the HTTP client. Nil uses one with defaultRemoteTimeout.
Client *http.Client
// MaxBytes caps the document. Zero uses DefaultRemoteMaxBytes.
MaxBytes int64
// Header carries additional request headers, e.g. authentication.
Header http.Header
// Wait requests long-polling: the server holds the request open until
// the policy changes or the duration elapses. Zero disables it, and a
// server that ignores the parameter simply answers immediately.
Wait time.Duration
// contains filtered or unexported fields
}
RemoteSource fetches a signed policy over HTTP with a conditional GET.
Modelled on internal/threatfeed/syncer.go, which is the in-tree precedent for this shape: If-None-Match honouring 304, a bounded read with an explicit truncation error rather than a silent prefix, and no clearing of what is already installed when a fetch fails.
The signature travels in a header rather than the body so the body is the exact bytes that were signed. Reading it out of a JSON envelope would mean re-encoding before verification, and any difference in that round trip invalidates a signature that was actually fine.
func NewRemoteSource ¶
func NewRemoteSource(rawURL string) (*RemoteSource, error)
NewRemoteSource validates the URL and returns a source.
func (*RemoteSource) Describe ¶
func (r *RemoteSource) Describe() string
Describe implements Source.
type ResolvedEnvPolicy ¶
type ResolvedEnvPolicy struct {
Allow []string
Deny []string
MaxBytes int
MaxKeys int
BlockIteration bool
}
ResolvedEnvPolicy is the merged env policy (global + rule override).
func MergeEnvPolicy ¶
func MergeEnvPolicy(global EnvPolicy, rule CommandRule) ResolvedEnvPolicy
MergeEnvPolicy merges global policy with rule override (rule wins when set).
type ResourceLimits ¶
type ResourceLimits struct {
MaxMemoryMB int `yaml:"max_memory_mb"`
MemorySwapMaxMB int `yaml:"memory_swap_max_mb"`
CPUQuotaPercent int `yaml:"cpu_quota_percent"`
DiskReadBpsMax int64 `yaml:"disk_read_bps_max"`
DiskWriteBpsMax int64 `yaml:"disk_write_bps_max"`
NetBandwidthMbps int `yaml:"net_bandwidth_mbps"`
PidsMax int `yaml:"pids_max"`
CommandTimeout duration `yaml:"command_timeout"`
SessionTimeout duration `yaml:"session_timeout"`
IdleTimeout duration `yaml:"idle_timeout"`
}
type RuleMetadata ¶
type RuleMetadata struct {
RuleName string `yaml:"rule_name"`
Source string `yaml:"source"`
DBService string `yaml:"db_service,omitempty"`
BypassMode string `yaml:"bypass_mode,omitempty"`
Destination string `yaml:"destination,omitempty"`
}
RuleMetadata is non-enforcing metadata attached to generated policy rules. The policy engine ignores it for decisions; consumers use it to correlate generic rule names back to higher-level generated bundles.
type ShellCOpaqueMode ¶
type ShellCOpaqueMode int
ShellCOpaqueMode selects how opaque shell-c scripts are handled when the policy has a restrictive command rule. The zero value is Enforce, so engines constructed without explicit configuration keep the pre-#378 behavior.
const ( ShellCOpaqueEnforce ShellCOpaqueMode = iota // run only under active per-exec enforcement; else deny ShellCOpaqueAllow // run even without per-exec enforcement ShellCOpaqueDeny // always deny opaque scripts )
func ParseShellCOpaqueMode ¶
func ParseShellCOpaqueMode(s string) ShellCOpaqueMode
ParseShellCOpaqueMode maps a config string to a mode. Unknown/empty values map to Enforce (the safe default); config validation rejects bad values before this is reached in production.
type SignalRule ¶
type SignalRule struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Signals []string `yaml:"signals"` // Signal names, numbers, or groups (@fatal, @job)
Target SignalTargetSpec `yaml:"target"` // Who can receive the signal
Decision string `yaml:"decision"` // allow, deny, audit, approve, redirect, absorb
Fallback string `yaml:"fallback"` // Fallback decision if platform can't enforce
RedirectTo string `yaml:"redirect_to"` // For redirect: target signal
Message string `yaml:"message"`
Timeout duration `yaml:"timeout"`
}
SignalRule controls signal sending between processes.
type SignalTargetSpec ¶
type SignalTargetSpec struct {
Type string `yaml:"type"` // self, children, external, system, etc.
Pattern string `yaml:"pattern,omitempty"` // For process name matching
Min int `yaml:"min,omitempty"` // For pid_range
Max int `yaml:"max,omitempty"` // For pid_range
}
SignalTargetSpec defines the target of a signal rule.
type Source ¶
type Source interface {
// Fetch returns the current bundle, or ErrNotModified.
Fetch(ctx context.Context) (*Bundle, error)
// Describe names the source for logs and errors.
Describe() string
}
Source produces a policy bundle.
Splitting this out of Manager.loadLocked is what makes a remotely served policy possible without a second load path: verification, parsing and validation stay exactly where they were, so a remote policy inherits the same trust guarantee as a local one rather than an approximation of it.
type ThreatCheckResult ¶
ThreatCheckResult holds the outcome of a threat feed lookup.
type ThreatChecker ¶
type ThreatChecker interface {
Check(domain string) (ThreatCheckResult, bool)
}
ThreatChecker is an optional interface for domain-level threat feed lookups. threatfeed.PolicyAdapter satisfies this interface, bridging the Store to the policy engine.
type TorChecker ¶
type TorChecker interface {
EvalExecve(filename string, argv []string) (TorVerdict, bool)
EvalConnect(ip net.IP, port int) (TorVerdict, bool)
EvalOnionName(host string) (TorVerdict, bool)
}
TorChecker is the optional Tor coordinator. internal/tor.PolicyAdapter satisfies it. All methods return (verdict, true) only on a Tor match the caller should act on (deny short-circuits; audit attaches+continues).
type TorVerdict ¶
type TorVerdict struct {
Vector string
Mode string
Decision string // "deny" or "audit"
Target string
}
TorVerdict mirrors tor.Verdict at the policy layer (avoids a policy→tor import). tor.PolicyAdapter translates between the two.
type TransparentCommandsConfig ¶
type TransparentCommandsConfig struct {
Add []string `yaml:"add,omitempty"` // Additional transparent commands
Remove []string `yaml:"remove,omitempty"` // Remove from built-in defaults
}
TransparentCommandsConfig allows policy to override the built-in transparent command set. Transparent commands are wrappers/interpreters whose payload argument is the real command to evaluate (e.g., env, sudo, ld-linux).
type UnixSocketRule ¶
type UnixSocketRule struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Paths []string `yaml:"paths"`
Operations []string `yaml:"operations"` // connect|bind|listen|sendto; empty = all
Decision string `yaml:"decision"` // allow|deny|approve
Message string `yaml:"message"`
Timeout duration `yaml:"timeout"`
}
UnixSocketRule controls AF_UNIX socket operations such as connect/bind/listen. Paths refer to filesystem socket paths; abstract namespace sockets use "@name" (no leading slash).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ancestry provides process ancestry tracking and taint propagation for parent-conditional policy enforcement.
|
Package ancestry provides process ancestry tracking and taint propagation for parent-conditional policy enforcement. |
|
envshim
|
|
|
test_helper
command
|
|
|
Package identity provides cross-platform process identification.
|
Package identity provides cross-platform process identification. |
|
Package pattern provides pattern matching for process identification.
|
Package pattern provides pattern matching for process identification. |