policy

package
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: AGPL-3.0 Imports: 15 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 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, Unknown included, so nothing interrupts a pane the user set to stop asking. Critical and Unknown still set Red and neither offers "allow similar"; an Unknown that ran keeps its grade on the tool card and in the audit. High, including git exec-config, auto-runs.

Index

Constants

View Source
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
)
View Source
const ReviewInstructions = `` /* 2617-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 AuditNotice added in v1.1.1

func AuditNotice(err error) (code string, ok bool)

AuditNotice is the code the timeline shows for an audit failure: "audit-unavailable:<reason>" before a run, "audit-failed:<reason>" after one. ok is false when err holds no AuditError.

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

func ParseReview(raw string) (allow bool, reason string, ok bool)

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

func Rank(r Risk) int

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

func Redact(s string) string

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

func RedactLines(s string) string

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, and terminal_send and
	// terminal_key, which type into a terminal) or, for Local, the ACP
	// tool_call kind (read, edit, delete, move, search, execute, fetch, think,
	// other).
	Tool    string
	Command string // run_command / execute; the line or key typed
	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 Answer

type Answer int

Answer is the user's (or the system's) reply to a confirmation.

const (
	Reject Answer = iota // also the default focus
	AllowOnce
	AllowSimilar // this pane session only
	TimedOut     // 5 minutes without an answer: treated as Reject
	Cancelled    // Stop / session cancel
)

type AuditError added in v1.1.1

type AuditError struct {
	Ran bool
	Err error
}

AuditError is a failed audit write. Ran is false when the log was not usable before the action, which then did not run; true when the action already ran and only its record was lost: that is reported, and the action is never run again. Error and Reason carry no local file path.

func (*AuditError) Error added in v1.1.1

func (e *AuditError) Error() string

func (*AuditError) Reason added in v1.1.1

func (e *AuditError) Reason() string

Reason is the cause, such as "permission denied", without the path.

func (*AuditError) Unwrap added in v1.1.1

func (e *AuditError) Unwrap() error

type AuditPreparer

type AuditPreparer interface {
	Prepare(at time.Time) error
}

AuditPreparer is optional. The gate calls Prepare with the record's time before it runs an action, and refuses to run when the file that record goes to cannot be opened for writing.

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 Decider

type Decider string

Decider is who made the final call (audit field 裁决人).

const (
	ByRule     Decider = "rule"
	ByReviewer Decider = "reviewer"
	ByUser     Decider = "user"
	ByFull     Decider = "full" // 完全允许
)

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

type DiffLines struct {
	Added   int `json:"added"`
	Removed int `json:"removed"`
}

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.

func NewDeviceEngine added in v0.0.26

func NewDeviceEngine() Engine

NewDeviceEngine grades what an agent types into a network device's own command line, over Telnet or a serial port: Cisco, Huawei, H3C, Juniper and their like. Every other action is graded as NewEngine grades it. The device's prompt mode is not tracked: what the rules do not know is Unknown, which asks wherever High would.

func NewEngine

func NewEngine() Engine

NewEngine returns the built-in grader.

func NewRootEngine added in v1.5.0

func NewRootEngine(root func() bool) Engine

NewRootEngine grades what an agent types into an SSH host's terminal that su or sudo -i made root's, root saying so when it asks: each line as sudo would make it, never below Medium. Every other action, and every line while root reports false, is graded as NewEngine grades it.

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). A failed write is an *AuditError with Ran
	// set: the caller shows it and never runs the action again.
	Done(a Action, v Verdict, exit int, durMS int64, outBytes int64) error
}

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.

func NewGate

func NewGate(cfg GateConfig) Gate

NewGate returns the session gate described by cfg.

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".

const (
	ModeAsk    Mode = "ask"    // 询问 (default)
	ModeReview Mode = "review" // 自动审核
	ModeFull   Mode = "full"   // 完全允许 (needs explicit confirmation at every level)
)

func Resolve

func Resolve(global, host, pane Mode) Mode

Resolve picks the effective mode: pane (this session only) over host (Host.AIPolicy.Mode) over global (AIDefaultMode). Invalid or empty levels are skipped; with nothing valid the answer is ModeAsk.

func (Mode) Valid

func (m Mode) Valid() bool

Valid reports whether m is one of the three modes.

type Outcome

type Outcome string

Outcome is what happens next.

const (
	Allow  Outcome = "allow"  // run without asking
	Ask    Outcome = "ask"    // ask the user
	Review Outcome = "review" // ask the review model; anything but a clean "allow" becomes Ask
)

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 Prompter

type Prompter interface {
	Ask(ctx context.Context, p Prompt) Answer
}

Prompter asks the user. It must return when ctx is done (Cancelled).

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.

const (
	RiskReadOnly Risk = iota // 只读
	RiskLow                  // 低
	RiskMedium               // 中
	RiskHigh                 // 高
	RiskCritical             // 高(红色)
	RiskUnknown              // 无法判定
)

func (Risk) String

func (r Risk) String() string

String is the audit token for a risk.

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.

type Verdict

type Verdict struct {
	Decision
	Run          bool   // execute the action
	Answer       Answer // when a prompt was shown
	ReviewReason string
	Refusal      string // when !Run: the reason sent back to the agent as the tool result
}

Verdict is the gate's final answer for one action.

type Where

type Where string

Where an action runs.

const (
	Remote Where = "remote"
	Local  Where = "local" // an external agent's own tool on this machine
)

Jump to

Keyboard shortcuts

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