Documentation
¶
Overview ¶
Package security provides audit logging for nightshift operations. All significant operations are logged to an append-only audit log.
Package security provides credential management for nightshift. Credentials are loaded from environment variables only - never from config files.
Package security provides sandboxed execution for nightshift agents. Agents run in isolated environments with minimal permissions.
Package security provides security and safety features for nightshift. Implements credential validation, sandboxed execution, audit logging, and safe defaults to protect against misuse and runaway costs.
Index ¶
- Constants
- Variables
- func ValidateCredentialFormat(name, value string) error
- func ValidateProjectPath(path string) error
- type AuditEvent
- type AuditEventType
- type AuditLogger
- func (l *AuditLogger) Close() error
- func (l *AuditLogger) GetLogFiles() ([]string, error)
- func (l *AuditLogger) Log(event AuditEvent) error
- func (l *AuditLogger) LogAgentComplete(agent, taskID, project string, duration time.Duration, tokensUsed int, ...) error
- func (l *AuditLogger) LogAgentError(agent, taskID, project string, err error) error
- func (l *AuditLogger) LogAgentStart(agent, taskID, project string) error
- func (l *AuditLogger) LogFileModification(eventType AuditEventType, path, agent, taskID string) error
- func (l *AuditLogger) LogGitOperation(operation, repo, branch, agent, taskID string, metadata map[string]string) error
- func (l *AuditLogger) LogOperation(op Operation) error
- func (l *AuditLogger) LogSecurityCheck(checkType, target, result string, allowed bool) error
- func (l *AuditLogger) RotateIfNeeded() error
- type Config
- type CredentialError
- type CredentialManager
- func (m *CredentialManager) CheckConfigForCredentials(content string) error
- func (m *CredentialManager) EnsureNoCredentialsInFile(path string) error
- func (m *CredentialManager) GetWarnings() []string
- func (m *CredentialManager) HasAnthropicKey() bool
- func (m *CredentialManager) HasOpenAIKey() bool
- func (m *CredentialManager) ValidateAll() []CredentialStatus
- func (m *CredentialManager) ValidateRequired() error
- type CredentialStatus
- type ExecResult
- type Manager
- func (m *Manager) Audit() *AuditLogger
- func (m *Manager) CheckPreExecution(op Operation) error
- func (m *Manager) Close() error
- func (m *Manager) Config() Config
- func (m *Manager) Credentials() *CredentialManager
- func (m *Manager) EnableWrites(enable bool)
- func (m *Manager) IsFirstRun() bool
- func (m *Manager) MarkFirstRunComplete() error
- func (m *Manager) SetMode(mode SafetyMode)
- func (m *Manager) ValidateBudgetSpend(currentPercent int) error
- func (m *Manager) ValidateGitPush() error
- func (m *Manager) ValidateWriteAccess() error
- type Operation
- type OperationType
- type SafetyMode
- type Sandbox
- func (s *Sandbox) Cleanup() error
- func (s *Sandbox) CreateTempDir(pattern string) (string, error)
- func (s *Sandbox) CreateTempFile(pattern string) (*os.File, error)
- func (s *Sandbox) Execute(ctx context.Context, name string, args ...string) (*ExecResult, error)
- func (s *Sandbox) ExecuteWithIO(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, name string, ...) error
- func (s *Sandbox) IsActive() bool
- func (s *Sandbox) TempDir() string
- func (s *Sandbox) ValidatePath(path string) error
- type SandboxConfig
- type SandboxedAgent
Constants ¶
const ( EnvAnthropicKey = "ANTHROPIC_API_KEY" EnvOpenAIKey = "OPENAI_API_KEY" )
Standard credential environment variables.
Variables ¶
var ( ErrNoCredentials = errors.New("no credentials available") ErrCredentialExpired = errors.New("credential may be expired") ErrInvalidCredential = errors.New("credential format invalid") )
Common credential errors.
Functions ¶
func ValidateCredentialFormat ¶
ValidateCredentialFormat checks if a credential has a valid format.
func ValidateProjectPath ¶ added in v0.3.2
ValidateProjectPath checks that a resolved project path is not a sensitive system directory. When agents run with dangerous permission flags, pointing them at a home directory or filesystem root exposes credentials, SSH keys, and other private data.
Types ¶
type AuditEvent ¶
type AuditEvent struct {
Timestamp time.Time `json:"timestamp"`
EventType AuditEventType `json:"event_type"`
Agent string `json:"agent,omitempty"`
TaskID string `json:"task_id,omitempty"`
Project string `json:"project,omitempty"`
Target string `json:"target,omitempty"`
Action string `json:"action,omitempty"`
Result string `json:"result,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
TokensUsed int `json:"tokens_used,omitempty"`
Error string `json:"error,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
RequestID string `json:"request_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
AuditEvent represents a single audit log entry.
func ReadEvents ¶
func ReadEvents(path string) ([]AuditEvent, error)
ReadEvents reads audit events from a specific log file.
type AuditEventType ¶
type AuditEventType string
AuditEventType categorizes audit events.
const ( AuditAgentStart AuditEventType = "agent_start" AuditAgentComplete AuditEventType = "agent_complete" AuditAgentError AuditEventType = "agent_error" AuditFileRead AuditEventType = "file_read" AuditFileWrite AuditEventType = "file_write" AuditFileDelete AuditEventType = "file_delete" AuditGitCommit AuditEventType = "git_commit" AuditGitPush AuditEventType = "git_push" AuditGitOperation AuditEventType = "git_operation" AuditSecurityCheck AuditEventType = "security_check" AuditSecurityDenied AuditEventType = "security_denied" AuditConfigChange AuditEventType = "config_change" AuditBudgetCheck AuditEventType = "budget_check" )
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger writes audit events to an append-only log file.
func NewAuditLogger ¶
func NewAuditLogger(logDir string) (*AuditLogger, error)
NewAuditLogger creates a new audit logger.
func (*AuditLogger) GetLogFiles ¶
func (l *AuditLogger) GetLogFiles() ([]string, error)
GetLogFiles returns a list of all audit log files.
func (*AuditLogger) Log ¶
func (l *AuditLogger) Log(event AuditEvent) error
Log writes an audit event to the log.
func (*AuditLogger) LogAgentComplete ¶
func (l *AuditLogger) LogAgentComplete(agent, taskID, project string, duration time.Duration, tokensUsed int, result string) error
LogAgentComplete logs the completion of an agent execution.
func (*AuditLogger) LogAgentError ¶
func (l *AuditLogger) LogAgentError(agent, taskID, project string, err error) error
LogAgentError logs an agent execution error.
func (*AuditLogger) LogAgentStart ¶
func (l *AuditLogger) LogAgentStart(agent, taskID, project string) error
LogAgentStart logs the start of an agent execution.
func (*AuditLogger) LogFileModification ¶
func (l *AuditLogger) LogFileModification(eventType AuditEventType, path, agent, taskID string) error
LogFileModification logs a file write or delete operation.
func (*AuditLogger) LogGitOperation ¶
func (l *AuditLogger) LogGitOperation(operation, repo, branch, agent, taskID string, metadata map[string]string) error
LogGitOperation logs a git operation.
func (*AuditLogger) LogOperation ¶
func (l *AuditLogger) LogOperation(op Operation) error
LogOperation logs an operation from the security manager.
func (*AuditLogger) LogSecurityCheck ¶
func (l *AuditLogger) LogSecurityCheck(checkType, target, result string, allowed bool) error
LogSecurityCheck logs a security check result.
func (*AuditLogger) RotateIfNeeded ¶
func (l *AuditLogger) RotateIfNeeded() error
RotateIfNeeded checks if the log file needs rotation (new day).
type Config ¶
type Config struct {
Mode SafetyMode // Operating mode
EnableWrites bool // Allow write operations
MaxBudgetPercent int // Max budget per run (default 75%)
AllowGitPush bool // Allow pushing to remote repos
AllowNetworkAgent bool // Allow network access for agents
AuditLogPath string // Path for audit logs
FirstRunFile string // File to track first run state
}
Config holds security configuration.
type CredentialError ¶
CredentialError represents a credential-related error.
func (*CredentialError) Error ¶
func (e *CredentialError) Error() string
Error returns a formatted credential error message.
type CredentialManager ¶
type CredentialManager struct {
// contains filtered or unexported fields
}
CredentialManager validates and provides access to credentials. Credentials are NEVER stored - only validated from environment.
func NewCredentialManager ¶
func NewCredentialManager() *CredentialManager
NewCredentialManager creates a new credential manager.
func (*CredentialManager) CheckConfigForCredentials ¶
func (m *CredentialManager) CheckConfigForCredentials(content string) error
CheckConfigForCredentials scans config content for potential credential leaks. Returns error if credentials appear to be stored in config.
func (*CredentialManager) EnsureNoCredentialsInFile ¶
func (m *CredentialManager) EnsureNoCredentialsInFile(path string) error
EnsureNoCredentialsInFile checks a file for potential credential storage.
func (*CredentialManager) GetWarnings ¶
func (m *CredentialManager) GetWarnings() []string
GetWarnings returns any warnings generated during validation.
func (*CredentialManager) HasAnthropicKey ¶
func (m *CredentialManager) HasAnthropicKey() bool
HasAnthropicKey checks if Anthropic API key is available.
func (*CredentialManager) HasOpenAIKey ¶
func (m *CredentialManager) HasOpenAIKey() bool
HasOpenAIKey checks if OpenAI API key is available.
func (*CredentialManager) ValidateAll ¶
func (m *CredentialManager) ValidateAll() []CredentialStatus
ValidateAll checks all known credentials and returns their status.
func (*CredentialManager) ValidateRequired ¶
func (m *CredentialManager) ValidateRequired() error
ValidateRequired checks that required credentials are set. Returns error if any required credential is missing.
type CredentialStatus ¶
type CredentialStatus struct {
Name string
EnvVar string
Present bool
Masked string // Masked value for display (e.g., "sk-...abc")
}
CredentialStatus represents the validation status of a credential.
type ExecResult ¶
type ExecResult struct {
Stdout string
Stderr string
ExitCode int
Duration time.Duration
Error string
}
ExecResult holds the result of a sandboxed execution.
func (*ExecResult) Success ¶
func (r *ExecResult) Success() bool
Success returns true if the command completed successfully.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager coordinates all security features.
func NewManager ¶
NewManager creates a security manager with given config.
func (*Manager) CheckPreExecution ¶
CheckPreExecution validates all safety checks before agent execution.
func (*Manager) Credentials ¶
func (m *Manager) Credentials() *CredentialManager
Credentials returns the credential manager.
func (*Manager) EnableWrites ¶
EnableWrites enables write operations.
func (*Manager) IsFirstRun ¶
IsFirstRun checks if this is the first run of nightshift.
func (*Manager) MarkFirstRunComplete ¶
MarkFirstRunComplete marks that first run setup is complete.
func (*Manager) SetMode ¶
func (m *Manager) SetMode(mode SafetyMode)
SetMode updates the safety mode.
func (*Manager) ValidateBudgetSpend ¶
ValidateBudgetSpend checks if spending within budget limits.
func (*Manager) ValidateGitPush ¶
ValidateGitPush checks if git push operations are allowed.
func (*Manager) ValidateWriteAccess ¶
ValidateWriteAccess checks if write operations are allowed.
type Operation ¶
type Operation struct {
Type OperationType
Target string // File path, git repo, URL, etc.
Agent string // Agent performing the operation
TaskID string // Associated task ID
Description string // Human-readable description
Metadata map[string]string // Additional context
}
Operation represents an action being performed.
type OperationType ¶
type OperationType string
Operation types for safety checks.
const ( OpAgentInvoke OperationType = "agent_invoke" OpFileRead OperationType = "file_read" OpFileWrite OperationType = "file_write" OpGitCommit OperationType = "git_commit" OpGitPush OperationType = "git_push" OpNetworkCall OperationType = "network_call" )
type SafetyMode ¶
type SafetyMode string
SafetyMode determines the level of access nightshift has.
const ( // ModeReadOnly allows only read operations (first run default). ModeReadOnly SafetyMode = "read_only" // ModeNormal allows normal operations with safety checks. ModeNormal SafetyMode = "normal" )
type Sandbox ¶
type Sandbox struct {
// contains filtered or unexported fields
}
Sandbox provides an isolated execution environment.
func NewSandbox ¶
func NewSandbox(cfg SandboxConfig) (*Sandbox, error)
NewSandbox creates a new sandbox with the given configuration.
func (*Sandbox) CreateTempDir ¶
CreateTempDir creates a temporary directory within the sandbox.
func (*Sandbox) CreateTempFile ¶
CreateTempFile creates a temporary file within the sandbox.
func (*Sandbox) ExecuteWithIO ¶
func (s *Sandbox) ExecuteWithIO(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, name string, args ...string) error
ExecuteWithIO runs a command with custom IO streams.
func (*Sandbox) ValidatePath ¶
ValidatePath checks if a path is accessible within the sandbox.
type SandboxConfig ¶
type SandboxConfig struct {
// WorkDir is the working directory for the sandboxed process.
WorkDir string
// TempDir is the temporary directory for working files.
TempDir string
// AllowNetwork enables network access (default false).
AllowNetwork bool
// AllowedPaths are paths the process can access.
AllowedPaths []string
// DeniedPaths are paths explicitly blocked.
DeniedPaths []string
// MaxDuration is the maximum execution time.
MaxDuration time.Duration
// MaxMemoryMB is the max memory in megabytes (0 = unlimited).
MaxMemoryMB int
// Environment variables to pass through.
Environment map[string]string
// Cleanup removes temp files after execution (default true).
Cleanup bool
}
SandboxConfig configures the sandbox environment.
func DefaultSandboxConfig ¶
func DefaultSandboxConfig() SandboxConfig
DefaultSandboxConfig returns a secure default configuration.
type SandboxedAgent ¶
type SandboxedAgent struct {
// contains filtered or unexported fields
}
SandboxedAgent wraps an agent to run in a sandbox.
func NewSandboxedAgent ¶
func NewSandboxedAgent(cfg SandboxConfig) (*SandboxedAgent, error)
NewSandboxedAgent creates a new sandboxed agent wrapper.
func (*SandboxedAgent) Close ¶
func (a *SandboxedAgent) Close() error
Close cleans up sandbox resources.
func (*SandboxedAgent) Sandbox ¶
func (a *SandboxedAgent) Sandbox() *Sandbox
Sandbox returns the underlying sandbox.