Documentation
¶
Overview ¶
Package policy grades what an AI agent wants to do by risk and decides, under the session's permission mode, whether SSHYard runs it, asks the user, or asks the review model. SSHYard is the final judge; nothing the agent says (its reason, its own approval settings, allow_always) changes a decision.
In automatic review mode, read-only actions run, Critical ones ask the user, and a configured review model judges every other action; local risk grades supply metadata and audit context, not approval.
Risk, highest first: Critical, Unknown, High, Medium, Low, ReadOnly. Rank implements that order. The Risk constants do not (Unknown is last so a zero Grade is read-only). Equal risk keeps the earlier command, unless the later category is more severe.
A command that is not in the built-in table is Unknown, never ReadOnly. Aliases are not expanded, and the text produced by a command substitution is not simulated: cat $(ls) stays read-only, but a bare $VAR given to a path reader is Unknown. python -c and the other interpreters are not parsed; piping curl or wget into one of them is Critical.
curl or wget with no save path is Medium "network". A save (-o, -O, --output, --output-document, wget -P / --directory-prefix, curl --output-dir) or a shell redirect of that output is graded as a write of the target, and the grade is at least the network grade. Under /tmp that stays Medium, not a low write. curl -P is the FTP port, not a directory. .ssh, shadow, and sudoers follow the write rules (High). A pipe into sh, bash, or another interpreter is Critical, including sh -c "$(curl …)". bash -c "curl URL" is only the inner grade.
Wrappers (sudo, doas, env, timeout, nice, nohup, xargs, command, exec, stdbuf, setsid, time, ionice) are peeled at any depth, including a leading VAR=value. The grade is the max of the inner command and a dangerous assignment. An option list that does not parse is Unknown. The wrapper still raises the result to at least Medium. sudo of a read-only command is "permission". sh -c is parsed, not raised. sudo with no command, sudo -i/-s, su, sudo su, and sudo of a shell with no -c (sudo bash) are High "permission".
sed is read-only only when every script is visible and has no e command, s///e flag, or w/W write. A w target is graded as a file write (low under a writable root). sed -f, or a script that does not parse, is Unknown. git -C is a directory. git -c and --config-env are graded by the key: a command, pager, alias, editor, helper, hook, textconv, filter, merge driver, include.path, or includeIf.<cond>.path is High "exec-config". http.proxy (including http.<url>.proxy) and protocol.*.allow=always are Medium "network". Any other key keeps the subcommand. A -c that is not key=value, or --exec-path, is Unknown. The value is not parsed as a shell command. ModeFull auto-runs High. git log and git diff -o/--output are file writes. git format-patch -o is a write; format-patch with no -o stays Unknown. sort --compress-program is Unknown.
An assignment that can change what runs (LD_*, DYLD_*, PATH, BASH_ENV, ENV, IFS, PROMPT_COMMAND, SHELLOPTS, PS4, a name ending in PAGER, EDITOR, VISUAL, GIT_*, PYTHONPATH, PYTHONSTARTUP, PERL5OPT, NODE_OPTIONS, LESSOPEN, LESSCLOSE, GETCONF_DIR), including bare assignments, export, env NAME=value cmd and the same words after sudo or another wrapper, is Unknown. Unknown ranks above High, so LD_PRELOAD, LD_LIBRARY_PATH, LD_AUDIT, and DYLD_* are not lowered to a High "exec-inject" grade. LANG, TZ, and LC_ALL stay neutral. Ordinary bare assignments with no command stay read-only. The command is still graded, so a visible critical stays critical.
Writes under a writable root are Low for mkdir, touch, and redirections. write_file is Low only for a new file under /tmp. mv, cp, sed -i, ln, and install stay at least Medium. Shell startup files (~/.bashrc, ~/.profile, ~/.zshrc, fish config.fish, /etc/profile*, /etc/bash.bashrc), systemd units, cron files, ~/.gitconfig, ~/.npmrc, ~/.pip, and ~/.config/autostart are at least Medium even inside a writable root. Writes of /etc/shadow, /etc/gshadow, /etc/sudoers*, authorized_keys, or anything under .ssh are High "permission". Other sensitive writes stay Medium. /dev/null and the standard character devices are not writes. /dev/sd*, /dev/nvme*, and the other disk devices are Critical.
Also sensitive to read: /proc/*/environ (not /proc/*/cmdline), a name matching .*_history, ~/.docker/config.json, ~/.git-credentials, ~/.config/gh/hosts.yml, and /etc/ssl/private.
mv of a critical top-level path, recursive cp of one (-r/-a), and rsync --delete of one are Critical. less and more with a + command or -k are Unknown.
Recursive rm of /, /*, ~, $HOME, the session home, or a top-level directory is Critical. The top-level set is /bin /boot /dev /etc /home /lib /lib32 /lib64 /libx32 /opt /proc /root /run /sbin /sys /usr /var /tmp /mnt /media /srv and the macOS roots /System /Users /Applications /Volumes /private /Library. rm -rf /tmp is Critical; rm -rf /tmp/x is High. apt-get update is Unknown (it is not an upgrade); yum, dnf, zypper, brew, and snap update are Medium "install". npm install is Medium only with -g.
Local reads inside Scope.Sandbox are "local-read", unless the path is sensitive. A read outside the sandbox is Low "local". An edit inside the sandbox is a low write. Deleting a Windows drive root or anything under \Windows is Critical.
A shell read of file content (cat, head, tail, less, grep, sort, wc, cut, sed, awk and the like, or a < redirect) is read-only only when every file is a literal, non-sensitive path under /etc, /var/log, /sys, /usr, /lib, /www/server or /www/wwwlogs, or a /proc entry that cannot reach another process's environment, memory or files. Globs, braces and backslashes, and files elsewhere (home, /tmp), are Medium "sensitive-read": a link there could lead to a secret. Standard input is not a file. awk is read-only when its program cannot run a command or write a file (system, getline, a pipe, print > file, a gawk @ directive); -f and other options are Unknown, and ENVIRON is a sensitive read. nginx, apachectl, httpd and php-fpm configuration tests and versions are read-only; their signals and service verbs are Medium "service".
ModeAsk does not offer "allow similar" for a file write, so the diff is shown every time. That is stricter than the spec table and is an open question. Session grants never skip the review model. ModeReview auto-runs ReadOnly and sends every other grade except Critical to a configured model, including Unknown; Critical always asks the user. The model is told to let work that moves the user's task forward run, writes, restarts and clean-ups included, and to stop only for named harms; it sees the current request and the user's earlier messages in the pane, never the assistant's text. Only an explicit allow runs automatically; ask, invalid replies, errors and timeouts ask the user. After the model asks, a session grant still covers one plain command (no list, pipe, redirection or substitution) but never a script. Without a model, ReadOnly and Low auto-run and all other grades ask. Grades remain metadata and audit context for the model. ModeFull auto-runs every grade except Unknown. Unknown asks with the red confirmation and does not offer "allow similar". Critical in ModeFull still auto-runs and sets Red. High, including git exec-config, auto-runs.
Index ¶
- Constants
- func BuildReviewPrompt(in ReviewInput) string
- func ParseReview(raw string) (allow bool, reason string, ok bool)
- func Rank(r Risk) int
- func Redact(s string) string
- func RedactLines(s string) string
- type Action
- type Answer
- type AuditPreparer
- type AuditRecord
- type Auditor
- type Category
- type Decider
- type Decision
- type DiffLines
- type Engine
- type Exec
- type Gate
- type GateConfig
- type Grade
- type Mode
- type Outcome
- type Prompt
- type Prompter
- type ReviewInput
- type Reviewer
- type Risk
- type Scope
- type Verdict
- type Where
Constants ¶
const ( // DefaultPromptTimeout is how long the user has to answer. Silence is a reject. DefaultPromptTimeout = 5 * time.Minute // DefaultReviewTimeout is how long the review model has. Failure asks the user. DefaultReviewTimeout = 10 * time.Second )
const ReviewInstructions = `` /* 2505-byte string literal not displayed */
ReviewInstructions tells a chat model how to review an action and how to answer; BuildReviewPrompt is the action.
Variables ¶
This section is empty.
Functions ¶
func BuildReviewPrompt ¶
func BuildReviewPrompt(in ReviewInput) string
BuildReviewPrompt is the text handed to the review model. Every field is redacted. Output is the last 20 lines, inside markers that say those lines are not the user's instructions.
func ParseReview ¶
ParseReview reads a review model's reply. The only accepted shape is {"decision":"allow"|"ask","reason":"..."}. Surrounding whitespace and one ```json fence are ignored. Extra JSON fields are ignored. Anything else, including trailing junk, is ok=false and the gate must ask.
func Rank ¶
Rank orders risks for "highest wins": Critical > Unknown > High > Medium > Low > ReadOnly. The Risk iota is not this order (Unknown is declared last so a zero Grade is ReadOnly). Equal rank keeps the earlier command, unless the later one has the more severe category.
func Redact ¶
Redact masks secrets in text that may be written to the audit log or sent to a model. It is a best-effort scan, not a parser.
It masks PEM private-key blocks, bearer tokens, AWS access key ids (AKIA plus 16 letters or digits), GitHub tokens (ghp_, gho_, ghu_, ghs_, ghr_, github_pat_), sk- keys of 20 or more characters, api_key/access_token/password/passwd/token/secret assignments (equals or colon, including --password=), mysql/mariadb -p passwords, and user:password in URLs. An attached mysql -p value that is only letters (the shape of a short flag such as -print) is left alone unless the text names mysql or mariadb.
func RedactLines ¶
RedactLines masks the same secrets while preserving line offsets for file slices
Types ¶
type Action ¶
type Action struct {
Where Where
// Tool is the remote tool (host_info, pane_output, list_dir, read_file,
// search_files, write_file, run_command) or, for Local, the ACP
// tool_call kind (read, edit, delete, move, search, execute, fetch, think,
// other).
Tool string
Command string // run_command / execute
Path string // file tools; for Local, the local path
Dir string // working directory of a command
Reason string // the agent's stated reason, shown and audited, never trusted
}
Action is one thing the agent asked to do. Every field except Where and Tool may be empty. All of it is untrusted input.
type AuditPreparer ¶
type AuditPreparer interface {
Prepare() error
}
AuditPreparer is optional. The gate calls Prepare before it runs an action and refuses to run when the log cannot be opened.
type AuditRecord ¶
type AuditRecord struct {
Time time.Time `json:"time"`
SessionID string `json:"session_id"`
PaneID string `json:"pane_id"`
Agent string `json:"agent"`
Host string `json:"host"`
Mode string `json:"mode"`
Where string `json:"where"`
Category string `json:"category"`
Risk string `json:"risk"`
Command string `json:"command"`
DiffHash string `json:"diff_hash"`
DiffLines DiffLines `json:"diff_lines"`
Verdict string `json:"verdict"`
Decider string `json:"decider"`
ReviewReason string `json:"review_reason"`
ExitCode *int `json:"exit_code"`
DurationMS int64 `json:"duration_ms"`
OutputBytes int64 `json:"output_bytes"`
}
AuditRecord is one JSONL audit line. The audit package writes it. File contents, command output, and secrets are never fields here. ExitCode is nil when the action did not run.
type Auditor ¶
type Auditor interface {
Record(AuditRecord) error
}
Auditor appends one record. A nil auditor skips the log. Record must be safe for concurrent use.
type Category ¶
type Category string
Category is the action class from the spec's table, e.g. "read", "sensitive-read", "low-write", "write", "install", "service", "delete", "permission", "network", "critical", "unknown", "local-read", "local".
type Decision ¶
type Decision struct {
Grade
Mode Mode
Outcome Outcome
By Decider
Similar bool // the confirmation may offer "allow similar this session" (never for High/Critical/Unknown)
Diff bool // a write: show the diff (new file: full text) before asking
Red bool // RiskCritical: red warning in the dialog / timeline
}
Decision is a grade plus what the mode says to do with it.
type DiffLines ¶
DiffLines counts added and removed lines in a unified diff. The diff text itself is not stored.
type Engine ¶
type Engine interface {
Classify(a Action, scope Scope) Grade
Decide(mode Mode, grade Grade, reviewerConfigured bool) Decision
}
Engine grades an action and applies the session's permission mode. SSHYard is the judge: the agent's reason never changes the result.
type Exec ¶
type Exec interface {
Run(ctx context.Context, cmd, dir string, stdout, stderr io.Writer) (exit int, err error)
}
Exec is the seam to the remote exec channel manager from ① (feat/metrics). Run executes cmd with `sh -c` in its own process group on a fresh exec channel of the host's pooled *ssh.Client (never a second connection, no agent forwarding, no injected env, never the user's visible shell). When ctx is done it stops the command: SSH signal, then `kill -TERM -<pgid>`, then -KILL after 5 s. Not implemented in A1 or A2.
type Gate ¶
type Gate interface {
Authorize(ctx context.Context, a Action, diff string) (Verdict, error)
// Done records the result of an action that ran (audit: exit code,
// duration, output bytes).
Done(a Action, v Verdict, exit int, durMS int64, outBytes int64)
}
Gate grades, decides, asks the reviewer and the user as needed, records "allow similar" grants for its session, and writes the audit record. One Gate per AI pane session.
type GateConfig ¶
type GateConfig struct {
Engine Engine
Mode func() Mode
Scope Scope
Prompter Prompter
Reviewer Reviewer
Auditor Auditor
SessionID string
PaneID string
Agent string
Host string
HostMeta string
Output func() string
Task func() string
Earlier func() []string
Now func() time.Time
PromptTimeout time.Duration
ReviewTimeout time.Duration
}
GateConfig builds one gate for one AI pane session. A nil Engine uses NewEngine. A nil Mode reports ModeAsk. A nil Reviewer means review mode runs ReadOnly and Low actions and asks the user for the rest. A nil Auditor skips the log. PromptTimeout and ReviewTimeout of 0 use the defaults (5 minutes and 10 seconds). Output, when set, supplies the recent untrusted terminal text the reviewer may see (the gate keeps the last 20 lines). Task, when set, supplies what the user asked for in the current turn, and Earlier the user's previous messages, oldest first (the gate keeps the last maxReviewEarlier).
type Grade ¶
type Grade struct {
Category Category
Risk Risk
Prefix string // command prefix or directory that "allow similar this session" matches on
Why string // short machine reason, e.g. "rm in pipeline", for the timeline and audit
}
Grade is the result of classifying an action.
type Mode ¶
type Mode string
Mode is a permission mode. The zero value means "not set at this level".
type Prompt ¶
type Prompt struct {
Action Action
Decision Decision
Diff string // unified diff or the new file's text; empty for non-writes
ReviewNote string // the review model's reason, if it was consulted
}
Prompt is what the confirmation dialog shows.
type ReviewInput ¶
type ReviewInput struct {
// Task is what the user asked for in this turn, against which the
// reviewer judges whether the action belongs. Earlier holds the
// user's previous messages in the pane, oldest first, for the task
// a short "continue" or "fix it" refers to.
Task string
Earlier []string
Category Category
Risk Risk
Why string // the local rule that set the risk, e.g. "unlisted command: atop"
Where Where
Dir string // actual working directory; empty means unknown
Command string
Path string
DiffSum string
HostMeta string
Reason string
Output string
}
ReviewInput is all the review model may see: no credentials, remote output only as bounded, marked untrusted data (last 20 lines).
type Reviewer ¶
type Reviewer interface {
Review(ctx context.Context, in ReviewInput) (allow bool, reason string, err error)
}
Reviewer is the optional review model. Any error, timeout (10 s) or unparsable reply must make the gate ask; it never auto-rejects.
type Risk ¶
type Risk int
Risk is an action's risk grade, ordered from least to most dangerous; RiskUnknown (cannot be graded) is treated at least like RiskHigh.
type Scope ¶
type Scope struct {
Home string // remote $HOME (absolute)
WritableRoots []string // default {Home, "/tmp"}; writes outside are at least RiskMedium
Sensitive []string // extra sensitive path globs (Host.AIPolicy), added to the built-in ones
Sandbox string // the external agent's empty local sandbox dir (Local actions)
}
Scope is what the grading needs to know about the session's host.