Documentation
¶
Overview ¶
Package shellguard provides static AST-based security analysis and command classification for shell execution in TaskSmith.
Architecture Overview ¶
A Guard instance is constructed via New with a dependency-injected Config (specifying WorkspaceDir, HomeDir, ProtectedDirs, MaxOperations, and a declarative Policy):
AST Parsing & Nested Extraction (Parse): Uses mvdan.cc/sh/v3/syntax to parse shell scripts into a CommandChain of Pipeline and ParsedCommand nodes. Recursively walks compound shell constructs—including pipelines, logical chains (&&, ||, ;), subshells ((...)), command blocks ({ ...; }), control-flow clauses (if, for, while, until, case, function declarations), command substitutions ($(cmd) and `cmd`), and wrapper commands (sudo, npx, bash -c, sh -c).
Virtual Working Directory Tracking & Value-Copied Subshell Isolation: Tracks directory transitions (cd) across sequential commands in a virtual CWD state machine using the configured HomeDir for tilde (~) expansion without runtime OS syscalls. When entering a subshell (ParsedCommand.Subshell), command substitution, or multi-command shell wrapper, the classifier passes a value copy of the tracker state so directory changes inside (cd /tmp && ls) never leak to subsequent commands outside the subshell.
Declarative Classification & Target Extraction (Policy, CommandRule): Evaluates each command against the Guard's Policy to assign an [ActionType] ([ActionRead], [ActionUnknown], [ActionWrite], [ActionExec], [ActionDelete]) and a [SafetyLevel] ([SafetySafe], [SafetyUnknown], [SafetyUnsafe]). Each CommandRule declaratively specifies its TargetMode (TargetsAll, TargetsNone, TargetsSkipFirst, TargetsLast, TargetsAfterDashDash, TargetsPredicateStop), ValueFlags, PathFlags, and SubcommandModes so a single generic extractor accurately identifies filesystem targets without false positives on echo strings, grep/sed patterns, or git commit -m messages. Commands escaping WorkspaceDir or modifying ProtectedDirs (.git, .bare, .agents) are flagged as [SafetyUnsafe].
Compound Operation Collapsing (Guard.Analyze vs Guard.AnalyzeDetailed): To prevent approval prompt bloat on multi-step scripts, Guard.Analyze collapses command chains exceeding MaxOperations (default DefaultMaxOperations) or containing control-flow clauses / inline interpreter scripts into a single summary Operation marked with IsCompound: true, taking the highest-severity [ActionType] and worst [SafetyLevel] across all constituent operations.
Index ¶
- Constants
- Variables
- func ExtractScriptPaths(cmdStr string) []string
- func MatchExcludedCommand(commandStr string, patterns []string) bool
- func TouchesProtectedPath(cmdStr, wsRoot, homeDir string) bool
- type ArgRule
- type CommandChain
- type CommandRule
- type Config
- type EnvVar
- type Guard
- func (g *Guard) Analyze(commandStr string) ([]Operation, error)
- func (g *Guard) AnalyzeDetailed(commandStr string) ([]Operation, error)
- func (g *Guard) EvaluatePath(targetPath string, action api.ActionType) (string, api.SafetyLevel)
- func (g *Guard) IsInReadDirs(targetPath string) bool
- func (g *Guard) IsInWriteDirs(targetPath string) bool
- func (g *Guard) IsProtectedPath(targetPath string) bool
- func (g *Guard) Match(grantTarget string, matchMethod string, cmd ParsedCommand) bool
- func (g *Guard) PathPosture(targetPath string) (insideWorkspace bool, protected bool)
- func (g *Guard) TouchesProtectedPath(cmdStr string) bool
- type Operation
- type ParsedCommand
- type Pipeline
- type Policy
- type Redirect
- type TargetArg
- type TargetMode
Constants ¶
const DefaultMaxOperations = 3
DefaultMaxOperations is the default maximum number of individual operations Guard.Analyze will return before collapsing them into a single compound Operation to prevent approval prompt bloat.
const MaxGranularOperations = DefaultMaxOperations
MaxGranularOperations is an alias for DefaultMaxOperations.
Variables ¶
var DefaultProtectedDirs = guard.DefaultProtectedDirs
DefaultProtectedDirs is the default list of protected workspace directories where write, delete, or exec operations are marked SafetyUnsafe.
Functions ¶
func ExtractScriptPaths ¶
ExtractScriptPaths parses cmdStr and returns deduplicated local script paths invoked directly (./scripts/foo.sh) or via common script interpreters (python3 tools/gen.py, sh build.sh, awk -f script.awk).
func MatchExcludedCommand ¶
MatchExcludedCommand reports whether an entire shell command is exempt from kernel sandboxing because every simple command in its syntax tree matches at least one excludedCommands pattern (e.g. "git commit *", "docker compose *").
It walks the raw mvdan.cc/sh syntax tree rather than the lossy ParsedCommand projection, and is deliberately strict: any statement form the projection could drop or flatten (decl/test/arith clauses, coprocesses, negation), background or disowned statements, redirects, subshells or other compounds, environment assignment prefixes, and any word with a non-literal part (parameter expansion, command substitution, globs, backticks — including the executable itself) disqualifies the whole command and keeps it sandboxed. Wrapper and context builtins (env, sudo, exec, source, command, sh, …) are rejected outright. A pattern is either an exact command line or a "<prefix> *" wildcard; matching is token-by-token against the static argv, so quoted arguments can never forge pattern boundaries.
func TouchesProtectedPath ¶
TouchesProtectedPath parses cmdStr and reports whether any command executable, argument, redirection, or command substitution references a protected control-plane, secret, XDG policy, or sensitive host path.
Types ¶
type ArgRule ¶
type ArgRule struct {
Category api.ActionType
Subcommands []string // Matches if the subcommand matches any of these
ContainsAny []string // Matches if args contain any of these flags/words
ContainsAll []string // Matches if args contain all of these flags/words
}
ArgRule defines conditional classification based on command arguments.
type CommandChain ¶
type CommandChain struct {
Pipelines []Pipeline
IsCompound bool // True if the AST contains control flow or multi-statement inline scripts
}
CommandChain represents a sequence of commands grouped by ;, &&, ||, or &.
func Parse ¶
func Parse(commandStr string) (CommandChain, error)
Parse parses a raw shell command string into a CommandChain.
type CommandRule ¶
type CommandRule struct {
DefaultCategory api.ActionType
TargetMode TargetMode
ValueFlags []string // Flags that consume the next arg as a non-path value (e.g. "-m", "-e", "-n")
PathFlags []string // Flags that consume the next arg as a path target (e.g. "-C", "-f", "--file")
SubcommandModes map[string]TargetMode // Optional per-subcommand TargetMode override (e.g. for git subcommands)
ArgRules []ArgRule
}
CommandRule defines classification and target extraction rules for a specific executable.
type Config ¶
type Config struct {
WorkspaceDir string
HomeDir string // Optional; used for ~ expansion (falls back to os.UserHomeDir once at New() time)
ProtectedDirs []string // Defaults to DefaultProtectedDirs (.git, .bare, .agents)
ReadDirs []string // Additional read-allowed directories outside WorkspaceDir (marked SafetySafe for reads)
WriteDirs []string // Additional read/write/delete-allowed directories outside WorkspaceDir (marked SafetySafe)
MaxOperations int // Defaults to DefaultMaxOperations (3)
Policy *Policy // Defaults to DefaultPolicy()
}
Config configures a Guard instance.
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard performs AST-based shell command analysis and permission matching.
func New ¶
New constructs a Guard with the provided configuration, applying sensible defaults for any omitted fields.
func (*Guard) Analyze ¶
Analyze parses the command string and returns operations for permission evaluation. If the command chain produces more than g.maxOperations operations or contains compound control-flow clauses / multi-statement inline scripts, it collapses them into a single summary Operation (IsCompound: true).
func (*Guard) AnalyzeDetailed ¶
AnalyzeDetailed parses the command string and returns all individual granular operations without compound collapsing.
func (*Guard) EvaluatePath ¶
func (g *Guard) EvaluatePath(targetPath string, action api.ActionType) (string, api.SafetyLevel)
EvaluatePath resolves targetPath against the Guard's workspaceDir (and expands ~ with homeDir) and classifies its SafetyLevel for the given ActionType.
func (*Guard) IsInReadDirs ¶
IsInReadDirs reports whether targetPath resolves inside one of the Guard's configured ReadDirs.
func (*Guard) IsInWriteDirs ¶
IsInWriteDirs reports whether targetPath resolves inside one of the Guard's configured WriteDirs.
func (*Guard) IsProtectedPath ¶
IsProtectedPath reports whether targetPath (either workspace-relative or absolute within the workspace) resides inside one of the Guard's configured protected directories (such as .git, .bare, or .agents).
func (*Guard) Match ¶
func (g *Guard) Match(grantTarget string, matchMethod string, cmd ParsedCommand) bool
Match checks if a parsed command matches a user's permission grant target. It supports wrapper unpacking, wildcard argument matching (e.g. "git *"), and subcommand matching (e.g. "git commit").
func (*Guard) PathPosture ¶
PathPosture reports whether targetPath is confined inside the Guard's workspace directory and whether it (or its symlink target) points to a protected control-plane, secret, XDG policy, or sensitive host path.
func (*Guard) TouchesProtectedPath ¶
TouchesProtectedPath parses cmdStr and reports whether any command executable, argument, redirection, or command substitution references a protected control-plane, secret, XDG policy, or sensitive host path.
type Operation ¶
type Operation struct {
Command *ParsedCommand // Link back to the AST node (or summary command when collapsed)
Action api.ActionType
Safety api.SafetyLevel
Path string // Resolved virtual CWD or target file
CWD string // Virtual CWD at command execution
IsCompound bool // True when collapsed from a complex script or > MaxOperations
}
Operation represents an evaluation of a command target.
type ParsedCommand ¶
type ParsedCommand struct {
Env []EnvVar // Environment variable assignments, e.g. PORT=8080
Executable string // Command executable, e.g. "git", "npm", "sudo"
Args []string // Arguments, e.g. ["commit", "-m", "hello"]
ArgsIsDynamic []bool // Indicates if the corresponding argument contains variables/subshells
Redirects []Redirect // Parsed redirects, e.g. > out.log
SubCommand *ParsedCommand // Recursive sub-command (if executable is a wrapper like sudo, npx, bash -c)
SubChain *CommandChain // Full parsed sub-chain for multi-command wrapper invocations (e.g., bash -c "a && b")
Subshell *CommandChain // Isolated subshell command chain for (...) nodes
SubstCommands []ParsedCommand // Commands extracted from command substitutions $(...) or `...`
HasCmdSubst bool // True if the command uses $(...) or `...`
Raw string // Raw command string (populated for collapsed compound summary commands)
}
ParsedCommand represents a single command invocation or subshell block.
type Pipeline ¶
type Pipeline struct {
Commands []ParsedCommand
Operator string // "&&", "||", ";", "|", "&", or "" (empty string for last command)
}
Pipeline represents commands piped together (cmd1 | cmd2) or chained.
type Policy ¶
type Policy struct {
DefaultCategory api.ActionType
Rules map[string]CommandRule
}
Policy defines the declarative ruleset for command classification and argument target extraction.
func DefaultPolicy ¶
func DefaultPolicy() Policy
DefaultPolicy returns the built-in declarative classification and argument extraction ruleset.
type Redirect ¶
type Redirect struct {
Op string // ">", ">>", "<", "<&", ">&"
Fd int // Source file descriptor (1 for stdout, 2 for stderr)
Target string // Target file path or stream
IsDynamic bool // True if target contains variables or command substitution
}
Redirect represents an I/O redirection attached to a command.
type TargetMode ¶
type TargetMode uint8
TargetMode specifies how positional arguments of a command are extracted as filesystem paths during safety analysis.
const ( TargetsAll TargetMode = iota // All positional args are paths (default) TargetsNone // Positional args are never paths (echo, printf, sleep, etc.) TargetsSkipFirst // First positional arg is pattern/script/mode; rest are paths (grep, rg, sed, chmod, chown, jq, yq) TargetsLast // Only the last positional arg is the destination path (cp) TargetsAfterDashDash // Only positional args after "--" are paths (git ref commands) TargetsPredicateStop // Positional args before the first "-" predicate/operator are paths (find) )