mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
A policy rule for a host name can narrow it to some of its requests: `api.github.com GET,HEAD /repos/` in a policy file, written by devvm network allow, deny and rm from --method and --path. Allows add up and a deny beats any allow, as for every rule, so narrowing a host that a rule allows whole, such as devvm's built-in GitHub, takes a deny: `devvm network deny api.github.com --method POST,PUT,PATCH,DELETE`, or `devvm network deny github.com --path '/*/*/git-receive-pack'`. An allow by method and path for a host already allowed whole warns that it narrows nothing and names the deny. The proxy decrypts such a host's HTTPS on :443 with the VM's CA, refuses its tunnels on other ports and without a CA, and judges every request on the connection, kept-alive HTTP/1.1 and HTTP/2 alike, every absolute-form one, and the shared Nix cache's own fetches. A connection's verdict and whether its requests are judged come from one read of the policy files. A blocked request gets 403 and a blocked event with its method and path; devvm network log shows it, and an allowed one's forward event names the rule that let it through. One matcher, internal/proxy/request.go, judges rules and secrets' bindings: methods from a closed list (RFC 9110's, PATCH, QUERY; never CONNECT); the methods a request names besides its own (every override-like header in any spelling, `_` for `-`, and the query's _method), each word judged, and while a rule narrows by method, a value that isn't exactly one method refused; path patterns with *, ** and a last / for everything below; and only a path in plain form. Allows and bindings match strictly, denies broadly: any case, every path that isn't plain, the prefix above a trailing /, and a last segment cut at its first dot (/admin.json, /admin.). A method devvm doesn't know isn't a rule, so a typo in a deny is a broken deny. Upgrades other than WebSocket and CONNECT inside a decrypted tunnel are refused for narrowed hosts. devvm secret set takes an optional --method (none for every method), and a secret's --path takes the same patterns, marked path_pattern in custom-secrets.json; a saved path with a * from before is refused rather than read as a wildcard. The bindings file stays version 1 while every binding reads alike to an older proxy, so devvm secret set and rm after an upgrade don't take a running older proxy's bindings away; a binding with methods or a pattern makes it version 2, which such a proxy refuses instead of putting a value in for every method, and writing one warns for each such VM. devvm network allow, deny and rm warn, naming the VM, when a rule by method and path changes while the VM's proxy runs from another devvm binary, or one devvm can't tell. A query with a ; or one Go can't read whole is refused while a rule narrows the host by method, and denies also match each segment with its trailing dots dropped. An allow that narrows nothing names the VMs, with -g by each VM's own allowlist, and says when it narrows only port 80's plain HTTP. - proxy: match, Methods, ParseMethods, PathOK, plainPath, matchPath, overrides, overrideLike, server.judgeRequest; parseRule/parseHostRule, CanonicalRule, NarrowRule, Narrowable, hostRules (rulesFor, verdict, byRequest, judge, unjudgeable), egress.checkHost, Allowlist.CoversWhole, trimDots; Binding.Methods, BindingListVersion 2 when needed (v1Binding); pathWithin and PathPrefixOK folded into match; the Nix cache judged - netpolicy: Rule(rule, deny, methods, path), NarrowedHost, sameRule, Proxy.Allowlist, Proxy.NarrowNotes, Proxy.OtherBinaries, BasePolicy, Proxy.SecretsWritten (after RefreshSecrets and devvm agent login --api-key's write); FormatEvent shows a blocked request's method and path and a forward's rule - secrets: Def/Secret/customJSON Methods, path_pattern, CheckMethods, CheckPath on proxy.PathOK - vm: RuleChange, PolicyChange(ctx, rules, RuleChange) - cli: --method and --path on network allow, deny and rm, --method on secret set, METHODS in devvm secret and "methods" in its --json - messages: bad_request_path (was bad_secret_path), bad_methods, rule_not_narrowable, rule_narrows, rule_narrows_nothing, rule_narrows_http_only, rule_narrows_unknown, proxy_other_binary, secrets_other_binary - tests: TestParseRuleNarrowed, TestMatchPath, TestDenyBypasses, TestAllowNarrowed, TestCoversWhole, TestForRequestMethods, TestInterceptRules and TestInterceptSecretMethods (HTTP/1.1 kept alive and HTTP/2), TestNarrowedNotDecrypted, TestNixCacheRulesByPath, FuzzDenyBypass (paths, methods, headers, _method), TestRule, TestNarrowedRules, TestOtherBinaries, TestRefreshSecretsOtherBinary, TestNarrowNotesUnreadable, TestDefine's path of /, TestReadBindings' versions, TestCustomsUnreadable's prefix path, network_narrow.txtar (narrows nothing), secret_custom.txtar's --method; on 0.1.0's frozen state: TestV010Bindings, TestV010ProxyConfig, TestV010Rules (0.1.0's TestParsePolicy and TestDecide, frozen), fixture_v010_network.txtar; e2e network: netRequestRules and the basic secret's --method GET,HEAD - docs: safety/network.md's Rules by method and path, the secrets' flags and an example, internals/network.md's Requests by method and path, the design note replacing the open-work entry, attack vectors, the commands page, internal/proxy/README.md, the CLI reference Co-Authored-By: Claude Opus 5.5 <[email protected]>
396 lines
12 KiB
Go
396 lines
12 KiB
Go
package cli
|
|
|
|
import (
|
|
"errors"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/spf13/pflag"
|
|
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/netpolicy"
|
|
"github.com/devvmhq/devvm/internal/secrets"
|
|
"github.com/devvmhq/devvm/internal/settings"
|
|
"github.com/devvmhq/devvm/internal/sshagent"
|
|
"github.com/devvmhq/devvm/internal/state"
|
|
"github.com/devvmhq/devvm/internal/upgrade"
|
|
"github.com/devvmhq/devvm/internal/vm"
|
|
)
|
|
|
|
// usageCode is the exit code of a usage error: a bad argument or flag, or
|
|
// an unknown command or word.
|
|
const usageCode = 2
|
|
|
|
// exclusiveKey is the annotation that lists a command's flags that can't
|
|
// be given together, as exclusive records them.
|
|
const exclusiveKey = "devvm-exclusive"
|
|
|
|
// usageError is an error in how devvm was run, found before the command
|
|
// does anything: Execute prints it, names the command's --help and exits
|
|
// with usageCode.
|
|
type usageError struct{ m msg.M }
|
|
|
|
func (e usageError) Error() string { return e.m.Error() }
|
|
func (e usageError) Unwrap() error { return e.m }
|
|
|
|
// usage makes err a usage error: a message as it is, anything else (the
|
|
// command-line parser's own) in usage_error.
|
|
func usage(err error) usageError {
|
|
if e, ok := errors.AsType[usageError](err); ok {
|
|
return e
|
|
}
|
|
m, ok := errors.AsType[msg.M](err)
|
|
if !ok {
|
|
m = msg.UsageError(err.Error()).Because(err)
|
|
}
|
|
return usageError{m}
|
|
}
|
|
|
|
// ranError is an error a command's RunE returned, once it ran, or the
|
|
// root's layout check (checkLayout): a failure, which showFailure prints,
|
|
// not a usage error.
|
|
type ranError struct{ err error }
|
|
|
|
func (e ranError) Error() string { return e.err.Error() }
|
|
func (e ranError) Unwrap() error { return e.err }
|
|
|
|
// checkCommands makes every command under root check its flags and
|
|
// arguments before anything else runs (root's PersistentPreRunE, any VM
|
|
// lookup), each error a usage error, and marks what RunE returns as a
|
|
// failure. The parser's flag errors become usage errors too (flagError).
|
|
func checkCommands(root *cobra.Command) {
|
|
root.SetFlagErrorFunc(func(c *cobra.Command, err error) error { return usage(flagError(c, err)) })
|
|
var walk func(c *cobra.Command)
|
|
walk = func(c *cobra.Command) {
|
|
checkCommand(c)
|
|
for _, sub := range c.Commands() {
|
|
walk(sub)
|
|
}
|
|
}
|
|
walk(root)
|
|
}
|
|
|
|
// checkCommand is what checkCommands does to each command: c checks its
|
|
// flags and arguments first, and RunE's errors are failures.
|
|
func checkCommand(c *cobra.Command) {
|
|
args := c.Args
|
|
c.Args = func(cmd *cobra.Command, a []string) error {
|
|
if err := noBlanks(cmd, a); err != nil {
|
|
return usage(err)
|
|
}
|
|
if err := checkFlags(cmd, a); err != nil {
|
|
return usage(err)
|
|
}
|
|
if args != nil {
|
|
if err := args(cmd, a); err != nil {
|
|
return usage(err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if run := c.RunE; run != nil {
|
|
c.RunE = func(cmd *cobra.Command, a []string) error {
|
|
if err := run(cmd, a); err != nil {
|
|
return ranError{err}
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// argsOf is the arguments in c's Use, without its flags: KEY_FILE,
|
|
// [all|none|LIST], RULE...; "" for none.
|
|
func argsOf(c *cobra.Command) string {
|
|
var out []string
|
|
depth, start := 0, -1
|
|
use := c.Use
|
|
if i := strings.IndexByte(use, ' '); i >= 0 {
|
|
use = use[i+1:]
|
|
} else {
|
|
use = ""
|
|
}
|
|
for i, r := range use + " " {
|
|
switch {
|
|
case r == '[':
|
|
if depth == 0 && start < 0 {
|
|
start = i
|
|
}
|
|
depth++
|
|
case r == ']':
|
|
depth--
|
|
case r == ' ' && depth == 0 && start >= 0:
|
|
if w := use[start:i]; !strings.HasPrefix(strings.TrimLeft(w, "["), "-") {
|
|
out = append(out, w)
|
|
}
|
|
start = -1
|
|
case r != ' ' && start < 0:
|
|
start = i
|
|
}
|
|
}
|
|
return strings.Join(out, " ")
|
|
}
|
|
|
|
// shownArgs is args as a message shows them: as typed, apart.
|
|
func shownArgs(args []string) string { return strings.Join(args, " ") }
|
|
|
|
// noArgs takes no arguments. A command with commands of its own says the
|
|
// word isn't one of them; devvm itself suggests the closest (checkWord).
|
|
func noArgs(cmd *cobra.Command, args []string) error {
|
|
if len(args) == 0 {
|
|
return nil
|
|
}
|
|
if !cmd.HasParent() {
|
|
return checkWord(cmd, args[0])
|
|
}
|
|
if cmd.HasAvailableSubCommands() {
|
|
var names []string
|
|
for _, c := range cmd.Commands() {
|
|
if c.IsAvailableCommand() {
|
|
names = append(names, c.Name())
|
|
}
|
|
}
|
|
return msg.NoSubcommand(cmd.CommandPath(), strings.Join(names, ", "), args[0])
|
|
}
|
|
return msg.ArgsNone(cmd.CommandPath(), shownArgs(args))
|
|
}
|
|
|
|
// argsN takes from least to most arguments (most < 0: any number), each
|
|
// one of the command's ValidArgs when it has them.
|
|
func argsN(least, most int) cobra.PositionalArgs {
|
|
return func(cmd *cobra.Command, args []string) error {
|
|
switch {
|
|
case len(args) < least:
|
|
return msg.ArgMissing(argsOf(cmd), cmd.CommandPath())
|
|
case most == 0:
|
|
return noArgs(cmd, args)
|
|
case most > 0 && len(args) > most:
|
|
return msg.ArgsTooMany(argsOf(cmd), cmd.CommandPath(), shownArgs(args))
|
|
}
|
|
if len(cmd.ValidArgs) == 0 {
|
|
return nil
|
|
}
|
|
for _, a := range args {
|
|
if !slices.Contains(cmd.ValidArgs, a) {
|
|
return msg.ArgNotChoice(strings.Join(cmd.ValidArgs, ", "), cmd.CommandPath(), a)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// exactArgs takes n arguments; maxArgs at most n; minArgs at least n.
|
|
func exactArgs(n int) cobra.PositionalArgs { return argsN(n, n) }
|
|
func maxArgs(n int) cobra.PositionalArgs { return argsN(0, n) }
|
|
func minArgs(n int) cobra.PositionalArgs { return argsN(n, -1) }
|
|
|
|
// exclusive marks cmd's flags names as not given together: Cobra's own
|
|
// mark, for completion, and exclusiveKey, which checkFlags checks before
|
|
// anything runs.
|
|
func exclusive(cmd *cobra.Command, names ...string) {
|
|
cmd.MarkFlagsMutuallyExclusive(names...)
|
|
if cmd.Annotations == nil {
|
|
cmd.Annotations = map[string]string{}
|
|
}
|
|
groups := cmd.Annotations[exclusiveKey]
|
|
if groups != "" {
|
|
groups += ";"
|
|
}
|
|
cmd.Annotations[exclusiveKey] = groups + strings.Join(names, " ")
|
|
}
|
|
|
|
// needs marks cmd's flag name as one that goes only with with: the flag
|
|
// it needs (--clone), or the word its first argument must be (on, for
|
|
// devvm clone on), which checkFlags checks before anything runs.
|
|
func needs(cmd *cobra.Command, name, with string) {
|
|
if cmd.Annotations == nil {
|
|
cmd.Annotations = map[string]string{}
|
|
}
|
|
cmd.Annotations[needsKey+name] = with
|
|
}
|
|
|
|
// needsKey starts the annotation of a flag that needs another (needs).
|
|
const needsKey = "devvm-needs-"
|
|
|
|
// checkNeeds refuses a flag given to cmd, with args, without the flag or
|
|
// the first argument it needs (needs).
|
|
func checkNeeds(cmd *cobra.Command, args []string) error {
|
|
f := cmd.Flags()
|
|
for key, with := range cmd.Annotations {
|
|
name, ok := strings.CutPrefix(key, needsKey)
|
|
if fl := f.Lookup(name); !ok || fl == nil || !fl.Changed {
|
|
continue
|
|
}
|
|
if flag, isFlag := strings.CutPrefix(with, "--"); isFlag {
|
|
if !f.Changed(flag) {
|
|
return msg.FlagNeedsFlag("--"+name, with)
|
|
}
|
|
} else if len(args) == 0 || args[0] != with {
|
|
return msg.FlagNeedsFlag("--"+name, cmd.CommandPath()+" "+with)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkFlags checks the flags given to cmd, with args: none of a group
|
|
// exclusive marked on it or a command above it together, none without
|
|
// the flag or argument it needs, and each value checkFlagValue knows.
|
|
func checkFlags(cmd *cobra.Command, args []string) error {
|
|
f := cmd.Flags()
|
|
if err := checkNeeds(cmd, args); err != nil {
|
|
return err
|
|
}
|
|
for c := cmd; c != nil; c = c.Parent() {
|
|
for group := range strings.SplitSeq(c.Annotations[exclusiveKey], ";") {
|
|
var set []string
|
|
for _, name := range strings.Fields(group) {
|
|
if fl := f.Lookup(name); fl != nil && fl.Changed {
|
|
set = append(set, "--"+name)
|
|
}
|
|
}
|
|
if len(set) > 1 {
|
|
return msg.FlagsExclusive(set[0], set[1])
|
|
}
|
|
}
|
|
}
|
|
var err error
|
|
f.Visit(func(fl *pflag.Flag) {
|
|
values := []string{fl.Value.String()}
|
|
if sv, ok := fl.Value.(pflag.SliceValue); ok {
|
|
values = sv.GetSlice() // a flag given many times, or with commas: each value
|
|
}
|
|
for _, v := range values {
|
|
if err == nil {
|
|
err = checkFlagValue(fl.Name, v)
|
|
}
|
|
}
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Cobra checks these only after the root's PersistentPreRunE: a group
|
|
// marked without exclusive, or a required flag, is refused first too,
|
|
// in usage_error.
|
|
if err := cmd.ValidateRequiredFlags(); err != nil {
|
|
return err
|
|
}
|
|
return cmd.ValidateFlagGroups()
|
|
}
|
|
|
|
// checkFlagValue checks the value of a flag, by its name, as each flag
|
|
// name has one meaning: what devvm would refuse later, refused first.
|
|
func checkFlagValue(name, value string) error {
|
|
var err error
|
|
switch name {
|
|
case "cpus":
|
|
_, err = settings.ParseCPUs("--cpus", value)
|
|
case "memory", "disk":
|
|
_, err = settings.ParseGiB("--"+name, value)
|
|
case "ports":
|
|
_, err = settings.ParsePorts(value)
|
|
case "network":
|
|
if _, _, ok := netpolicy.Choice(value); !ok {
|
|
err = msg.ArgNotChoice(strings.Join(netpolicy.Choices(), ", "), "--network", value)
|
|
}
|
|
case "lifetime":
|
|
if value != "" {
|
|
err = sshagent.CheckLifetime(value)
|
|
}
|
|
case "as":
|
|
err = vm.CheckLinkName(value)
|
|
case "older-than":
|
|
_, err = state.ParseDuration(value)
|
|
case "tools", "agents", "layers":
|
|
err = checkPartFlag("--"+name, value)
|
|
case "repos":
|
|
err = checkReposFlag(value)
|
|
case "to":
|
|
if !upgrade.Valid(strings.TrimPrefix(value, "v")) {
|
|
err = msg.UpgradeNotVersion(value)
|
|
}
|
|
case "host":
|
|
// One --host, or several joined with commas, as the flag takes them.
|
|
for h := range strings.SplitSeq(value, ",") {
|
|
if _, err = secrets.CheckHost(h); err != nil {
|
|
break
|
|
}
|
|
}
|
|
case "header":
|
|
_, err = secrets.CheckHeader(value)
|
|
case "env":
|
|
err = secrets.CheckEnv(value)
|
|
case "prefix":
|
|
err = secrets.CheckPrefix(value)
|
|
case "scheme":
|
|
if value != secrets.None {
|
|
err = secrets.CheckScheme(value)
|
|
}
|
|
case "path":
|
|
if value != secrets.None {
|
|
err = secrets.CheckPath(value)
|
|
}
|
|
case "method":
|
|
if value != secrets.None {
|
|
_, err = secrets.CheckMethods(value)
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
// checkReposFlag checks the value of --repos: all or none alone, or a
|
|
// comma-separated list of paths relative to the folder, each in it.
|
|
func checkReposFlag(value string) error {
|
|
if value == vm.ReposAll || value == vm.ReposNone {
|
|
return nil
|
|
}
|
|
for p := range strings.SplitSeq(value, ",") {
|
|
p = strings.TrimSpace(p)
|
|
if p == "" || p == vm.ReposAll || p == vm.ReposNone || !filepath.IsLocal(p) && p != "." {
|
|
return msg.ReposValue(value)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// flagError is the message for a flag the parser refused: unknown, without
|
|
// its value, or with one it can't take.
|
|
func flagError(c *cobra.Command, err error) error {
|
|
if e, ok := errors.AsType[*pflag.NotExistError](err); ok {
|
|
return msg.FlagUnknown(c.CommandPath(), flagName(e.GetSpecifiedName(), e.GetSpecifiedShortnames()))
|
|
}
|
|
if e, ok := errors.AsType[*pflag.ValueRequiredError](err); ok {
|
|
name := flagName(e.GetSpecifiedName(), e.GetSpecifiedShortnames())
|
|
return msg.FlagNeedsValue(name, name+" "+flagForm(e.GetFlag()))
|
|
}
|
|
if e, ok := errors.AsType[*pflag.InvalidValueError](err); ok {
|
|
if m, ok := errors.AsType[msg.M](e.Unwrap()); ok {
|
|
return m
|
|
}
|
|
name, value := "--"+e.GetFlag().Name, e.GetValue()
|
|
if e.GetFlag().Value.Type() == "bool" {
|
|
return msg.FlagBadSwitch(name, value)
|
|
}
|
|
return msg.FlagBadValue(name, flagForm(e.GetFlag()), value)
|
|
}
|
|
if e, ok := errors.AsType[*pflag.InvalidSyntaxError](err); ok {
|
|
return msg.FlagUnknown(c.CommandPath(), e.GetSpecifiedFlag())
|
|
}
|
|
return err
|
|
}
|
|
|
|
// flagName is a flag as it was given: --name, or -n within a group of
|
|
// shorthands.
|
|
func flagName(name, shorthands string) string {
|
|
if shorthands != "" {
|
|
return "-" + name
|
|
}
|
|
return "--" + name
|
|
}
|
|
|
|
// flagForm is what a flag's value is, as its help names it: N, GiB, AGE.
|
|
func flagForm(f *pflag.Flag) string {
|
|
name, _ := pflag.UnquoteUsage(f)
|
|
return name
|
|
}
|