security

package
v0.52.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package security provides input sanitization and output scanning for fullsend's agent entrypoints. These scanners run at the boundaries:

  • Input boundary: before untrusted text (issue bodies, PR descriptions, code comments, context files) reaches agent processing
  • Output boundary: before agent-generated text (PR comments, issue comments) is posted via the forge API

The scanners are adapted from Hermes Agent's production security controls, ported to Go for integration into fullsend's CLI entrypoints.

See: experiments/hermes-security-patterns/ for the Python prototypes and evaluation results.

Index

Constants

View Source
const AllTools = "*"

AllTools is the wildcard tool matcher.

View Source
const HookTimeoutSeconds = 30

HookTimeoutSeconds is the per-run timeout written for every sandbox hook.

View Source
const SandboxHooksDir = sandbox.SandboxClaudeConfig + "/hooks"

SandboxHooksDir is the directory where hook scripts are installed inside the sandbox. Co-located with SandboxHooksSettings under the runner-owned config directory so they are outside the agent-writable workspace tree.

View Source
const SandboxHooksSettings = sandbox.SandboxClaudeConfig + "/hooks.json"

SandboxHooksSettings is the path where the hook wiring hooks.json is written inside the sandbox. buildRunCommand passes this via --settings so Claude Code loads the hooks regardless of its working directory.

Variables

View Source
var CanaryPostToolHook []byte
View Source
var CanaryPreToolHook []byte
View Source
var CanonicalClaudeTools = map[string]bool{
	"Agent":                true,
	"Artifact":             true,
	"AskUserQuestion":      true,
	"Bash":                 true,
	"CronCreate":           true,
	"CronDelete":           true,
	"CronList":             true,
	"Edit":                 true,
	"EndConversation":      true,
	"EnterPlanMode":        true,
	"EnterWorktree":        true,
	"ExitPlanMode":         true,
	"ExitWorktree":         true,
	"Glob":                 true,
	"Grep":                 true,
	"ListAgents":           true,
	"ListMcpResourcesTool": true,
	"LSP":                  true,
	"Monitor":              true,
	"NotebookEdit":         true,
	"PowerShell":           true,
	"PushNotification":     true,
	"Read":                 true,
	"ReadMcpResourceTool":  true,
	"RemoteTrigger":        true,
	"ReportFindings":       true,
	"ScheduleWakeup":       true,
	"SendMessage":          true,
	"SendUserFile":         true,
	"ShareOnboardingGuide": true,
	"Skill":                true,
	"TaskCreate":           true,
	"TaskGet":              true,
	"TaskList":             true,
	"TaskOutput":           true,
	"TaskStop":             true,
	"TaskUpdate":           true,
	"TodoWrite":            true,
	"ToolSearch":           true,
	"WaitForMcpServers":    true,
	"WebFetch":             true,
	"WebSearch":            true,
	"Workflow":             true,
	"Write":                true,
}

CanonicalClaudeTools is the set of tool names Claude Code exposes today. It is the canonical hook vocabulary (ADR 0090, #608): FULLSEND_TOOL_ALLOWLIST entries and HookGroup.Tools are written in these names, and a runtime adapter (pi: claudeToolForPi → fullsend-manifest.json hooks.toolNames → fullsend-hooks.js claudeToolName) translates its own names to them before any hook script runs. A name the adapter did not translate is still blocked (the allowlist is exact-match, fail-closed) but tool_allowlist_pretool.py reports it as an adapter gap rather than a forbidden tool.

Verified 2026-08-23 against the live tools reference (https://code.claude.com/docs/en/tools-reference, which documents the latest release — 2.1.241 at the time); the CHANGELOG for 2.1.235–2.1.241 records no tool additions or removals relative to the 2.1.234 pinned in images/sandbox/Containerfile. Re-check on every pin bump.

MCP tool names (mcp__<server>__<tool>) are not canonical: they pass through verbatim and the allowlist matches them exactly, so the hook never treats their case variants as a translation gap.

The hook script carries its own copy (CANONICAL_TOOLS / LEGACY_TOOLS in hooks/tool_allowlist_pretool.py) because the scripts have no access to Go; TestToolAllowlistHook_VocabularyMatchesGo keeps the two identical.

View Source
var ContextSuppressPostToolHook []byte
View Source
var HookIO []byte

HookIO is the shared PostToolUse protocol library imported by the chain and by individual sanitizer/canary scripts. It is not itself a hook.

View Source
var LegacyClaudeTools = map[string]string{
	"LS":           "",
	"MultiEdit":    "Edit",
	"NotebookRead": "Read",
	"Task":         "Agent",
	"TodoRead":     "",
}

LegacyClaudeTools are tool names Claude Code no longer exposes but which still appear in agent `tools:` frontmatter and in runtime adapter maps (the pi adapter reports pi's `ls` as LS and accepts MultiEdit for its edit tool). Claude Code itself never sends these to a hook; an adapter may. The value is the current replacement, "" when there is none.

View Source
var PostToolChainHook []byte
View Source
var SSRFPreToolHook []byte
View Source
var ScannableFiles = map[string]bool{
	"agents.md":               true,
	".cursorrules":            true,
	"claude.md":               true,
	".claude.md":              true,
	"soul.md":                 true,
	".hermes.md":              true,
	"hermes.md":               true,
	"gemini.md":               true,
	".gemini.md":              true,
	"copilot-instructions.md": true,
	"skill.md":                true,
	"plugin.json":             true,
	".lsp.json":               true,
}

ScannableFiles is the set of filenames that should be scanned for prompt injection before being loaded into agent context.

View Source
var SecretRedactPostToolHook []byte
View Source
var TirithCheckHook []byte
View Source
var ToolAllowlistPreToolHook []byte
View Source
var UnicodePostToolHook []byte

Functions

func AppendFinding

func AppendFinding(path string, tf TracedFinding) error

AppendFinding writes a traced finding as a JSON line to the given file path. It computes a SHA-256 hash chain: each entry's hash covers the previous entry's hash and the current entry's payload, making the log tamper-evident.

func DestroyMLScanner

func DestroyMLScanner()

DestroyMLScanner is a no-op stub when ONNX runtime is not available.

func GenerateHooksConfig added in v0.37.0

func GenerateHooksConfig(hooks SandboxHookConfig) ([]byte, error)

GenerateHooksConfig produces the hooks.json Claude Code hook wiring, loaded via --settings in buildRunCommand. Returns the JSON bytes. The wiring comes from HookPlan; this function only renders it in Claude Code's settings format.

func GenerateHooksConfigPinned added in v0.48.0

func GenerateHooksConfigPinned(hooks SandboxHookConfig, python, path string) ([]byte, error)

GenerateHooksConfigPinned is GenerateHooksConfig with the interpreter and the hooks' PATH fixed by the caller. Claude Code runs a hook through the shell it inherits *after* the agent-writable workspace .env is sourced, so a bare `python3`, or a bare `tirith` inside tirith_check.py, resolves through a PATH an earlier iteration controls: a fake that exits 0 skips the check while hooks.json and the scripts stay byte-identical. The runtime therefore resolves an absolute python (and a trusted PATH) at Bootstrap, on a shell the agent has not touched, and renders them here so the hooks.json digest covers both. An empty path leaves PATH as inherited.

-E ignores every PYTHON* variable (PYTHONPATH, PYTHONHOME, PYTHONSTARTUP, ...) and -s drops the user site directory. -I is not used: it would also drop the script's own directory from sys.path, and the scripts import hook_io and load the chain's stages from SandboxHooksDir. That directory is covered by the runtime's exhaustive launch guard, so no sitecustomize.py or shadowing module can sit in it.

func GenerateTraceID

func GenerateTraceID() string

GenerateTraceID returns a UUID v4 string for correlating security findings across scanning phases (host pre-step, sandbox pre-agent, runtime hooks, post-agent output scan).

func HasCriticalFindings added in v0.2.0

func HasCriticalFindings(findings []Finding) bool

HasCriticalFindings reports whether any finding has critical severity.

func HookFiles

func HookFiles(hooks SandboxHookConfig) map[string][]byte

HookFiles returns a map of filename -> content for all enabled hook scripts.

func IsShellSafeTraceID added in v0.28.0

func IsShellSafeTraceID(id string) bool

IsShellSafeTraceID returns true if the trace ID consists only of lowercase hex and dashes in UUID shape — the property that makes it safe for shell interpolation. Unlike IsValidTraceID it accepts any version/variant, because a trace id adopted from an inbound W3C traceparent (issue #2779) is not necessarily UUID v4. The charset restriction is the entire safety argument; version bits carry no interpolation risk.

func IsValidTraceID

func IsValidTraceID(id string) bool

IsValidTraceID returns true if the trace ID is safe for shell interpolation.

func KnownClaudeTool added in v0.38.0

func KnownClaudeTool(name string) bool

KnownClaudeTool reports whether name is a canonical or legacy Claude tool name — i.e. a name the hook scripts can be expected to see from a runtime adapter.

func MLScanAvailable

func MLScanAvailable() bool

MLScanAvailable reports whether the native ONNX ML scanner is compiled in.

func ParseEgressAllowlist added in v0.38.0

func ParseEgressAllowlist(raw string) map[string]bool

ParseEgressAllowlist parses a comma-separated "host:port" allowlist string into a lookup map.

func RegisterRuntimeSecret added in v0.38.0

func RegisterRuntimeSecret(value string) bool

RegisterRuntimeSecret adds an exact value to the process-wide redaction set and reports whether it is now registered. Registering the same value twice is a no-op; a value below the minimum length is refused (false) so the caller can decide not to use a credential it cannot redact.

func RuntimeSecrets added in v0.48.0

func RuntimeSecrets() []string

RuntimeSecrets returns the registered runtime secrets, longest first, for callers that combine them with their own literals in one longest-first pass.

func ShouldScan

func ShouldScan(filename string) bool

ShouldScan reports whether a filename should be scanned for injection.

Types

type ChainVerification added in v0.19.0

type ChainVerification struct {
	Valid     bool
	Entries   int
	BrokenAt  int    // 0-indexed; -1 if valid
	BrokenMsg string // empty if valid
}

ChainVerification holds the result of verifying a findings JSONL file.

func VerifyChain added in v0.19.0

func VerifyChain(path string) (ChainVerification, error)

VerifyChain reads a findings JSONL file and verifies the hash chain integrity. Returns a ChainVerification indicating whether the chain is intact. Entries without hash fields (from older versions) are skipped.

type ContextInjectionScanner

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

ContextInjectionScanner detects prompt injection patterns in project context files (AGENTS.md, .cursorrules, CLAUDE.md, etc.) before they are loaded into an agent's system prompt. Adapted from Hermes Agent's prompt_builder.py injection scanning.

func NewContextInjectionScanner

func NewContextInjectionScanner() *ContextInjectionScanner

NewContextInjectionScanner creates a scanner with the default pattern set.

func (*ContextInjectionScanner) Name

func (c *ContextInjectionScanner) Name() string

func (*ContextInjectionScanner) Scan

type Finding

type Finding struct {
	Scanner  string // "secret_redactor", "ssrf_validator", "context_injection", "unicode_normalizer"
	Name     string // pattern name or category
	Severity string // "critical", "high", "medium"
	Detail   string // human-readable description
	Position int    // byte offset in original text, -1 if N/A
}

Finding represents a single security issue detected by a scanner.

type HookGroup added in v0.37.0

type HookGroup struct {
	Phase   HookPhase
	Tools   []string
	Scripts []string
}

HookGroup is one ordered chain of hook scripts bound to a set of tools. Tools are Claude Code tool names ("Bash", "Read", "WebFetch", ...); "*" means every tool. Scripts are filenames from HookFiles, run sequentially in the listed order — ordering is load-bearing for PostToolUse chains (see HookPlan). Runtimes that use different tool names translate before matching.

func HookPlan added in v0.37.0

func HookPlan(hooks SandboxHookConfig) []HookGroup

HookPlan returns the runtime-neutral wiring for the enabled sandbox hooks: which scripts run in which phase, for which tools, in what order. It is the single source of truth consumed by GenerateHooksConfig (Claude Code) and by any other runtime's hook adapter, so the two cannot diverge.

type HookPhase added in v0.37.0

type HookPhase string

HookPhase identifies when a sandbox hook group runs relative to a tool call. The names match Claude Code's settings.json event names; other runtimes map them onto their own hook/plugin/extension events (e.g. OpenCode tool.execute.before/after, pi tool_call/tool_result).

const (
	// HookPhasePreToolUse runs before the tool executes and may block it.
	HookPhasePreToolUse HookPhase = "PreToolUse"
	// HookPhasePostToolUse runs after the tool executes and may rewrite its result.
	HookPhasePostToolUse HookPhase = "PostToolUse"
	// HookPhasePostToolUseFailure runs after a tool call fails. Claude Code
	// delivers the error text but allows no rewrite, so this phase detects
	// rather than sanitizes: a canary halts the session, and credential-shaped
	// or control content is logged and returned to the agent as an
	// additionalContext warning. Runtimes whose post-tool event already covers
	// failed calls (pi) map it onto nothing.
	HookPhasePostToolUseFailure HookPhase = "PostToolUseFailure"
)

type Pipeline

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

Pipeline chains multiple scanners in sequence. Each scanner's sanitized output feeds into the next scanner's input.

func InputPipeline

func InputPipeline() *Pipeline

InputPipeline returns the standard input scanning pipeline for untrusted text entering the agent. Order matters:

  1. UnicodeNormalizer — strip invisible chars, normalize fullwidth
  2. ContextInjectionScanner — detect prompt injection patterns

func NewPipeline

func NewPipeline(scanners ...Scanner) *Pipeline

NewPipeline creates a scanner pipeline from the given scanners. Scanners run in order; place normalizers first, detectors after.

func OutputPipeline

func OutputPipeline() *Pipeline

OutputPipeline returns the standard output scanning pipeline for agent-generated text before posting to the forge.

  1. UnicodeNormalizer — strip invisible chars, normalize fullwidth
  2. SecretRedactor — redact API keys, tokens, credentials

func (*Pipeline) Scan

func (p *Pipeline) Scan(text string) ScanResult

Scan runs all scanners in sequence. Returns the aggregate result. The pipeline is fail-open for sanitization (each scanner transforms the text) but fail-closed for safety (any scanner marking unsafe makes the whole result unsafe).

type SSRFValidator

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

SSRFValidator validates URLs against blocked networks, hostnames, and schemes to prevent Server-Side Request Forgery. Adapted from Hermes Agent's URL validation.

func NewSSRFValidator

func NewSSRFValidator() *SSRFValidator

NewSSRFValidator creates a validator with the default blocklists.

func NewSSRFValidatorWithAllowlist added in v0.38.0

func NewSSRFValidatorWithAllowlist(allowlist string) *SSRFValidator

NewSSRFValidatorWithAllowlist creates a validator with an egress allowlist. The allowlist is a comma-separated string of host:port entries (e.g. "gitlab.internal:443,other.host:8443"). Hosts on the allowlist bypass DNS-failure fail-closed — all other checks (scheme, blocked hostnames, IP checks) still apply.

func (*SSRFValidator) Name

func (s *SSRFValidator) Name() string

func (*SSRFValidator) Scan

func (s *SSRFValidator) Scan(text string) ScanResult

Scan implements the Scanner interface. Extracts URLs from text and validates each one. Uses regex-based extraction (matching the Python hook's URL_PATTERN) to handle URLs embedded in markdown, JSON, etc.

func (*SSRFValidator) ValidateRedirectChain

func (s *SSRFValidator) ValidateRedirectChain(urls []string) ScanResult

ValidateRedirectChain checks each URL in a redirect chain.

func (*SSRFValidator) ValidateURL

func (s *SSRFValidator) ValidateURL(rawURL string, resolveDNS bool) ScanResult

ValidateURL checks a single URL for SSRF risk. Set resolveDNS to true to resolve hostnames and check resolved IPs.

type SandboxHookConfig added in v0.37.0

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

SandboxHookConfig configures the runtime-neutral sandbox tool hooks (PreToolUse/PostToolUse scripts in hooks/). It is derived from the harness `security.sandbox_hooks` block and consumed by any agent runtime that installs the hook scripts — Claude Code wires them through settings.json; other runtimes call the same scripts from their own hook/plugin/extension mechanism. A nil internal hook config uses the same defaults as an unset harness security block.

func SandboxHookConfigFromHarness added in v0.37.0

func SandboxHookConfigFromHarness(h *harness.Harness) SandboxHookConfig

SandboxHookConfigFromHarness extracts sandbox hook settings from a harness.

func (SandboxHookConfig) ForgeEgressEntry added in v0.38.0

func (c SandboxHookConfig) ForgeEgressEntry() string

ForgeEgressEntry returns the forge-specific "host:port" egress entry set by the CLI layer, or empty when none was configured.

func (SandboxHookConfig) SSRFEgressAllowlist added in v0.38.0

func (c SandboxHookConfig) SSRFEgressAllowlist() string

SSRFEgressAllowlist returns the comma-separated egress allowlist, or empty when unset. The allowlist tells the SSRF hook which hosts may bypass the DNS-failure fail-closed check (the L7 egress proxy will resolve and enforce the network policy for those hosts).

func (SandboxHookConfig) TirithFailOn added in v0.37.0

func (c SandboxHookConfig) TirithFailOn() string

TirithFailOn returns the Tirith severity threshold env value, or empty when unset.

func (SandboxHookConfig) TirithRequired added in v0.37.0

func (c SandboxHookConfig) TirithRequired() bool

TirithRequired reports whether Tirith Bash scanning should be required in the sandbox.

func (SandboxHookConfig) WithForgeEgressEntry added in v0.38.0

func (c SandboxHookConfig) WithForgeEgressEntry(entry string) SandboxHookConfig

WithForgeEgressEntry returns a copy of c with the forge egress entry set. The entry is a "host:port" string merged into the egress allowlist at bootstrap time.

type ScanResult

type ScanResult struct {
	Safe      bool
	Findings  []Finding
	Sanitized string // cleaned/redacted version of input (empty if unchanged)
}

ScanResult holds the outcome of a security scan.

func RunMLScan

func RunMLScan(_ string, _ bool) ScanResult

RunMLScan is a no-op stub when ONNX runtime is not available.

type Scanner

type Scanner interface {
	// Name returns the scanner identifier.
	Name() string

	// Scan checks text for security issues. Returns a ScanResult with
	// findings and optionally a sanitized version of the input.
	Scan(text string) ScanResult
}

Scanner is the interface for all security scanners.

type SecretRedactor

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

SecretRedactor scans text for API keys, tokens, credentials, and sensitive patterns, replacing them with masked versions. Adapted from Hermes Agent's agent/redact.py.

func NewSecretRedactor

func NewSecretRedactor() *SecretRedactor

NewSecretRedactor creates a redactor with the default pattern set.

func (*SecretRedactor) Name

func (s *SecretRedactor) Name() string

func (*SecretRedactor) Scan

func (s *SecretRedactor) Scan(text string) ScanResult

type TracedFinding

type TracedFinding struct {
	TraceID   string `json:"trace_id"`
	Timestamp string `json:"timestamp"`
	Phase     string `json:"phase"` // "host_input", "sandbox_context", "hook_pretool", "hook_posttool", "host_output"
	PrevHash  string `json:"prev_hash"`
	Hash      string `json:"hash"`
	Finding
}

TracedFinding is a Finding enriched with trace and phase metadata for the JSONL audit log. PrevHash and Hash form a SHA-256 chain: each entry's Hash covers PrevHash and the rest of the entry, making tampering detectable.

type UnicodeNormalizer

type UnicodeNormalizer struct{}

UnicodeNormalizer strips invisible Unicode characters and normalizes fullwidth characters to prevent command obfuscation and hidden payload injection. Adapted from Hermes Agent's approval.py.

func NewUnicodeNormalizer

func NewUnicodeNormalizer() *UnicodeNormalizer

NewUnicodeNormalizer creates a UnicodeNormalizer.

func (*UnicodeNormalizer) Name

func (u *UnicodeNormalizer) Name() string

func (*UnicodeNormalizer) Scan

func (u *UnicodeNormalizer) Scan(text string) ScanResult

Jump to

Keyboard shortcuts

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