policy

package
v0.0.0-...-b198e9d Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PolicyDataFromStruct

func PolicyDataFromStruct(pd *PolicyData) (map[string]interface{}, error)

PolicyDataFromStruct converts a PolicyData struct to a map for OPA.

Types

type AgentContext

type AgentContext struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Capabilities []string `json:"capabilities"`
	Model        string   `json:"model"`
	Publisher    string   `json:"publisher"`
	Tags         []string `json:"tags"`
}

AgentContext contains information about the agent making the request.

type CacheConfig

type CacheConfig struct {
	Enabled    bool
	TTL        time.Duration
	MaxEntries int
}

CacheConfig holds cache configuration.

type CacheStats

type CacheStats struct {
	L1Hits  int64
	L2Hits  int64
	Misses  int64
	Entries int
	HitRate float64
	Evicted int64
}

CacheStats contains cache performance statistics.

type DecisionCache

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

DecisionCache provides multi-tier caching for policy decisions.

func NewDecisionCache

func NewDecisionCache(cfg CacheConfig) *DecisionCache

NewDecisionCache creates a new decision cache.

func (*DecisionCache) ComputeKey

func (c *DecisionCache) ComputeKey(input *PolicyInput) string

ComputeKey generates a cache key from the policy input. Key format: agent_id:tool:capabilities_hash

func (*DecisionCache) Get

func (c *DecisionCache) Get(key string) (*PolicyDecision, bool, string)

Get retrieves a cached decision.

func (*DecisionCache) Invalidate

func (c *DecisionCache) Invalidate()

Invalidate removes all cached entries (e.g., on policy reload).

func (*DecisionCache) Set

func (c *DecisionCache) Set(key string, decision *PolicyDecision)

Set stores a decision in the cache.

func (*DecisionCache) Stats

func (c *DecisionCache) Stats() CacheStats

Stats returns cache statistics.

type Engine

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

Engine provides policy evaluation using embedded OPA.

func NewEngine

func NewEngine(cfg EngineConfig) *Engine

NewEngine creates a new policy engine.

func (*Engine) Evaluate

func (e *Engine) Evaluate(ctx context.Context, input *PolicyInput) (*EvaluationResult, error)

Evaluate evaluates a policy decision for the given input.

func (*Engine) IsAllowed

func (e *Engine) IsAllowed(ctx context.Context, input *PolicyInput) (bool, *EvaluationResult, error)

IsAllowed is a convenience method to check if a request is allowed.

func (*Engine) IsReady

func (e *Engine) IsReady() bool

IsReady returns true if the policy engine is initialized and ready.

func (*Engine) LoadPolicies

func (e *Engine) LoadPolicies(ctx context.Context, modules map[string]string) error

LoadPolicies compiles and loads Rego policies.

func (*Engine) Mode

func (e *Engine) Mode() string

Mode returns the current policy mode.

func (*Engine) SetPolicyData

func (e *Engine) SetPolicyData(data map[string]interface{}) error

SetPolicyData updates the runtime policy data.

func (*Engine) Stats

func (e *Engine) Stats() EngineStats

Stats returns engine statistics.

type EngineConfig

type EngineConfig struct {
	Mode        string // "enforce" or "audit"
	Enabled     bool
	CacheConfig CacheConfig
}

EngineConfig holds configuration for the policy engine.

type EngineStats

type EngineStats struct {
	Evaluations   int64
	EvalErrors    int64
	AvgEvalTimeMs float64
	CacheStats    CacheStats
}

EngineStats contains policy engine statistics.

type EnvironmentContext

type EnvironmentContext struct {
	Timestamp   time.Time `json:"timestamp"`
	SourceIP    string    `json:"source_ip"`
	Environment string    `json:"environment"`
	ProxyRegion string    `json:"proxy_region"`
}

EnvironmentContext contains information about the execution environment.

type EvaluationResult

type EvaluationResult struct {
	Decision   *PolicyDecision
	Input      *PolicyInput
	EvalTime   time.Duration
	CacheHit   bool
	CacheTier  string // "L1", "L2", or ""
	PolicyMode string // "audit" or "enforce"
}

EvaluationResult contains the full result of a policy evaluation.

type IdentityContext

type IdentityContext struct {
	Verified     bool      `json:"verified"`
	DID          string    `json:"did"`
	SignatureAlg string    `json:"signature_alg"`
	IssuedAt     time.Time `json:"issued_at"`
	HasLogProof  bool      `json:"has_log_proof"`
}

IdentityContext contains verified identity information from AgentFacts.

type InputBuilder

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

InputBuilder helps construct PolicyInput from various sources.

func NewInputBuilder

func NewInputBuilder() *InputBuilder

NewInputBuilder creates a new InputBuilder with defaults.

func (*InputBuilder) Build

func (b *InputBuilder) Build() *PolicyInput

Build returns the constructed PolicyInput.

func (*InputBuilder) WithAgent

func (b *InputBuilder) WithAgent(id, name string, capabilities []string) *InputBuilder

WithAgent sets the agent context.

func (*InputBuilder) WithAgentDetails

func (b *InputBuilder) WithAgentDetails(model, publisher string, tags []string) *InputBuilder

WithAgentDetails sets additional agent details.

func (*InputBuilder) WithEnvironment

func (b *InputBuilder) WithEnvironment(sourceIP, environment, region string) *InputBuilder

WithEnvironment sets the environment context.

func (*InputBuilder) WithIdentity

func (b *InputBuilder) WithIdentity(verified bool, did string) *InputBuilder

WithIdentity sets the identity context.

func (*InputBuilder) WithRequest

func (b *InputBuilder) WithRequest(method, tool string, arguments map[string]interface{}) *InputBuilder

WithRequest sets the request context.

func (*InputBuilder) WithSession

func (b *InputBuilder) WithSession(id string, requestCount int, startedAt time.Time) *InputBuilder

WithSession sets the session context.

type Loader

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

Loader handles loading policy files and data.

func NewLoader

func NewLoader(policyDir, dataFile string, opts ...LoaderOption) *Loader

NewLoader creates a new policy loader.

func (*Loader) LoadAndInitialize

func (l *Loader) LoadAndInitialize(ctx context.Context, engine *Engine) error

LoadAndInitialize loads policies and data, then initializes the engine.

func (*Loader) LoadPolicies

func (l *Loader) LoadPolicies() (map[string]string, error)

LoadPolicies loads all policy files (.rego and compiled .json) from the policy directory.

func (*Loader) LoadPolicyData

func (l *Loader) LoadPolicyData() (map[string]interface{}, error)

LoadPolicyData loads policy data from the JSON file.

func (*Loader) LoadPolicyDataStruct

func (l *Loader) LoadPolicyDataStruct() (*PolicyData, error)

LoadPolicyDataStruct loads policy data as a typed struct.

func (*Loader) ValidatePolicies

func (l *Loader) ValidatePolicies(ctx context.Context) error

ValidatePolicies checks if policies can be loaded and compiled without errors.

func (*Loader) WatchForChanges

func (l *Loader) WatchForChanges(ctx context.Context, engine *Engine, onChange func()) error

WatchForChanges monitors policy files for changes (placeholder for future implementation).

type LoaderOption

type LoaderOption func(*Loader)

LoaderOption configures the loader.

func WithJSONPolicyDir

func WithJSONPolicyDir(dir string) LoaderOption

WithJSONPolicyDir sets the JSON policy directory.

type PolicyData

type PolicyData struct {
	ToolCapabilities      map[string]string `json:"tool_capabilities"`
	RateLimits            map[string]int    `json:"rate_limits"`
	BlockedTools          []string          `json:"blocked_tools"`
	BlockedAgents         []string          `json:"blocked_agents"`
	BlockedDIDs           []string          `json:"blocked_dids"`
	AllowedDIDs           []string          `json:"allowed_dids"`
	TrustedPublishers     []string          `json:"trusted_publishers"`
	IdentityRequiredTools []string          `json:"identity_required_tools"`
	PIITools              []string          `json:"pii_tools"`
	BlockedModelsForPII   []string          `json:"blocked_models_for_pii"`
}

PolicyData contains runtime policy data loaded from JSON.

type PolicyDecision

type PolicyDecision struct {
	Allow       bool               `json:"allow"`
	Violations  []string           `json:"violations"`
	MatchedRule string             `json:"matched_rule"`
	Obligations []PolicyObligation `json:"obligations,omitempty"`
}

PolicyDecision is the output from OPA policy evaluation.

type PolicyInput

type PolicyInput struct {
	Agent    AgentContext       `json:"agent"`
	Request  RequestContext     `json:"request"`
	Session  SessionContext     `json:"session"`
	Identity IdentityContext    `json:"identity"`
	Context  EnvironmentContext `json:"context"`
}

PolicyInput is the input structure sent to OPA for policy evaluation. This matches the schema defined in the spec section 4.2.

type PolicyObligation

type PolicyObligation struct {
	Action string            `json:"action"` // "log", "alert", "rate_limit"
	Params map[string]string `json:"params"`
}

PolicyObligation represents an action that must be taken (e.g., log, alert).

type RequestContext

type RequestContext struct {
	Method    string                 `json:"method"`
	Tool      string                 `json:"tool"`
	Arguments map[string]interface{} `json:"arguments"`
	Intent    string                 `json:"intent"`
}

RequestContext contains information about the request being made.

type SessionContext

type SessionContext struct {
	ID               string    `json:"id"`
	RequestCount     int       `json:"request_count"`
	StartedAt        time.Time `json:"started_at"`
	CumulativeReads  int       `json:"cumulative_reads"`
	CumulativeWrites int       `json:"cumulative_writes"`
}

SessionContext contains information about the current session.

Directories

Path Synopsis
Package compiler provides JSON to Rego policy compilation.
Package compiler provides JSON to Rego policy compilation.

Jump to

Keyboard shortcuts

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