Documentation
¶
Overview ¶
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 ¶
- 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 InputGuardrail
- type OutputGuardrail
- type RateLimiter
- type SSRFConfig
- type SSRFGuard
- type SafeMergeError
- type ToolSecurityPolicy
Constants ¶
This section is empty.
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") )
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.
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 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{}
OutputGuardrail valida respostas geradas pelo LLM antes do envio.
func NewOutputGuardrail ¶
func NewOutputGuardrail() *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.
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 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.