Documentation
¶
Overview ¶
Package grant is RemoHop's scoped, expiring access for AI agents (and for anybody else a host owner wants to give less than everything): a grant names what a credential may do on a host (which services, which file roots, which commands), until when, how many sessions at once, whether each action needs the owner's approval and whether terminal output is recorded.
The host daemon (internal/hostd) stores grants and enforces them; this package holds what both sides of that and the service packages share: parsing and checking the rules, the grant code a client redeems, the Guard a service asks before it acts for a granted session, and the asciicast recorder. It depends only on the leaf packages perm and peer, so service packages can import it without importing the host daemon.
Index ¶
- Constants
- Variables
- func Attach(c *peer.Conn, g Guard)
- func AttachFull(c *peer.Conn)
- func CheckCommand(cmd string, allow []string) error
- func CheckLinkTarget(link, target string) error
- func CheckProtected(p string, a Access) error
- func EncodeCode(tokenID string, secret []byte) string
- func OwnerOf(g Guard) string
- func ParseApprove(v string) (string, error)
- func ParseCode(code string) (tokenID string, secret []byte, err error)
- func Protect(dir string) (release func())
- func ProtectedDirs() []string
- func RealPath(p string) (string, error)
- func ServiceLabel(service string) string
- func ValidName(name string) error
- type Access
- type Cast
- type Dialect
- type Grant
- type Guard
- type Owned
- type Place
- type ProtectedError
- type Recorder
- type Refusal
- type RootChangedError
- type Rules
- func (r *Rules) AllowsFeature(f perm.Feature) bool
- func (r *Rules) AllowsService(service string) bool
- func (r *Rules) CheckPath(p string, a Access) error
- func (r *Rules) CheckWorkDir(dir string) error
- func (r *Rules) Denied() []string
- func (r *Rules) RootsContaining(dirs []string) []string
- func (r *Rules) Scope() *Scope
- func (r *Rules) Summary() []string
- type Scope
- type ShellMode
- type State
Constants ¶
const ( ApproveNone = "none" // nothing is asked ApproveFirst = "first" // the first command or file change of each session is asked ApproveEach = "each" // every command and every file change is asked )
Approval modes.
const DefaultMaxSessions = 2
DefaultMaxSessions is how many sessions a grant allows at once unless its owner says otherwise.
const Items = "shell, shell:run-only, shell:cmd=PROGRAM, files, files:read, files:read:PATH, files:write:PATH, " +
"screenshot, screen, desktop, input, clip, info, forward, vpn, serial, usb"
Items is the allow-list vocabulary, for help texts and errors.
const MaxCast = 64 << 20
MaxCast bounds one recording; past it the recording ends with a marker and the session goes on unrecorded.
Variables ¶
var ErrNoGrantState error = noGrantState{}
ErrNoGrantState is what the guard of a host session without grant state answers to everything.
var HostShell = func() (Dialect, string) { return DialectPOSIX, "" }
HostShell reports the dialect and path of the shell the host runs commands with. The shell service sets it; the default is POSIX.
Functions ¶
func Attach ¶
Attach makes g the guard of c. The host daemon calls it before the session serves its first stream.
func AttachFull ¶
AttachFull records that c stands on no grant: Of(c) is nil and services do not restrict it. The host daemon calls it, instead of Attach, before a session with full access serves its first stream.
func CheckCommand ¶
CheckCommand checks a command line against the allow-list, for the host's shell (HostShell). An empty list allows everything. An entry matches when the command's leading words are exactly the entry's words: "git" allows "git status" and "git log -1", "go test" allows "go test ./..." but not "go run". Commands that chain, redirect, substitute or expand anything are refused outright, because the leading words would no longer say what runs.
This limits which programs the host starts on the agent's behalf. It is a guard rail, not a sandbox: a permitted program that can itself run others (git aliases and hooks, make, find -exec, interpreters) carries that power along. Allow such programs deliberately.
func CheckLinkTarget ¶
CheckLinkTarget decides whether a symbolic link with target text target may be at host path link (made there, renamed there or linked there) under a grant: it may not lead into a protected directory or to a directory above one, whatever the grant's roots.
func CheckProtected ¶
CheckProtected refuses access a to host path p when it reaches into a protected directory (see Protect), or for a change, when it is a directory above one.
func EncodeCode ¶
EncodeCode formats a grant credential.
func OwnerOf ¶
OwnerOf is the owner of what a session under g starts (see Owned), or the grant's name when g does not say.
func ParseApprove ¶
ParseApprove validates an --approve value.
func Protect ¶
func Protect(dir string) (release func())
Protect adds dir to the directories no grant gives access to, and returns a function that removes it again. The host daemon protects its config directory for as long as it serves. Protecting the same directory more than once is counted.
func ProtectedDirs ¶
func ProtectedDirs() []string
ProtectedDirs returns the protected directories, each as given and, if different, with its links resolved.
func RealPath ¶
RealPath resolves the symbolic links in p as far as p exists, and appends the components that do not exist yet unchanged. A link whose target does not exist is resolved too: what matters is where an open or create through it would land. On Windows junctions (mount points) are resolved like links.
func ServiceLabel ¶
ServiceLabel names what a refused service stands for in the allow-list vocabulary, so a refusal tells the reader what to ask for.
Types ¶
type Cast ¶
type Cast struct {
// contains filtered or unexported fields
}
Cast writes an asciicast v2 recording (https://docs.asciinema.org/manual/asciicast/v2/): a header line, then one JSON array per event. Play it back with `asciinema play FILE`.
type Dialect ¶
type Dialect int
Dialect is the quoting dialect of the shell the host runs commands with.
const ( // DialectPOSIX: sh and its relatives (bash, dash, zsh, ksh, ...). DialectPOSIX Dialect = iota // DialectPowerShell: Windows PowerShell and PowerShell 7. DialectPowerShell // DialectCmd: cmd.exe, where only double quotes quote, and %, ^ and // ! expand or escape even inside them. DialectCmd // DialectUnknown: a shell whose rules the check does not know. DialectUnknown )
type Grant ¶
type Grant struct {
// Name identifies the grant in every command, refusal and audit
// entry. See ValidName.
Name string `json:"name"`
// TokenID is the credential the grant is redeemed with (an entry in
// the host's pairing-token store marked with this grant's name).
TokenID string `json:"token_id"`
// Allow is the allow list as given (`--allow`), e.g. "shell:run-only",
// "files:read:/home/me/project", "screenshot".
Allow []string `json:"allow"`
// Commands, when not empty, are the only commands that may be run:
// each entry is a program name, optionally followed by leading
// arguments ("git", "go test").
Commands []string `json:"commands,omitempty"`
// Approve is ApproveNone, ApproveFirst or ApproveEach.
Approve string `json:"approve,omitempty"`
// MaxSessions bounds concurrent sessions under the grant.
MaxSessions int `json:"max_sessions"`
// Record keeps an asciicast recording of every command's and
// terminal's output in the host's config directory.
Record bool `json:"record,omitempty"`
Created time.Time `json:"created"`
Expires time.Time `json:"expires"`
// Suspended grants (`remohop host panic`) refuse logins and streams until
// resumed.
Suspended bool `json:"suspended,omitempty"`
}
Grant is what a host owner issued, as stored on the host.
type Guard ¶
type Guard interface {
// Name is the grant's name.
Name() string
// Command is asked before a command is started: kind is "exec" or
// "spawn", tty whether it gets a terminal, env the extra environment
// the client asked for.
Command(ctx context.Context, kind, command string, tty bool, env []string) error
// WorkDir is asked before a command (kind "exec" or "spawn") starts
// in host directory dir, after Command allowed it: a grant with a
// command allow-list refuses directories its file roots let the
// session write (see Rules.CheckWorkDir).
WorkDir(ctx context.Context, kind, dir string) error
// Terminal is asked before an interactive terminal is attached.
Terminal(ctx context.Context, session string) error
// File is asked before a file operation on host path p. op names the
// operation for the audit log ("open", "remove", ...).
File(ctx context.Context, op string, a Access, p string) error
// FileScope is the grant's file scope: the pinned roots the file
// service does its I/O through once File has allowed an operation.
// It is the same Scope for as long as the grant's credential stays
// the same, so a service can tell a reissued grant apart.
FileScope() (*Scope, error)
// Log records an action that needs no permission of its own in the
// audit log (for example killing a background job).
Log(action string, kv ...string)
// Record returns a recorder for a terminal or command's output, or
// nil if the grant does not record.
Record(kind, title string, cols, rows int) Recorder
}
Guard is what a host service asks before it acts for a session that stands on a grant. The host daemon attaches one to every such session, and marks every session with full access as such (AttachFull); for those Of returns nil, and services then skip the checks entirely.
A host-side session with neither (one whose setup did not finish, or a service reached by some path that never set it up) does not get full access: Of returns a guard that refuses everything.
Every method that can refuse returns an error whose text is meant for the client: usually a *Refusal, or the owner's denial of an approval. Methods may block while the host's owner is asked to approve.
func Of ¶
Of returns the guard of c, or nil if the session is not under a grant. For the host side of a session that was given neither a guard nor AttachFull it returns a guard that refuses everything: missing grant state never means full access. The controlling side of a session (a client serving callbacks from its host) is not restricted.
type Owned ¶
type Owned interface {
// Owner names who owns the background jobs and terminals a session
// starts: the grant's name and the client's identity.
Owner() string
}
Owned is a Guard that tells apart the identities using its grant. A grant an authorizer gives (RemoHop Teams' team rules) can be used by many client keys at once; what one of them leaves running must not be the others'.
type Place ¶
type Place struct {
// Root is the pinned root the operation goes through, with Rel the
// path below it ("." for the root itself). Root is nil when the
// access is not confined (the grant allows it anywhere) or is only
// looking at an ancestor of a root; the operation then uses Path.
Root *os.Root
Rel string
// Path is the host path, with its symbolic links resolved as the
// operation would resolve them.
Path string
// RootPath is the root as configured ("" when Root is nil).
RootPath string
// contains filtered or unexported fields
}
Place is where a file operation acts under a scope.
type ProtectedError ¶
type ProtectedError struct {
Path, Dir string
// Above is set when the path is a directory above Dir (or a link
// leading to one) and the refused access would change it.
Above bool
}
ProtectedError refuses access to a protected directory.
func (*ProtectedError) Error ¶
func (e *ProtectedError) Error() string
type Recorder ¶
type Recorder interface {
Output(p []byte)
Input(p []byte)
Resize(cols, rows int)
Close(exit string)
}
Recorder receives a terminal stream as it happens. Implementations are safe for concurrent use and never block the stream for long; Close writes the end marker.
type Refusal ¶
type Refusal struct {
Grant string
What string // "files:write", "command \"rm -rf /\"", ...
Why string // optional detail
}
Refusal is an action a grant does not allow. Its text is meant for the agent (or person) that attempted it: what was refused, under which grant, and why, in the allow-list vocabulary.
type RootChangedError ¶
type RootChangedError struct{ Root string }
RootChangedError is the refusal for a root whose path no longer names the directory pinned when the grant was loaded.
func (*RootChangedError) Error ¶
func (e *RootChangedError) Error() string
type Rules ¶
type Rules struct {
Shell ShellMode
// Commands restricts which commands run (see CheckCommand); empty
// means any.
Commands []string
// ReadAll and WriteAll allow reading and changing files anywhere the
// host's user can.
ReadAll, WriteAll bool
// ReadRoots and WriteRoots are directories (absolute, cleaned) below
// which files may be read, or read and changed.
ReadRoots, WriteRoots []string
// Input allows keyboard and mouse control.
Input bool
// contains filtered or unexported fields
}
Rules is a parsed allow list: what a granted session may do. The zero value allows nothing.
func Parse ¶
Parse turns an allow list into Rules. Each item may itself be a comma-separated list. commands adds to the command allow-list (as shell:cmd= items do) and implies shell:run-only.
func (*Rules) AllowsFeature ¶
AllowsFeature reports whether the rules allow all of feature: used for abilities that services check on their own (perm.Input inside the desktop service).
func (*Rules) AllowsService ¶
AllowsService reports whether the rules let a session open service. Services in perm.Always are not this function's business: the host decides about those itself.
func (*Rules) CheckPath ¶
CheckPath decides whether the rules allow access to host path p (an absolute path, as the file service resolved it). Symbolic links (and junctions) are resolved first, both for the path itself and for its parent directory (an operation on a link acts on one or the other), and both results must lie under an allowed root, so a link cannot lead out of a root; a link whose target does not exist yet is resolved to where the target would be created. Paths with ".." components are refused when roots apply. A root whose path no longer names the directory pinned when the grant was loaded refuses everything below it (see Scope).
This is the policy check, made before the operation. The file service then does the operation through the root's pinned handle (see Scope.Resolve), so a link swapped in between cannot lead it out either.
func (*Rules) CheckWorkDir ¶
CheckWorkDir decides whether a command may run in host directory dir (absolute) under the rules. Without a command allow-list anything goes: such a grant runs whatever it likes anyway. With one, the directory may not be at or below a root the grant may write, nor contain one: the allowed programs read files there that decide what they run (git reads .git/config and its hooks, go test compiles every package below it, make reads its Makefile, npm its package.json), so a session that may write there could make an allowed command run a program of its own. A grant that may write anywhere (files) can therefore run its commands nowhere.
func (*Rules) Denied ¶
Denied lists the allow-list capabilities the rules do not grant, for the agent: what not to try.
func (*Rules) RootsContaining ¶
RootsContaining returns the file roots of r that contain one of dirs, so that whoever issues a grant can be told that the config directory in them stays out of reach. ReadAll and WriteAll are the caller's to check.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope is the file side of a grant as the host enforces it: the roots, each pinned to the directory it named when the grant was loaded.
Pinning means two things. The root is opened once, as an os.Root, and the file service does its I/O through that handle, so resolving a path below the root can never leave it, whatever symbolic links, junctions or renamed directories it meets on the way (os.Root refuses to follow a link out of the root, atomically, on every platform). And the root's identity (device and inode, or volume and file ID) is remembered: when the root's path later names a different directory, because the root was moved, removed or replaced by a link, every operation under it is refused rather than following the path to its new place. Reissuing the grant pins the directory that is there now.
A Scope is shared by every session on the same grant credential; it is safe for concurrent use.
func (*Scope) CheckLink ¶
CheckLink decides whether a symbolic link with target text target may be created at link (a Place resolved without following, under a root). It must lead to a place inside the same root: the file service would not follow it anywhere else, and other software on the host should not find links out of a root that a confined session planted.
Where a relative link leads depends on where the link is, and on the directories its ".." components climb out of, so a link that leads inside when it is made could lead out once it, or a directory above it, is renamed or replaced. A target with ".." is therefore refused, and so is an absolute one outside the root's path: what is left points at the link's own directory or below it (or at a fixed place in the root), wherever the link is moved to within the root.
Wherever the grant lets a session make links (also outside roots, when it may change files anywhere), the link may not lead into the host's config directory or to a directory above it (CheckLinkTarget).
func (*Scope) ID ¶
ID identifies the scope: the grant credential it was loaded for. A reissued grant has a different ID. The file service binds resumable uploads to it.
func (*Scope) IsRoot ¶
IsRoot reports whether fi (from Lstat) is one of the scope's pinned roots. The file service refuses to remove, rename or replace a root entry: a session confined to a root cannot swap it for something else.
func (*Scope) Resolve ¶
Resolve maps host path p (absolute, as the file service resolved it) to the place an operation with access a acts on, or refuses it. follow says whether the operation follows a symbolic link at p itself (open, stat) or acts on the link (lstat, remove, rename, creating a link).
The returned Rel has the links resolved as they are now; the operation must still go through Root, which keeps it inside the root if they change in between. The caller calls Release on the Place when done.