entities

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package entities provides core domain entities for the SDK. These are general-purpose types used across all SDK operations. Domain-specific types like Evidence belong in consuming applications (e.g., Reglet).

Package entities provides core domain entities for the SDK. These are general-purpose types used across all SDK operations. Domain-specific types like Evidence belong in consuming applications (e.g., Reglet).

Package entities defines core domain types and wire protocol structures. These types serve dual purpose: domain entities AND JSON wire format DTOs.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Broad filesystem patterns that grant excessive access
	BroadFilesystemPatterns = []string{
		"**", "/**", "read:**", "write:**", "read:/", "write:/",
		"read:/etc/**", "write:/etc/**",
		"read:/root/**", "write:/root/**",
		"read:/home/**", "write:/home/**",
	}

	// Shell interpreters that allow arbitrary command execution
	DangerousShells = []string{
		"bash", "sh", "zsh", "fish",
		"/bin/bash", "/bin/sh", "/bin/zsh",
	}

	// Script interpreters (matches base + versioned variants)
	DangerousInterpreters = []string{
		"python", "perl", "ruby", "node", "nodejs",
		"php", "lua", "awk", "gawk", "tclsh",
	}

	// Broad environment variable patterns
	BroadEnvPatterns = []string{"*", "AWS_*", "AZURE_*", "GCP_*"}
)

Dangerous patterns (security domain knowledge)

Functions

This section is empty.

Types

type Capability

type Capability struct {
	// Category is the capability category (e.g., "network", "fs", "exec").
	Category string `json:"kind"`

	// Resource is the specific resource within the category.
	Resource string `json:"pattern"`

	// Action is the permitted action (e.g., "read", "write", "connect").
	Action string `json:"action,omitempty"`
}

Capability represents a permission or capability required by an SDK operation. Capabilities follow the format "category:resource" (e.g., "network:outbound:443").

func ExecCapabilityLegacy

func ExecCapabilityLegacy(command string) Capability

ExecCapabilityLegacy creates an exec capability.

func FileSystemCapabilityLegacy

func FileSystemCapabilityLegacy(resource string) Capability

FileSystemCapabilityLegacy creates a filesystem capability.

func NetworkCapabilityLegacy

func NetworkCapabilityLegacy(resource string) Capability

NetworkCapabilityLegacy creates a network capability.

func NewCapability

func NewCapability(category, resource string) Capability

NewCapability creates a new Capability with the given category and resource.

func (Capability) String

func (c Capability) String() string

String returns the capability in "category:resource" format.

func (Capability) WithAction

func (c Capability) WithAction(action string) Capability

WithAction returns a copy of the Capability with the action set.

type CapabilityRequest

type CapabilityRequest struct {
	Rule        interface{}
	Kind        string
	Description string
	RiskLevel   RiskLevel
}

CapabilityRequest represents a request for a capability to be granted (e.g. via prompt).

type Config

type Config struct {
	// LogLevel is the logging verbosity level (e.g., "debug", "info", "warn", "error").
	LogLevel string `json:"log_level,omitempty"`

	// DefaultTimeout is the default timeout for operations.
	DefaultTimeout time.Duration `json:"default_timeout"`

	// MaxRetries is the maximum number of retry attempts for failed operations.
	MaxRetries int `json:"max_retries"`

	// EnableLogging controls whether SDK operations are logged.
	EnableLogging bool `json:"enable_logging"`
}

Config represents SDK configuration settings. These settings control SDK behavior across all operations.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default SDK configuration. These defaults align with constitution requirements for secure-by-default.

func NewConfig

func NewConfig(opts ...ConfigOption) Config

NewConfig creates a new Config with the given options.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for configuring SDK settings.

func WithDefaultTimeout

func WithDefaultTimeout(d time.Duration) ConfigOption

WithDefaultTimeout sets the default timeout for operations.

func WithLogLevel

func WithLogLevel(level string) ConfigOption

WithLogLevel sets the logging verbosity level.

func WithLogging

func WithLogging(enabled bool) ConfigOption

WithLogging enables or disables logging.

func WithMaxRetries

func WithMaxRetries(n int) ConfigOption

WithMaxRetries sets the maximum number of retry attempts.

type ContextWire

type ContextWire struct {
	Deadline  *time.Time `json:"deadline,omitempty"`
	RequestID string     `json:"request_id,omitempty"`
	TimeoutMs int64      `json:"timeout_ms,omitempty"`
	Canceled  bool       `json:"canceled,omitempty"`
}

ContextWire is the JSON wire format for context.Context propagation.

type DNSRequest

type DNSRequest struct {
	Hostname   string      `json:"hostname"`
	Type       string      `json:"type"`
	Nameserver string      `json:"nameserver,omitempty"`
	Context    ContextWire `json:"context"`
}

DNSRequest is the JSON wire format for a DNS lookup request.

type DNSResponse

type DNSResponse struct {
	Error     *ErrorDetail `json:"error,omitempty"`
	Records   []string     `json:"records,omitempty"`
	MXRecords []MXRecord   `json:"mx_records,omitempty"`
}

DNSResponse is the JSON wire format for a DNS lookup response.

type EnvironmentCapability

type EnvironmentCapability struct {
	Variables []string `json:"vars" yaml:"vars" jsonschema:"required"`
}

EnvironmentCapability defines permitted environment variables.

type EnvironmentRequest

type EnvironmentRequest struct {
	Variable string
}

EnvironmentRequest represents a runtime request to access environment variables.

type ErrorDetail

type ErrorDetail struct {
	// Wrapped contains a wrapped error for error chains.
	Wrapped *ErrorDetail `json:"wrapped,omitempty"`

	// Details contains additional error context.
	Details map[string]any `json:"details,omitempty"`

	// Message is a human-readable error description.
	Message string `json:"message"`

	// Type categorizes the error.
	Type string `json:"type"`

	// Code is a machine-readable error code.
	Code string `json:"code"`

	// Stack contains the stack trace for panic errors.
	Stack []byte `json:"stack,omitempty"`

	// IsTimeout indicates if this was a timeout error.
	IsTimeout bool `json:"is_timeout,omitempty"`

	// IsNotFound indicates if this was a "not found" error.
	IsNotFound bool `json:"is_not_found,omitempty"`
}

ErrorDetail provides structured error information. Used across SDK operations and as wire protocol error format. Error Types: "network", "timeout", "config", "panic", "capability", "validation", "internal"

func NewErrorDetail

func NewErrorDetail(errorType, message string) *ErrorDetail

NewErrorDetail creates a new ErrorDetail with the given type and message.

func (*ErrorDetail) Error

func (e *ErrorDetail) Error() string

Error implements the error interface.

func (*ErrorDetail) WithCode

func (e *ErrorDetail) WithCode(code string) *ErrorDetail

WithCode returns a copy of the ErrorDetail with the given code attached.

func (*ErrorDetail) WithDetails

func (e *ErrorDetail) WithDetails(details map[string]any) *ErrorDetail

WithDetails returns a copy of the ErrorDetail with the given details attached.

type ExecCapability

type ExecCapability struct {
	Commands []string `json:"commands" yaml:"commands" jsonschema:"required"`
}

ExecCapability defines permitted command execution.

type ExecRequest

type ExecRequest struct {
	Command string
}

ExecRequest represents a runtime request to execute a command.

type ExecResponse

type ExecResponse struct {
	Error      *ErrorDetail `json:"error,omitempty"`
	Stdout     string       `json:"stdout"`
	Stderr     string       `json:"stderr"`
	ExitCode   int          `json:"exit_code"`
	DurationMs int64        `json:"duration_ms,omitempty"`
	IsTimeout  bool         `json:"is_timeout,omitempty"`
}

ExecResponse is the JSON wire format for an exec response.

type FileSystemCapability

type FileSystemCapability struct {
	Rules []FileSystemRule `json:"rules" yaml:"rules" jsonschema:"required"`
}

FileSystemCapability defines permitted filesystem access.

type FileSystemRequest

type FileSystemRequest struct {
	Path      string
	Operation string // "read", "write"
}

FileSystemRequest represents a runtime request to access the filesystem.

type FileSystemRule

type FileSystemRule struct {
	Read  []string `json:"read,omitempty" yaml:"read,omitempty"`
	Write []string `json:"write,omitempty" yaml:"write,omitempty"`
}

FileSystemRule defines a single filesystem access rule.

type GrantSet

type GrantSet struct {
	Network *NetworkCapability     `json:"network,omitempty" yaml:"network,omitempty"`
	FS      *FileSystemCapability  `json:"fs,omitempty" yaml:"fs,omitempty"`
	Env     *EnvironmentCapability `json:"env,omitempty" yaml:"env,omitempty"`
	Exec    *ExecCapability        `json:"exec,omitempty" yaml:"exec,omitempty"`
	KV      *KeyValueCapability    `json:"kv,omitempty" yaml:"kv,omitempty"`
}

GrantSet is a structured collection of rules representing all capabilities granted to a plugin.

func (*GrantSet) IsEmpty

func (g *GrantSet) IsEmpty() bool

IsEmpty returns true if no capabilities are present.

func (*GrantSet) Merge

func (g *GrantSet) Merge(other *GrantSet)

Merge unions two grant sets.

type HTTPRequest

type HTTPRequest struct {
	Headers map[string][]string `json:"headers,omitempty"`
	Method  string              `json:"method"`
	URL     string              `json:"url"`
	Body    string              `json:"body,omitempty"`
	Context ContextWire         `json:"context"`
}

HTTPRequest is the JSON wire format for an HTTP request.

type HTTPResponse

type HTTPResponse struct {
	Headers       map[string][]string `json:"headers,omitempty"`
	Error         *ErrorDetail        `json:"error,omitempty"`
	Body          string              `json:"body,omitempty"`
	StatusCode    int                 `json:"status_code"`
	BodyTruncated bool                `json:"body_truncated,omitempty"`
}

HTTPResponse is the JSON wire format for an HTTP response.

type KeyValueCapability

type KeyValueCapability struct {
	Rules []KeyValueRule `json:"rules" yaml:"rules" jsonschema:"required"`
}

KeyValueCapability defines permitted key-value store access.

type KeyValueRequest

type KeyValueRequest struct {
	Key       string
	Operation string // "read", "write"
}

KeyValueRequest represents a runtime request to access the key-value store.

type KeyValueRule

type KeyValueRule struct {
	Operation string   `json:"op" yaml:"op" jsonschema:"required,enum=read,enum=write,enum=read-write"`
	Keys      []string `json:"keys" yaml:"keys" jsonschema:"required"`
}

KeyValueRule defines a single key-value access rule.

type MXRecord

type MXRecord struct {
	Host string `json:"host"`
	Pref uint16 `json:"pref"`
}

MXRecord represents a single MX record.

type Metadata

type Metadata struct {
	Name           string       `json:"name"`
	Version        string       `json:"version"`
	Description    string       `json:"description"`
	SDKVersion     string       `json:"sdk_version,omitempty"`
	MinHostVersion string       `json:"min_host_version,omitempty"`
	Capabilities   []Capability `json:"capabilities"`
}

Metadata contains information about the plugin.

type NetworkCapability

type NetworkCapability struct {
	Rules []NetworkRule `json:"rules" yaml:"rules" jsonschema:"required"`
}

NetworkCapability defines permitted network access.

type NetworkRequest

type NetworkRequest struct {
	Host string
	Port int
}

NetworkRequest represents a runtime request to access the network.

type NetworkRule

type NetworkRule struct {
	Hosts []string `json:"hosts" yaml:"hosts" jsonschema:"required"`
	Ports []string `json:"ports" yaml:"ports" jsonschema:"required"` // "80", "8000-9000", "*"
}

NetworkRule defines a single network access rule.

type PluginManifest

type PluginManifest struct {
	Capabilities *GrantSet `json:"capabilities,omitempty" yaml:"capabilities,omitempty"`
	Name         string    `json:"name" yaml:"name"`
	Version      string    `json:"version" yaml:"version"`
	Description  string    `json:"description,omitempty" yaml:"description,omitempty"`
}

PluginManifest represents the root configuration of a plugin.

type Result

type Result struct {
	// Timestamp is when this result was created.
	// This is automatically set by the SDK when the result is returned.
	Timestamp time.Time `json:"timestamp"`

	// Data contains operation-specific result data.
	// The structure depends on the operation type (DNS, HTTP, TCP, etc.).
	Data map[string]any `json:"data,omitempty"`

	// Metadata contains execution metadata (timing, versions, etc.).
	Metadata *RunMetadata `json:"metadata,omitempty"`

	// Error contains structured error information if Status is Error.
	Error *ErrorDetail `json:"error,omitempty"`

	// Status indicates whether the operation succeeded, failed, or errored.
	Status ResultStatus `json:"status"`

	// Message provides a human-readable description of the result.
	Message string `json:"message,omitempty"`
}

Result represents the general-purpose outcome of an SDK operation. This is the SDK's return type for check functions - consuming applications like Reglet map Result to their domain-specific types (e.g., Evidence).

func ResultError

func ResultError(err *ErrorDetail) Result

ResultError creates an error Result with the given error details. Use this when the operation could not complete due to an error.

func ResultFailure

func ResultFailure(message string, data map[string]any) Result

ResultFailure creates a failure Result with the given message and data. Use this when the operation completed but the check did not pass.

func ResultSuccess

func ResultSuccess(message string, data map[string]any) Result

ResultSuccess creates a successful Result with the given message and data.

func (Result) IsError

func (r Result) IsError() bool

IsError returns true if the result indicates an error.

func (Result) IsFailure

func (r Result) IsFailure() bool

IsFailure returns true if the result indicates failure.

func (Result) IsSuccess

func (r Result) IsSuccess() bool

IsSuccess returns true if the result indicates success.

func (Result) WithMetadata

func (r Result) WithMetadata(m *RunMetadata) Result

WithMetadata returns a copy of the Result with the given metadata attached.

type ResultStatus

type ResultStatus string

ResultStatus represents the outcome status of an SDK operation.

const (
	// ResultStatusSuccess indicates the operation completed successfully.
	ResultStatusSuccess ResultStatus = "success"

	// ResultStatusFailure indicates the operation failed.
	ResultStatusFailure ResultStatus = "failure"

	// ResultStatusError indicates an error occurred during the operation.
	ResultStatusError ResultStatus = "error"
)

type RiskAssessor

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

RiskAssessor evaluates the security risk of capabilities.

func NewRiskAssessor

func NewRiskAssessor(opts ...RiskAssessorOption) *RiskAssessor

NewRiskAssessor creates a new RiskAssessor with the given options.

func (*RiskAssessor) AssessGrantSet

func (r *RiskAssessor) AssessGrantSet(g *GrantSet) RiskLevel

AssessGrantSet evaluates the overall risk level of a GrantSet.

func (*RiskAssessor) DescribeRisks

func (r *RiskAssessor) DescribeRisks(g *GrantSet) []string

DescribeRisks returns a list of human-readable risk descriptions.

type RiskAssessorOption

type RiskAssessorOption func(*riskAssessorConfig)

RiskAssessorOption configures a RiskAssessor instance.

func WithCustomBroadPatterns

func WithCustomBroadPatterns(kind string, patterns []string) RiskAssessorOption

WithCustomBroadPatterns adds additional patterns considered "broad" for a kind.

type RiskLevel

type RiskLevel int

RiskLevel represents the security risk level of a capability or grant set.

const (
	RiskLevelLow    RiskLevel = iota // Specific, narrow permissions
	RiskLevelMedium                  // Network access, sensitive reads
	RiskLevelHigh                    // Broad permissions, arbitrary execution
)

func (RiskLevel) String

func (r RiskLevel) String() string

String returns the human-readable name of the risk level.

type RunMetadata

type RunMetadata struct {
	// StartTime is when the operation started.
	StartTime time.Time `json:"start_time"`

	// EndTime is when the operation completed.
	EndTime time.Time `json:"end_time"`

	// SDKVersion is the version of the SDK that executed the operation.
	SDKVersion string `json:"sdk_version,omitempty"`

	// PluginID identifies the plugin that requested the operation (if known).
	PluginID string `json:"plugin_id,omitempty"`

	// Duration is the total execution time.
	Duration time.Duration `json:"duration_ns"`
}

RunMetadata contains execution metadata for SDK operations.

func NewRunMetadata

func NewRunMetadata(start, end time.Time) *RunMetadata

NewRunMetadata creates a new RunMetadata with the given start and end times.

func (*RunMetadata) WithPluginID

func (m *RunMetadata) WithPluginID(pluginID string) *RunMetadata

WithPluginID returns a copy of the RunMetadata with the plugin ID set.

func (*RunMetadata) WithSDKVersion

func (m *RunMetadata) WithSDKVersion(version string) *RunMetadata

WithSDKVersion returns a copy of the RunMetadata with the SDK version set.

type SMTPRequest

type SMTPRequest struct {
	Host      string      `json:"host"`
	Port      string      `json:"port"`
	Context   ContextWire `json:"context"`
	TimeoutMs int         `json:"timeout_ms,omitempty"`
	TLS       bool        `json:"tls"`
	StartTLS  bool        `json:"starttls"`
}

SMTPRequest is the JSON wire format for an SMTP connection request.

type SMTPResponse

type SMTPResponse struct {
	Error          *ErrorDetail `json:"error,omitempty"`
	Address        string       `json:"address,omitempty"`
	Banner         string       `json:"banner,omitempty"`
	TLSVersion     string       `json:"tls_version,omitempty"`
	TLSCipherSuite string       `json:"tls_cipher_suite,omitempty"`
	TLSServerName  string       `json:"tls_server_name,omitempty"`
	ResponseTimeMs int64        `json:"response_time_ms,omitempty"`
	Connected      bool         `json:"connected"`
	TLS            bool         `json:"tls,omitempty"`
}

SMTPResponse is the JSON wire format for an SMTP connection response.

type TCPRequest

type TCPRequest struct {
	Host      string      `json:"host"`
	Port      string      `json:"port"`
	Context   ContextWire `json:"context"`
	TimeoutMs int         `json:"timeout_ms,omitempty"`
	TLS       bool        `json:"tls"`
}

TCPRequest is the JSON wire format for a TCP connection request.

type TCPResponse

type TCPResponse struct {
	TLSCertNotAfter *time.Time   `json:"tls_cert_not_after,omitempty"`
	Error           *ErrorDetail `json:"error,omitempty"`
	TLSVersion      string       `json:"tls_version,omitempty"`
	LocalAddr       string       `json:"local_addr,omitempty"`
	TLSCipherSuite  string       `json:"tls_cipher_suite,omitempty"`
	TLSServerName   string       `json:"tls_server_name,omitempty"`
	TLSCertSubject  string       `json:"tls_cert_subject,omitempty"`
	TLSCertIssuer   string       `json:"tls_cert_issuer,omitempty"`
	RemoteAddr      string       `json:"remote_addr,omitempty"`
	Address         string       `json:"address,omitempty"`
	ResponseTimeMs  int64        `json:"response_time_ms,omitempty"`
	TLS             bool         `json:"tls,omitempty"`
	Connected       bool         `json:"connected"`
}

TCPResponse is the JSON wire format for a TCP connection response.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a specific validation error.

type ValidationResult

type ValidationResult struct {
	Errors []ValidationError
	Valid  bool
}

ValidationResult represents the outcome of a capability validation.

type WireExecRequest

type WireExecRequest struct {
	Args    []string    `json:"args"`
	Env     []string    `json:"env,omitempty"`
	Command string      `json:"command"`
	Dir     string      `json:"dir,omitempty"`
	Context ContextWire `json:"context"`
}

WireExecRequest is the JSON wire format for an exec request.

Jump to

Keyboard shortcuts

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