nlpolicy

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxCommandsPerList = 200
	MaxPathsPerList    = 200
	MaxAllowedHosts    = 200
	MaxBlockedPorts    = 100
	MaxExplanationLen  = 2000
	MaxCommandLen      = 200
	MaxPathLen         = 4096
	MaxHostLen         = 253 // RFC 1035 maximum domain name length
)

Bounds on the compiled output. A policy is produced by an LLM, so its size is not inherently limited; these caps stop a single policy from generating a multi-megabyte Rego module or thousands of iptables rules.

View Source
const MaxNaturalLanguageLen = 4000

MaxNaturalLanguageLen bounds the free-text policy description a caller may submit.

The description is forwarded verbatim to an LLM, so an unbounded field lets an authenticated caller run up the deployment's inference bill — and, with a large enough prompt, hold an API worker open for the length of the completion. 4000 characters is far more than any real policy needs.

Variables

View Source
var ErrDescriptionTooLong = errors.New("policy description too long")

ErrDescriptionTooLong is returned for a policy description over the limit.

View Source
var ErrUnsafePolicy = errors.New("unsafe policy")

ErrUnsafePolicy is returned when a policy contains a value that cannot be safely compiled into Rego, iptables rules or a Docker configuration.

View Source
var PolicyTemplates = []PolicyTemplate{
	{
		Name:        "python-data-science",
		Description: "Python environment for data analysis with network access to PyPI and GitHub",
		Category:    "data-science",
		Template: `Python data science environment.

Network access:
- Allow pypi.org for package installation
- Allow github.com for repository access
- Block all other outbound connections

Resources:
- 2 CPU cores maximum
- 4GB memory maximum
- 30 minute timeout

Commands:
- Allow python, pip, git, jupyter
- Block curl, wget, netcat
- No sudo or privileged operations

Files:
- Full access to /workspace
- No access to /etc, /root, or /proc`,
	},
	{
		Name:        "nodejs-web-app",
		Description: "Node.js environment for web application development",
		Category:    "web-dev",
		Template: `Node.js web application environment.

Network access:
- Allow registry.npmjs.org for packages
- Allow github.com for repositories
- Allow port 3000-9000 for development servers
- Block all other outbound connections

Resources:
- 2 CPU cores maximum
- 2GB memory maximum
- 60 minute timeout

Commands:
- Allow node, npm, npx, git
- Block curl, wget (use npm for dependencies)
- No sudo or privileged operations

Files:
- Full access to /workspace
- No access to /etc, /root`,
	},
	{
		Name:        "security-audit",
		Description: "Restricted environment for security testing and auditing",
		Category:    "security",
		Template: `Security audit environment with strict isolation.

Network access:
- Completely disabled (air-gapped)

Resources:
- 1 CPU core maximum
- 1GB memory maximum
- 15 minute timeout

Commands:
- Allow only: ls, cat, grep, find, sha256sum
- Block all network tools
- Block all compilers and interpreters
- No sudo or privileged operations

Files:
- Read-only access to /workspace
- No write operations
- No access to /etc, /root, /proc`,
	},
	{
		Name:        "unrestricted-dev",
		Description: "Minimal restrictions for trusted development workflows",
		Category:    "development",
		Template: `Development environment with minimal restrictions.

Network access:
- Enabled for all domains
- All ports allowed

Resources:
- 4 CPU cores maximum
- 8GB memory maximum
- 120 minute timeout

Commands:
- All commands allowed except sudo
- No privileged operations

Files:
- Full access to /workspace
- No access to /etc, /root, /proc`,
	},
}

Common policy templates

Functions

func ValidateNaturalLanguage added in v0.3.2

func ValidateNaturalLanguage(s string) error

ValidateNaturalLanguage bounds a free-text policy description before it reaches a parser.

Types

type CommandPolicy

type CommandPolicy struct {
	AllowedCommands []string `json:"allowed_commands"` // Commands that are allowed (nil = allow all)
	BlockedCommands []string `json:"blocked_commands"` // Commands that are explicitly blocked
	BlockSudo       bool     `json:"block_sudo"`       // Whether to block sudo/su
	BlockNetwork    bool     `json:"block_network"`    // Whether to block network commands (curl, wget, etc)
}

CommandPolicy defines which commands can be executed

type CompiledPolicy

type CompiledPolicy struct {
	SourcePolicy *Policy       `json:"source_policy"`
	OPAPolicy    string        `json:"opa_policy"`
	DockerConfig *DockerConfig `json:"docker_config"`
	NetworkRules *NetworkRules `json:"network_rules"`
}

CompiledPolicy contains all compiled policy formats

type Compiler

type Compiler struct{}

Compiler converts structured Policy to executable formats

func NewCompiler

func NewCompiler() *Compiler

NewCompiler creates a new policy compiler

func (*Compiler) CompileAll

func (c *Compiler) CompileAll(policy *Policy) (*CompiledPolicy, error)

CompileAll compiles policy to all formats

func (*Compiler) CompileToDockerConfig

func (c *Compiler) CompileToDockerConfig(policy *Policy) (*DockerConfig, error)

CompileToDockerConfig converts Policy to Docker container constraints

func (*Compiler) CompileToNetworkRules

func (c *Compiler) CompileToNetworkRules(policy *Policy) (*NetworkRules, error)

CompileToNetworkRules converts Policy to iptables/network rules

func (*Compiler) CompileToOPA

func (c *Compiler) CompileToOPA(policy *Policy) (string, error)

CompileToOPA converts Policy to OPA Rego policy

type DockerConfig

type DockerConfig struct {
	CPULimit       float64  `json:"cpu_limit"`
	MemoryLimitMB  int      `json:"memory_limit_mb"`
	NetworkMode    string   `json:"network_mode"` // "none", "bridge"
	CapAdd         []string `json:"cap_add"`      // Capabilities to add
	CapDrop        []string `json:"cap_drop"`     // Capabilities to drop
	ReadOnlyRootfs bool     `json:"read_only_rootfs"`
}

DockerConfig represents Docker container configuration

type FilePolicy

type FilePolicy struct {
	AllowedPaths []string `json:"allowed_paths"` // Paths that can be accessed (nil = allow all in /workspace)
	BlockedPaths []string `json:"blocked_paths"` // Paths that are explicitly blocked
	ReadOnly     bool     `json:"read_only"`     // Whether filesystem is read-only
}

FilePolicy defines filesystem access rules

type MockParser

type MockParser struct{}

MockParser is a simple parser for testing that doesn't require API keys

func NewMockParser

func NewMockParser() *MockParser

NewMockParser creates a mock parser for testing

func (*MockParser) Parse

func (m *MockParser) Parse(ctx context.Context, naturalLanguage string) (*Policy, error)

Parse returns a predefined policy

func (*MockParser) Validate

func (m *MockParser) Validate(ctx context.Context, naturalLanguage string) (*ValidationResult, error)

Validate always returns valid for mock parser

type NetworkPolicy

type NetworkPolicy struct {
	Enabled       bool     `json:"enabled"`        // Whether network is enabled at all
	AllowedHosts  []string `json:"allowed_hosts"`  // Allowlist of domains/IPs (empty = allow all)
	BlockedPorts  []int    `json:"blocked_ports"`  // Ports to block (e.g. [25, 587] for SMTP)
	AllowDNS      bool     `json:"allow_dns"`      // Whether to allow DNS lookups
	AllowLoopback bool     `json:"allow_loopback"` // Whether to allow localhost connections
}

NetworkPolicy defines network access rules

type NetworkRules

type NetworkRules struct {
	Enabled       bool     `json:"enabled"`
	AllowedHosts  []string `json:"allowed_hosts"`
	BlockedPorts  []int    `json:"blocked_ports"`
	AllowDNS      bool     `json:"allow_dns"`
	IptablesRules []string `json:"iptables_rules"` // Generated iptables commands
}

NetworkRules represents network access rules

type OpenAIParser

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

OpenAIParser implements Parser using OpenAI's GPT models

func NewOpenAIParser

func NewOpenAIParser(apiKey string) *OpenAIParser

NewOpenAIParser creates a new OpenAI-based policy parser

func (*OpenAIParser) Parse

func (p *OpenAIParser) Parse(ctx context.Context, naturalLanguage string) (*Policy, error)

Parse converts natural language to structured policy

func (*OpenAIParser) Validate

func (p *OpenAIParser) Validate(ctx context.Context, naturalLanguage string) (*ValidationResult, error)

Validate checks if a natural language policy is valid

type Parser

type Parser interface {
	// Parse converts natural language policy description to structured Policy
	Parse(ctx context.Context, naturalLanguage string) (*Policy, error)

	// Validate checks if a natural language policy is valid and actionable
	Validate(ctx context.Context, naturalLanguage string) (*ValidationResult, error)
}

Parser converts natural language to structured policy

type Policy

type Policy struct {
	ResourceLimits ResourceLimits `json:"resource_limits"`
	NetworkPolicy  NetworkPolicy  `json:"network_policy"`
	CommandPolicy  CommandPolicy  `json:"command_policy"`
	FilePolicy     FilePolicy     `json:"file_policy"`
	Explanation    string         `json:"explanation"` // Human-readable summary of what the policy does
	Warnings       []string       `json:"warnings"`    // Potential issues or recommendations
	GeneratedAt    time.Time      `json:"generated_at"`
}

Policy represents a structured security policy parsed from natural language

func (*Policy) Validate added in v0.3.1

func (p *Policy) Validate() error

Validate checks that a policy can be compiled without injecting syntax into any of the three output formats.

A Policy is untrusted input: it is produced by an LLM from a user-supplied prompt, so a prompt-injection attack reaches these fields directly. Every value that is interpolated into generated code is checked here rather than at each interpolation site.

type PolicyTemplate

type PolicyTemplate struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Template    string `json:"template"` // Natural language template
	Category    string `json:"category"` // e.g. "data-science", "web-dev", "security-audit"
}

PolicyTemplate is a pre-defined policy for common use cases

func GetTemplate

func GetTemplate(name string) *PolicyTemplate

GetTemplate returns a template by name

func ListTemplates

func ListTemplates(category string) []PolicyTemplate

ListTemplates returns all available templates, optionally filtered by category

type ResourceLimits

type ResourceLimits struct {
	CPULimit       float64 `json:"cpu_limit"`       // CPU cores (e.g. 2.0)
	MemoryLimitMB  int     `json:"memory_limit_mb"` // Memory in MB (e.g. 4096)
	TimeoutSeconds int     `json:"timeout_seconds"` // Session timeout (e.g. 1800)
	MaxProcesses   int     `json:"max_processes"`   // Max concurrent processes (0 = unlimited)
}

ResourceLimits defines compute resource constraints

type ValidationResult

type ValidationResult struct {
	Valid       bool     `json:"valid"`
	Errors      []string `json:"errors"`      // Blocking issues
	Warnings    []string `json:"warnings"`    // Non-blocking recommendations
	Suggestions []string `json:"suggestions"` // Helpful improvements
}

ValidationResult contains validation feedback

Jump to

Keyboard shortcuts

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