shellline

package
v1.2.0 Latest Latest
Warning

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

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

Documentation

Overview

Package shellline reads a command line into the commands it would run.

It is the structural layer two policy surfaces share: the HITL gate that decides ask/allow/deny before a tool call runs, and the shell tool's own command policy that decides what may execute at all. Parsing lives here so both reason about the same commands; what to do about them stays with the caller.

Index

Constants

View Source
const MaxLineBytes = 64 * 1024

MaxLineBytes bounds what is parsed; a longer line is not read at all.

View Source
const UnknowableTarget = "(not statically knowable)"

UnknowableTarget stands in for a redirect target that only exists at run time, so a decision message can say so rather than showing an empty string.

Variables

This section is empty.

Functions

func ArgTokens

func ArgTokens(v any) []string

ArgTokens reads a tool call's args field, which arrives as a list or as one already-split string.

func DecodeEscapes

func DecodeEscapes(s string) string

DecodeEscapes resolves the escapes printf and `echo -e` would expand, which is how a payload printed as text becomes the command it spells.

func DigitValue

func DigitValue(c byte) int

DigitValue is the value of one ASCII digit, or -1 when it is not one.

func DisplayWords

func DisplayWords(words []string) string

DisplayWords renders already-resolved words for a message.

func FlattenDisplay

func FlattenDisplay(parts []string) string

FlattenDisplay renders a command for a message, with control characters flattened so a decision message cannot forge a log line or terminal escape, and truncated so one command cannot fill the line.

func LenientWords

func LenientWords(call *syntax.CallExpr) []string

LenientWords reads a call's words, using "" for one that only exists at run time, so a caller can still resolve the program and its shape.

func LiteralAssignments

func LiteralAssignments(file *syntax.File) map[string]string

LiteralAssignments collects the plain `NAME=value` assignments in a line, which is what lets a later `$NAME` resolve to a word.

func LiteralWord

func LiteralWord(word *syntax.Word) (string, bool)

LiteralWord resolves a word to its exact value when nothing about it depends on run time. Globs, expansions, substitutions, tilde and backslash escapes all make a word unknowable, because the value that reaches the program is then not the value in the line.

func ModeRequested

func ModeRequested(args map[string]any) bool

ModeRequested reports whether a call asked for shell interpretation, which is what makes its command a line rather than a single argv.

func ParseEscapedNumber

func ParseEscapedNumber(s string, base, maxDigits int) (value byte, width int, ok bool)

ParseEscapedNumber reads at most maxDigits digits in base, refusing a value that does not fit a byte.

func ParseFile

func ParseFile(src string) (file *syntax.File, bashOnly bool, ok bool)

ParseFile reads src with the POSIX grammar first and the bash grammar second. bashOnly reports a line only the second parse accepts.

func Parses

func Parses() int64

Parses counts the lines parsed in this process, which is how a caller proves a line was read rather than guessed at.

func ResolveAssignedWords

func ResolveAssignedWords(call *syntax.CallExpr, assigns map[string]string) ([]string, bool)

ResolveAssignedWords re-reads a call's words with the line's assignments substituted, so `CMD=x; $CMD -v` resolves to `x -v`. It reports false when nothing was resolved or the program itself stays unknowable.

func SoleParamName

func SoleParamName(word *syntax.Word) (string, bool)

SoleParamName reports a word that is exactly one parameter reference, which is the only shape an assignment can be substituted into.

func Structural

func Structural(trusted Kind, goos string) bool

Structural reports whether a command line of this kind can be read at all. A trusted kind is required: the kind a call claims about itself is a claim, not evidence, so an empty kind is only trusted where the host can produce nothing else.

func UnescapeDoubleQuoted

func UnescapeDoubleQuoted(s string) string

UnescapeDoubleQuoted peels the escapes bash honors inside double quotes, leaving the rest as written.

func UnescapeUnquoted

func UnescapeUnquoted(s string) string

UnescapeUnquoted peels backslash escapes outside quotes; a trailing backslash is a line continuation and disappears.

func WithKind

func WithKind(ctx context.Context, kind string) context.Context

WithKind marks ctx with the shell that will interpret command lines evaluated under it, enabling structural analysis when the shell is POSIX.

func WordName

func WordName(word *syntax.Word) (string, bool)

WordName resolves a word the way a lenient reader must: quotes and escapes are peeled, so `r”m` names rm, while a word whose value only exists at run time has no name at all.

Types

type Kind

type Kind string

Kind names the shell that will interpret a command line.

const (
	// KindPOSIX is the only kind structural analysis runs on: `sh -c`.
	KindPOSIX Kind = "sh"
	// KindPowerShell is what the shell tool spawns on Windows; mvdan
	// cannot parse it, so it never reaches the parser.
	KindPowerShell Kind = "powershell"
	// KindCmd is cmd.exe — same treatment as powershell.
	KindCmd Kind = "cmd"
	// KindUnknown is any kind this package does not recognize; distinct
	// from "" so an unrecognized kind fails closed.
	KindUnknown Kind = "unknown"
)

func KindFromContext

func KindFromContext(ctx context.Context) Kind

KindFromContext returns the trusted shell kind set by WithKind, or "" when none was set.

func NormalizeKind

func NormalizeKind(s string) Kind

NormalizeKind maps a shell name to the kind that parses it.

type Line

type Line struct {
	// Readable is false when structural analysis does not apply to the shell
	// that would interpret this line, which is a refusal for any caller that
	// would otherwise allow something: an unreadable line is not a safe line.
	Readable bool
	// Parsed is false when the line could not be read at all, which is a
	// refusal for any caller that would otherwise allow something.
	Parsed bool
	// BashOnly marks a line only the wider second parse accepts: sh, the
	// executor, would reject the reading, so it can never ground an allow.
	BashOnly bool
	// Steps are the simple commands, top level and in order.
	Steps []Step
	// File is the parsed line, for a caller that reasons about nodes this
	// record does not describe (nesting, pipes, producers).
	File *syntax.File
	// Redirects are the redirects on top-level statements.
	Redirects []Redirect
	// CommandSubst, ProcessSubst and ArithmExp mark run-time values in the
	// line: `$(…)`, `<(…)` and `$((…))`.
	CommandSubst bool
	ProcessSubst bool
	ArithmExp    bool
	// Background, Negated, Coprocess and Control mark statements that are
	// not a plain sequence: `cmd &`, `! cmd`, `coproc`, and compound
	// constructs such as if/for/while/case/subshell/function.
	Background bool
	Negated    bool
	Coprocess  bool
	Control    bool
	// Pipelines counts steps joined by `|`, which no argv-only executor can
	// honour.
	Pipelines int
}

Line is what one command line would do, in execution order.

func LineFromArgs

func LineFromArgs(args map[string]any, kind Kind, goos string) (Line, bool)

LineFromArgs reads the command line a tool call carries: the command, plus its args when the call asked for shell interpretation, and nothing when the call keeps them apart (that shape is a single argv, not a line).

func Parse

func Parse(src string, kind Kind, goos string) Line

Parse reads src as a command line of the given kind. A line that cannot be read, or that this kind of shell would not interpret, comes back with Parsed false.

type Operator

type Operator string

Operator joins a step to the one before it.

const (
	// OpStart is the first step of a line.
	OpStart Operator = ""
	// OpAnd runs the step only when the step before it succeeded.
	OpAnd Operator = "&&"
	// OpOr runs the step only when the step before it failed.
	OpOr Operator = "||"
	// OpSeq runs the step whatever the step before it did.
	OpSeq Operator = ";"
	// OpPipe feeds the step's output to the step after it.
	OpPipe Operator = "|"
)

type Redirect

type Redirect struct {
	Op      string
	Target  string
	Heredoc bool
}

Redirect is one redirection, with its target when that target is literal.

func RedirectView

func RedirectView(redir *syntax.Redirect) Redirect

RedirectView reads one redirection, naming its target when that is literal.

type Step

type Step struct {
	Operator Operator
	// Name is the program as spelled, Base its basename, and Display the
	// command as a decision or a refusal should quote it.
	Name    string
	Base    string
	Display string
	// Words is the full argv, program included, only when Literal is true.
	Words   []string
	Literal bool
	// ArgCount counts Words as spelled, which is what a prefix match needs
	// when the words themselves are not knowable.
	ArgCount int
	// Assigns are the environment assignments prefixed to the call.
	Assigns []string
}

Step is one simple command: a program and its literal arguments, or, when Unreadable, only what could be read of it.

func StepFromCall

func StepFromCall(call *syntax.CallExpr) Step

StepFromCall reads one simple command, resolving its words only when every word is knowable without running anything.

func WordsFromValues

func WordsFromValues(words []string) Step

WordsFromValues renders words that came from a decoded payload, which is how a revealed command is spelled back into a decision.

Jump to

Keyboard shortcuts

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