Documentation
¶
Overview ¶
Package security – audit.go implements security auditing for DevClaw configuration. Checks for common misconfigurations, exposed secrets, and security gaps.
Package security implementa os guardrails de segurança do DevClaw. Inclui validação de input (injection, rate limit, PII), validação de output (URLs, fatos, PII) e políticas de segurança para execução de tools.
Package security – safe_merge.go provides protection against prototype pollution when merging maps. This is a security hardening measure inspired by openclaw.
Package security – ssrf.go implements SSRF (Server-Side Request Forgery) protection for web_fetch and similar tools. Resolves hostnames first to defend against DNS rebinding, then validates resolved IPs against private ranges, metadata endpoints, and blocked hosts.
Index ¶
- Constants
- Variables
- func IsBlockedKey(key string) bool
- func SafeMerge(dst, src map[string]any) error
- func SafeMergeDeep(dst, src map[string]any) error
- func ValidateMapKeys(m map[string]any) error
- type AuditFinding
- type AuditOptions
- type AuditReport
- type InputGuardrail
- type OutputGuardrail
- type RateLimiter
- type SSRFConfig
- type SSRFGuard
- type SafeMergeError
- type ToolResultContext
- type ToolSecurityPolicy
Constants ¶
const ( SeverityCritical = "critical" SeverityWarning = "warning" SeverityInfo = "info" )
Severity levels for audit findings.
Variables ¶
var ( ErrInputTooLong = fmt.Errorf("mensagem excede o tamanho máximo permitido") ErrRateLimited = fmt.Errorf("limite de mensagens por minuto excedido, aguarde um momento") ErrPromptInjection = fmt.Errorf("conteúdo potencialmente malicioso detectado") ErrEmptyOutput = fmt.Errorf("resposta vazia gerada pelo modelo") ErrSystemPromptLeak = fmt.Errorf("possível vazamento de instruções internas") ErrHallucinatedURL = fmt.Errorf("URL na resposta não corresponde aos resultados") ErrConfirmationRequired = fmt.Errorf("esta ação requer confirmação do usuário") ErrToolNotAllowed = fmt.Errorf("tool não permitida pela política de segurança") ErrCredentialLeak = fmt.Errorf("credential detected in output — redacting") )
var BlockedMergeKeys = map[string]bool{ "__proto__": true, "prototype": true, "constructor": true, }
BlockedMergeKeys are keys that should never be used in map operations as they can lead to prototype pollution attacks.
var SecurityChecks = []func(AuditOptions) *AuditFinding{
checkVaultNotConfigured,
checkRawAPIKeys,
checkConfigPermissions,
checkSessionsPermissions,
checkGatewayBindNoAuth,
checkCORSOpen,
checkSudoAllowed,
checkSSRFDisabled,
checkEmbeddingNoKey,
checkVaultFilePermissions,
}
SecurityChecks is the list of all security check functions run during an audit.
Functions ¶
func IsBlockedKey ¶ added in v1.8.0
IsBlockedKey checks if a single key is in the blocked list.
func SafeMerge ¶ added in v1.8.0
SafeMerge performs a shallow merge of src into dst, but blocks any keys that could cause prototype pollution. Returns an error if blocked keys are detected in src.
func SafeMergeDeep ¶ added in v1.8.0
SafeMergeDeep performs a deep merge of src into dst, but blocks any keys that could cause prototype pollution at any level. Returns an error if blocked keys are detected.
func ValidateMapKeys ¶ added in v1.8.0
ValidateMapKeys checks if a map contains any blocked keys that could cause prototype pollution. Returns an error if blocked keys are found.
Types ¶
type AuditFinding ¶ added in v1.13.0
type AuditFinding struct {
CheckID string `json:"check_id"`
Severity string `json:"severity"`
Title string `json:"title"`
Detail string `json:"detail"`
Remediation string `json:"remediation"`
}
AuditFinding represents a single security finding.
type AuditOptions ¶ added in v1.13.0
type AuditOptions struct {
ConfigPath string // Path to config.yaml
SessionsDir string // Path to sessions directory
VaultPath string // Path to .devclaw.vault
VaultConfigured bool // Whether vault is initialized
APIKey string // Current API key value (for plaintext check)
Provider string // Current LLM provider
GatewayEnabled bool // Whether HTTP gateway is enabled
GatewayBind string // Gateway bind address
GatewayAuth bool // Whether gateway auth is configured
CORSOrigins []string // CORS allowed origins
SSRFEnabled bool // Whether SSRF guard is enabled
SudoAllowed bool // Whether sudo is allowed in exec tools
EmbeddingProvider string // Embedding provider name
EmbeddingAPIKey string // Embedding API key
ExtraChecks map[string]string // Additional key-value pairs for custom checks
}
AuditOptions configures which checks to run.
type AuditReport ¶ added in v1.13.0
type AuditReport struct {
Timestamp time.Time `json:"timestamp"`
TotalChecks int `json:"total_checks"`
CriticalCount int `json:"critical_count"`
WarningCount int `json:"warning_count"`
InfoCount int `json:"info_count"`
Findings []AuditFinding `json:"findings"`
}
AuditReport is the result of a security audit.
func RunSecurityAudit ¶ added in v1.13.0
func RunSecurityAudit(opts AuditOptions) *AuditReport
RunSecurityAudit executes all security checks and returns a report.
func (*AuditReport) Summary ¶ added in v1.13.0
func (r *AuditReport) Summary() string
Summary returns a human-readable summary line.
type InputGuardrail ¶
type InputGuardrail struct {
// contains filtered or unexported fields
}
InputGuardrail valida mensagens de entrada antes do processamento pelo LLM.
func NewInputGuardrail ¶
func NewInputGuardrail(maxLength, rateLimit int) *InputGuardrail
NewInputGuardrail cria um novo guardrail de input.
func (*InputGuardrail) Validate ¶
func (g *InputGuardrail) Validate(userID, input string) error
Validate executa todas as validações no input.
type OutputGuardrail ¶
type OutputGuardrail struct {
// CredentialChecker is an optional function that detects credential patterns
// in text. When set, ValidateWithContext uses it to detect credential leaks
// in the final output. Injected by the copilot package to avoid circular imports.
CredentialChecker func(string) bool
// contains filtered or unexported fields
}
OutputGuardrail valida respostas geradas pelo LLM antes do envio.
func NewOutputGuardrail ¶
func NewOutputGuardrail(logger *slog.Logger) *OutputGuardrail
NewOutputGuardrail cria um novo guardrail de output.
func (*OutputGuardrail) Validate ¶
func (g *OutputGuardrail) Validate(output string) error
Validate executa todas as validações no output do LLM.
func (*OutputGuardrail) ValidateWithContext ¶ added in v1.13.0
func (g *OutputGuardrail) ValidateWithContext(output string, toolResults []ToolResultContext) error
ValidateWithContext validates output against an optional set of tool results from the current turn. Used to cross-check claimed URLs and facts.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implementa rate limiting por usuário usando sliding window.
func NewRateLimiter ¶
func NewRateLimiter(maxRequests int, window time.Duration) *RateLimiter
NewRateLimiter cria um novo rate limiter.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(userID string) bool
Allow verifica se o usuário pode fazer uma nova requisição. Retorna true se permitido, false se excedeu o limite.
type SSRFConfig ¶
type SSRFConfig struct {
// AllowPrivate allows requests to private IPs (default: false).
AllowPrivate bool `yaml:"allow_private"`
// AllowedHosts is a whitelist. If set, only these hosts are allowed.
AllowedHosts []string `yaml:"allowed_hosts"`
// BlockedHosts is a blacklist (checked even if AllowPrivate is true).
BlockedHosts []string `yaml:"blocked_hosts"`
}
SSRFConfig configures SSRF protection behavior.
type SSRFGuard ¶
type SSRFGuard struct {
// contains filtered or unexported fields
}
SSRFGuard validates URLs before outgoing HTTP requests to prevent SSRF.
func NewSSRFGuard ¶
func NewSSRFGuard(cfg SSRFConfig, logger *slog.Logger) *SSRFGuard
NewSSRFGuard creates a new SSRF guard from config.
type SafeMergeError ¶ added in v1.8.0
type SafeMergeError struct {
Key string
}
SafeMergeError is returned when a blocked key is detected.
func (*SafeMergeError) Error ¶ added in v1.8.0
func (e *SafeMergeError) Error() string
type ToolResultContext ¶ added in v1.13.0
ToolResultContext holds a single tool result for output validation.
type ToolSecurityPolicy ¶
type ToolSecurityPolicy struct {
// AllowedTools lista as tools permitidas por skill (chave = skill name, valor = tool names).
AllowedTools map[string][]string
// RequiresConfirmation lista tools que precisam de confirmação do usuário.
RequiresConfirmation []string
// ToolRateLimits define rate limits específicos por tool.
ToolRateLimits map[string]int
}
ToolSecurityPolicy define políticas de segurança para execução de tools.
func (*ToolSecurityPolicy) BeforeToolCall ¶
func (p *ToolSecurityPolicy) BeforeToolCall(skillName, tool string) error
BeforeToolCall valida se uma tool pode ser executada para uma skill específica.