shellfacts

package
v1.5.84 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package shellfacts describes what a shell command will do, parsed rather than guessed at.

The rule that shapes every line: this package produces FACTS, never verdicts. It says "this argv vector, this redirect, this nested command, this word is dynamic" — and nothing about whether any of it is safe. Deciding belongs to the layers above, because a permission decision needs context a parser does not have (what the user asked for, which directory is trusted, what the program does with its arguments).

Why parse at all. A guard that pattern-matches the raw command string is answering a different question than the shell will: bash performs quote removal, parameter expansion, command substitution and field splitting AFTER any string match has run, so the bytes a matcher sees are not the argv that executes. That gap is where shell-injection bypasses live (`r”m` becomes `rm`; `$IFS` becomes whitespace; `$(echo rm)` becomes a program name). This package closes the gap by handing the caller the argv vectors bash would build, instead of making it infer them from text.

What it deliberately does NOT do:

  • It never expands anything. No variable is looked up, no command is run, no glob touches the filesystem. A word carrying `$VAR` is reported as dynamic WITH the variable's name, and a word carrying `$(...)` gets its body parsed as a nested plan — because "this will execute something" is the fact that matters, and executing it to learn its output would be the exact mistake this package exists to avoid.
  • It never decides. There is no "is this safe", no allowlist, no confidence. A caller that wants a verdict builds one from these facts.

A parse failure is itself a fact: a real command line that this parser cannot read (an unterminated quote, a zsh-only construct) leaves the shell reading more input, so callers must treat Parsed == false as "unknown", never as "harmless".

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Access

type Access struct {
	// Path is the path as written, with quotes removed. Empty for a target that
	// cannot be named (a dynamic redirect target like `> $OUT`).
	Path string
	// Op is what the command does to it. UnknownOp means the operation depends
	// on the program's semantics — an argument — and the caller must narrow it
	// with knowledge this package does not have.
	Op Op
	// Dynamic reports that the path is not fully known: it contains a variable,
	// a glob, or a substitution. A caller must not treat Path as the whole
	// story, and must not hand out a grant wider than the written text.
	Dynamic bool
	// CommandIndex is the command that touches it, so a dialog can name the
	// step and a reviewer can see them together.
	CommandIndex int
	// Origin says where in the command the path came from: "redirect",
	// "command", "argument", or "nested" for one inside a substitution.
	Origin string
	// Nested reports that this path is inside a command substitution or process
	// substitution: it is touched by a command that runs first, and the reason
	// substitutions deserve their own line in a dialog.
	Nested bool
}

Access is one path a command touches, with what it does there and why.

type AccessSummary

type AccessSummary struct {
	Path string `json:"path"`
	Op   Op     `json:"op"`
	// Dynamic reports that at least one occurrence was dynamic.
	Dynamic bool `json:"dynamic,omitempty"`
}

AccessSummary groups the accesses by path, keeping the operation set. A dialog needs "golder wants to read /x and write /y", not two rows for the same path when a command both reads and writes it.

type Command

type Command struct {
	// Index is this command's position in the program's execution order.
	Index int
	// Argv is the argument vector, command position first.
	Argv []Word
	// Assigns are the leading `VAR=value` words. They are separated from Argv
	// because a shell treats them as environment for this command, not as
	// arguments — and because an assignment in command position is how
	// `LD_PRELOAD=… ls` runs something other than what it appears to.
	Assigns []Word
	// Redirs are this command's redirections.
	Redirs []Redirect
	// Nested holds the bodies of any command or process substitutions inside
	// this command's words, in order of appearance.
	Nested []*Plan
	// Background reports a trailing `&`.
	Background bool
	// Negated reports a leading `!`.
	Negated bool
	// InPipeline reports that this command's output feeds another.
	InPipeline bool
	// InSubshell reports that this command runs in a subshell rather than the
	// shell's own process.
	InSubshell bool
}

Command is one simple command in the program, with the shape the caller needs in order to reason about it.

func (Command) Args

func (c Command) Args() []Word

Args returns the words after the command word. They are NOT the same as argv with the program removed when an assignment prefix is present, which is why Assigns is separate.

func (Command) Program

func (c Command) Program() (string, bool)

Program returns the command word's text and whether it was a plain literal. A dynamic command word means the program itself is computed at runtime, which is the most important fact about a command and the one a string matcher cannot see: `$(echo rm) -rf /` has no literal program at all.

type Op

type Op uint8

Op is an operation on a path. It mirrors what a shell or program does to the path, not what any policy thinks about it.

const (
	// Read opens or lists the path.
	Read Op = 1 << iota
	// Write creates, truncates, appends to or deletes the path.
	Write
	// Execute runs the path as a program (a path in command position).
	Execute
	// UnknownOp means the path was named but the operation depends on program
	// semantics this package does not have. A caller must treat it as possibly
	// destructive rather than guessing.
	UnknownOp
)

func (Op) MarshalJSON

func (o Op) MarshalJSON() ([]byte, error)

MarshalJSON sends the words rather than the bitmask. The state this type travels in is read by a model, and `"op":2` is not a fact any reader can use — it was the whole operation set rendered as a number.

func (Op) String

func (o Op) String() string

String renders the operation set as "+"-joined words: "write", "read+write", "read+execute". It used to answer "mixed" for any set of more than one bit, which was ambiguous in two ways at once — Read|Write and Read|Write|UnknownOp both printed as "mixed" — and this form is also what goes on the wire (see MarshalJSON), so a reader that is not a Go program can tell what the call does.

An empty set renders as "unknown": the bit means exactly "the path was named and nothing about the operation could be determined".

func (*Op) UnmarshalJSON

func (o *Op) UnmarshalJSON(b []byte) error

UnmarshalJSON reads the words back, so a round trip through the wire form preserves the set. An unrecognized word is an error rather than a silently dropped bit: a reader that quietly ignored "read+write" would turn a write into a read.

type Part

type Part struct {
	Kind PartKind
	// Text is the literal text (for LiteralPart and QuotedPart) or the variable
	// name (for VariablePart). Empty otherwise.
	Text string
	// Nested is the parsed body of a command substitution. It is present so a
	// caller can see what will run; it is never executed here.
	Nested *Plan
}

Part is one segment of a word.

type PartKind

type PartKind string

PartKind is what one segment of a word is. The kinds exist so a caller can see WHY a word is dynamic without re-parsing it.

const (
	// LiteralPart is ordinary text.
	LiteralPart PartKind = "literal"
	// QuotedPart is single- or double-quoted text. Quotes are removed from the
	// text, because that is what the shell does before the word reaches argv.
	QuotedPart PartKind = "quoted"
	// VariablePart is `$VAR` or `${VAR}`. The value is NOT resolved.
	VariablePart PartKind = "variable"
	// CommandSubstPart is `$(...)` or backticks: a command that will run before
	// this one. Its body is parsed into Nested.
	CommandSubstPart PartKind = "command-substitution"
	// ArithmPart is `$((...))`.
	ArithmPart PartKind = "arithmetic"
	// GlobPart is an unquoted `*`, `?` or `[...]`: a path the shell computes by
	// reading a directory.
	GlobPart PartKind = "glob"
	// ProcSubstPart is `<(cmd)` or `>(cmd)`: a FIFO the shell creates.
	ProcSubstPart PartKind = "process-substitution"
	// ExtGlobPart is bash's `@(a|b)`, `!(a)` and friends: a word that decides
	// itself from the filesystem.
	ExtGlobPart PartKind = "extglob"
	// TildePart is a leading unquoted `~`: the shell replaces it with a home
	// directory, so the word's value is not the text.
	TildePart PartKind = "tilde"
)

type Plan

type Plan struct {
	// Raw is the text this plan was parsed from, unchanged. It is kept because
	// the parser can be wrong: a caller comparing Raw against Commands can see
	// a construct this layer represented poorly, and the model reviewer (which
	// reads prose) can still see the original.
	Raw string
	// Parsed reports whether the text parsed as a complete program. False means
	// the shell would keep reading (an unterminated quote) or the construct is
	// not POSIX/bash — either way nothing here may be treated as complete.
	Parsed bool
	// ParseError is the parser's message when Parsed is false.
	ParseError string
	// Commands are the TOP-LEVEL simple commands, in execution order. A command
	// substitution's own commands are NOT here: they hang off the containing
	// command's Nested field, so the structure of the line stays readable.
	//
	// That split is a trap for a caller enumerating commands to decide
	// something: `echo "$(rm -rf /x)"` has one top-level command (`echo`), and
	// iterating this slice alone would never see the `rm`. Use AllCommands for
	// any enumeration that must be complete — it is the safe default for
	// deciding, and this field is for showing.
	Commands []Command
	// Constructs names command forms this layer walked past without describing:
	// a loop, a function definition, a conditional. They are reported rather
	// than ignored, because "there is a for loop here" is exactly the kind of
	// fact a caller needs in order to decline to reason about the command.
	Constructs []string
}

Plan is what one command line will do.

func Parse

func Parse(command string) *Plan

Parse reads one command line. It never returns an error: a failure to parse is reported in the Plan, because callers must treat "could not read it" as a fact distinct from "there is nothing there".

func (*Plan) AllCommands

func (p *Plan) AllCommands() []Command

AllCommands returns every command in the plan, including the ones inside command and process substitutions, in execution order: a substitution runs before the command containing it, so its commands come first.

This is the enumeration a caller deciding something must use. Commands alone is a trap there: `echo "$(rm -rf /x)"` has exactly one top-level command, and the `rm` is reachable only through Nested. Two ways to enumerate a plan is one too many, so the safe one is named for what it is and the other is documented as the display view.

func (*Plan) Enumerable added in v1.3.4

func (p *Plan) Enumerable() (bool, string)

The parser already knows what it could not resolve — a variable, a substitution, an assignment it cannot expand. Enumerable turns those facts into the one yes/no a caller can act on, and it exists because some decisions treat the argv as the whole story: which paths a consent question must cover, whether a single path can stand for the call, and whether a command may run outside the OS sandbox, where nothing else bounds it.

The answer is deliberately conservative, and it is a property of the READING, not of the intent:

  • a glob stays enumerable: `src/*.go` is bounded by the directory it is written against, and the caller's question is which place is touched;
  • a `~` stays enumerable: the shell expands it to a value this process knows (its own home), which is exactly the fact the boundary gate wants;
  • a `$VAR`, a `$(...)`, an arithmetic expansion or a process substitution does not: the value is a runtime fact, and nothing here may guess it;
  • an environment assignment that changes what runs or what code is loaded does not: `PATH=…` picks another program, `LD_PRELOAD=/x.so` injects one, `HOME=…` moves the configuration and credentials the same command reads. The test is the VARIABLE'S NAME, not the shape of its value; `GOCACHE=/tmp/cache go test` is a cache directory and stays enumerable;
  • a construct this layer walked past does not: a loop or a conditional is reported rather than described, and "there is a for loop here" is precisely the fact that says "do not reason about this from the text".

False means "treat this call as one whose effect cannot be bounded from its text", never "there is nothing here".

func (*Plan) PathAccesses

func (p *Plan) PathAccesses() []Access

PathAccesses returns every path this plan touches, in execution order.

The walk covers all three places a path can hide, because a guard that reads only the argv misses two of them:

  • redirection targets, where the operation is fixed by shell semantics (`>` writes, `<` reads) and never appears among the arguments;
  • the command word, when it is path-shaped — that is an execute;
  • arguments, where the operation is the program's business.

Substitutions are descended into, so `cat $(echo /etc/passwd)` reports the inner command's own access rather than only the outer `cat`. Their entries carry Nested so a caller can present them as what they are: commands that will run before this one does.

func (*Plan) Summary

func (p *Plan) Summary() []AccessSummary

Summary folds the access list into one entry per path, in first-seen order.

type Redirect

type Redirect struct {
	// Fd is the file descriptor, 1 for stdout when unspecified.
	Fd int
	// Target is where the descriptor points. For a descriptor duplication
	// (`2>&1`) it is the other descriptor as text, and Dup is true.
	Target Word
	// Op is the shell's operator text: ">", ">>", "<", "<>", ">|", "<<", "<&",
	// ">&", "&>", "&>>".
	Op string
	// Dup reports a descriptor duplication, which names no path.
	Dup bool
	// Heredoc reports `<<`/`<<-`: the body is further shell input.
	Heredoc bool
}

Redirect is one redirection, with its operation already decided because shell redirection semantics are fixed (`>` writes, `<` reads) — unlike a path passed as an argument, whose operation depends on the program.

type Word

type Word struct {
	// Text is the word's text with quotes removed and literals joined. It is
	// the argv spelling when Dynamic is false, and a best-effort spelling
	// otherwise — a word spelled `"$HOME"/x` reads as `/x` with a variable part,
	// so callers must consult Dynamic before trusting Text as a path.
	Text string
	// Dynamic reports that some part expands at runtime, so this word's argv
	// value is not fixed by the text.
	Dynamic bool
	// Parts is every segment, in order.
	Parts []Part
}

Word is one argument as the shell would build it, as far as that can be known without expanding anything.

Jump to

Keyboard shortcuts

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