security

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 11 Imported by: 0

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

View Source
const (
	EnvAnthropicKey = "ANTHROPIC_API_KEY"
	EnvOpenAIKey    = "OPENAI_API_KEY"
)

Standard credential environment variables.

Variables

View Source
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

func ValidateCredentialFormat(name, value string) error

ValidateCredentialFormat checks if a credential has a valid format.

func ValidateProjectPath added in v0.3.2

func ValidateProjectPath(path string) error

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) Close

func (l *AuditLogger) Close() error

Close closes the audit log file.

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.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns safe default configuration.

type CredentialError

type CredentialError struct {
	Credential string
	Message    string
}

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

func NewManager(cfg Config) (*Manager, error)

NewManager creates a security manager with given config.

func (*Manager) Audit

func (m *Manager) Audit() *AuditLogger

Audit returns the audit logger.

func (*Manager) CheckPreExecution

func (m *Manager) CheckPreExecution(op Operation) error

CheckPreExecution validates all safety checks before agent execution.

func (*Manager) Close

func (m *Manager) Close() error

Close cleans up security manager resources.

func (*Manager) Config

func (m *Manager) Config() Config

Config returns current security config.

func (*Manager) Credentials

func (m *Manager) Credentials() *CredentialManager

Credentials returns the credential manager.

func (*Manager) EnableWrites

func (m *Manager) EnableWrites(enable bool)

EnableWrites enables write operations.

func (*Manager) IsFirstRun

func (m *Manager) IsFirstRun() bool

IsFirstRun checks if this is the first run of nightshift.

func (*Manager) MarkFirstRunComplete

func (m *Manager) MarkFirstRunComplete() error

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

func (m *Manager) ValidateBudgetSpend(currentPercent int) error

ValidateBudgetSpend checks if spending within budget limits.

func (*Manager) ValidateGitPush

func (m *Manager) ValidateGitPush() error

ValidateGitPush checks if git push operations are allowed.

func (*Manager) ValidateWriteAccess

func (m *Manager) ValidateWriteAccess() error

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) Cleanup

func (s *Sandbox) Cleanup() error

Cleanup removes all temporary files created by the sandbox.

func (*Sandbox) CreateTempDir

func (s *Sandbox) CreateTempDir(pattern string) (string, error)

CreateTempDir creates a temporary directory within the sandbox.

func (*Sandbox) CreateTempFile

func (s *Sandbox) CreateTempFile(pattern string) (*os.File, error)

CreateTempFile creates a temporary file within the sandbox.

func (*Sandbox) Execute

func (s *Sandbox) Execute(ctx context.Context, name string, args ...string) (*ExecResult, error)

Execute runs a command 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) IsActive

func (s *Sandbox) IsActive() bool

IsActive returns true if a command is currently executing.

func (*Sandbox) TempDir

func (s *Sandbox) TempDir() string

TempDir returns the sandbox temporary directory.

func (*Sandbox) ValidatePath

func (s *Sandbox) ValidatePath(path string) error

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.

Jump to

Keyboard shortcuts

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