diff --git a/CHANGELOG.md b/CHANGELOG.md index cc8593e54..4bfef81be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ - Docs: use placeholder accounts in Gmail auto-reply, Drive audit, and live-testing examples. (#1332) — thanks @vyctorbrzezowski. +- Safety profiles: add `denied-values` to refuse specific values of string and list flags on named commands, and use it in `agent-safe` to refuse the `TRASH` and `SPAM` labels on Gmail modify commands and `--send-updates all|externalOnly` on calendar create, update and move, auto-declining `calendar focus-time` (pass `--auto-decline none`), and focus-time or out-of-office events written through `calendar create` and `calendar update`; a `"*"` entry refuses any value of a flag; `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#1263) — thanks @bautrey. + ## 0.48.0 - 2026-11-05 **Highlights:** New backups stay local until you configure a remote; existing configurations keep working. Store service-account keys in the keyring, search Gmail IDs efficiently, and use environment-backed watch tokens, with Calendar fixes and security dependency updates. diff --git a/cmd/bake-safety-profile/denied_values_test.go b/cmd/bake-safety-profile/denied_values_test.go new file mode 100644 index 000000000..e99ea1017 --- /dev/null +++ b/cmd/bake-safety-profile/denied_values_test.go @@ -0,0 +1,76 @@ +package main + +import ( + "bytes" + "fmt" + "go/parser" + "go/token" + "testing" + + "github.com/openclaw/gogcli/internal/safetyprofile" +) + +func TestGenerateDeniedValuesEmitsHashedLookup(t *testing.T) { + profile := &safetyprofile.Profile{ + Name: "test", + AllowRules: []string{"gmail.thread.modify"}, + DeniedValues: []safetyprofile.DeniedValue{ + {Path: "calendar.create", Flag: "send-updates", Values: []string{"all", "externalonly"}}, + {Path: "gmail.thread.modify", Flag: "add", Values: []string{"spam", "trash"}}, + {Path: "drive.upload", Flag: "name", Values: []string{"private,report.txt"}}, + {Path: "calendar.create", Flag: "focus-chat-status", Values: []string{"*"}}, + }, + } + + out := generate(profile) + + if _, err := parser.ParseFile(token.NewFileSet(), "gen.go", out, parser.AllErrors); err != nil { + t.Fatalf("generated code does not parse as Go:\n%s\n\nerror: %v", out, err) + } + + // Path and flag are hashed together like a command rule, and each refused value is + // hashed with them, so no part of a rule is a string an in-place edit could change. + for _, rule := range profile.DeniedValues { + anyValue := len(rule.Values) == 1 && rule.Values[0] == "*" + want := fmt.Sprintf("\tcase 0x%016x:\n\t\treturn true, %t\n", safetyprofile.HashRule(rule.Path+"."+rule.Flag), anyValue) + if !bytes.Contains(out, []byte(want)) { + t.Fatalf("generated output missing rule case for %s %s:\n%s\n\nfull output:\n%s", rule.Path, rule.Flag, want, out) + } + for _, verbatim := range append([]string{rule.Path, rule.Flag}, rule.Values...) { + if bytes.Contains(out, []byte(`"`+verbatim+`"`)) { + t.Fatalf("denied value rule component %q appears verbatim; it should only be hashed\n\nfull output:\n%s", verbatim, out) + } + } + if anyValue { + continue + } + for _, value := range rule.Values { + h := fmt.Sprintf("0x%016x", safetyprofile.HashRule(safetyprofile.DeniedValueKey(rule.Path, rule.Flag, value))) + if !bytes.Contains(out, []byte(h)) { + t.Fatalf("generated output missing value hash %s for %s %s %q:\n%s", h, rule.Path, rule.Flag, value, out) + } + } + } + if !bytes.Contains(out, []byte("func bakedSafetyDeniedValueRuleCount() int { return 4 }\n")) { + t.Fatalf("generated output missing the rule count:\n%s", out) + } +} + +// A profile without denied values still needs both functions, so safety_profile +// builds compile whether or not the profile uses the feature. +func TestGenerateWithoutDeniedValuesStillDefinesLookup(t *testing.T) { + out := generate(&safetyprofile.Profile{Name: "test", AllowRules: []string{"gmail.get"}}) + + if _, err := parser.ParseFile(token.NewFileSet(), "gen.go", out, parser.AllErrors); err != nil { + t.Fatalf("generated code does not parse as Go:\n%s\n\nerror: %v", out, err) + } + for _, want := range []string{ + "func bakedSafetyDeniedValueRule(path []string, flag string) (bool, bool) {\n\treturn false, false\n}\n", + "func bakedSafetyDeniedValueMatch(path []string, flag, value string) bool {\n\treturn false\n}\n", + "func bakedSafetyDeniedValueRuleCount() int { return 0 }\n", + } { + if !bytes.Contains(out, []byte(want)) { + t.Fatalf("generated output missing %q:\n%s", want, out) + } + } +} diff --git a/cmd/bake-safety-profile/main.go b/cmd/bake-safety-profile/main.go index 9c3b0a2f7..1e4f5e614 100644 --- a/cmd/bake-safety-profile/main.go +++ b/cmd/bake-safety-profile/main.go @@ -68,10 +68,68 @@ func generate(profile *safetyprofile.Profile) []byte { writeMatcher(&out, "bakedSafetyAllowExactMatch", profile.AllowRules, profile.AllowAll && len(profile.DenyRules) == 0, true) out.WriteString("\n") writeLockedFlags(&out, profile.LockedFlags) + out.WriteString("\n") + writeDeniedValues(&out, profile.DeniedValues) return out.Bytes() } +// writeDeniedValues emits the denied value lookups. The command path and flag name are +// hashed together like a command rule, and the rule case says whether it refuses any +// value. Each refused value is hashed with its path and flag (DeniedValueKey), and the +// runtime hashes the value it was given the same way, so no denied value is a string an +// in-place edit of the binary could change. The count travels alongside so the runtime +// can tell that every rule matched a real flag without the names being written down. +func writeDeniedValues(out *bytes.Buffer, rules []safetyprofile.DeniedValue) { + out.WriteString("func bakedSafetyDeniedValueRule(path []string, flag string) (bool, bool) {\n") + if len(rules) == 0 { + out.WriteString("\treturn false, false\n}\n") + out.WriteString("\nfunc bakedSafetyDeniedValueMatch(path []string, flag, value string) bool {\n\treturn false\n}\n") + out.WriteString("\nfunc bakedSafetyDeniedValueRuleCount() int { return 0 }\n") + return + } + out.WriteString("\tswitch bakedSafetyHashPath(append(append([]string(nil), path...), flag)) {\n") + seen := make(map[uint64]string, len(rules)) + var valueCases []string + for _, rule := range rules { + key := rule.Path + "." + rule.Flag + h := safetyprofile.HashRule(key) + if existing, dup := seen[h]; dup { + fmt.Fprintf(os.Stderr, "bake-safety-profile: hash collision between denied value rules %q and %q (FNV-64a=%#x)\n", existing, key, h) + os.Exit(1) + } + seen[h] = key + anyValue := len(rule.Values) == 1 && rule.Values[0] == "*" + fmt.Fprintf(out, "\tcase 0x%016x:\n\t\treturn true, %t\n", h, anyValue) + if anyValue { + continue + } + for _, value := range rule.Values { + valueKey := safetyprofile.DeniedValueKey(rule.Path, rule.Flag, value) + vh := safetyprofile.HashRule(valueKey) + if existing, dup := seen[vh]; dup { + fmt.Fprintf(os.Stderr, "bake-safety-profile: hash collision between denied value rules %q and %q (FNV-64a=%#x)\n", existing, valueKey, vh) + os.Exit(1) + } + seen[vh] = valueKey + valueCases = append(valueCases, fmt.Sprintf("0x%016x", vh)) + } + } + out.WriteString("\t}\n\treturn false, false\n}\n") + + out.WriteString("\nfunc bakedSafetyDeniedValueMatch(path []string, flag, value string) bool {\n") + if len(valueCases) == 0 { + out.WriteString("\treturn false\n}\n") + } else { + out.WriteString("\tswitch bakedSafetyDeniedValueHash(path, flag, value) {\n") + for _, c := range valueCases { + fmt.Fprintf(out, "\tcase %s:\n\t\treturn true\n", c) + } + out.WriteString("\t}\n\treturn false\n}\n") + } + fmt.Fprintf(out, "\nfunc bakedSafetyDeniedValueRuleCount() int { return %d }\n", len(rules)) +} + // writeLockedFlags emits the locked flag lookup. Names are hashed like the command // rules; the locked boolean values are literals because the flag parser consumes them. The // count travels alongside so the runtime can tell that every lock matched a real diff --git a/docs/safety-profiles.md b/docs/safety-profiles.md index 7ed36df93..0acc9371a 100644 --- a/docs/safety-profiles.md +++ b/docs/safety-profiles.md @@ -94,7 +94,10 @@ FNV-64a hash of each dotted command path, not as raw YAML. The compiled rule table never contains the rule strings themselves, so to re-enable a blocked command an attacker has to patch compiled machine code rather than flip ASCII bytes in a YAML blob; the cost goes from a one-line `sed` invocation to -disassembly-level work. +disassembly-level work. Denied values are compiled the same way: each refused +value is hashed together with its command path and flag, and the runtime hashes +the value it was given before comparing, so no denied value is stored as a +string either. Note that command names may still appear in the binary from unrelated metadata (API URLs, error message format strings, Kong help text). What this hardening @@ -108,8 +111,15 @@ error messages can reference it. Allows reading, searching, drafting, labeling, archiving, organizing files, and other low-risk recoverable actions. Blocks sends, deletes, sharing changes, admin -operations, and auth writes. Keeps `schema` available for command, exit-code, -and effective safety-policy discovery. +operations, and auth writes. Refuses the `TRASH` and `SPAM` labels on the Gmail +modify commands, `--send-updates all|externalOnly` on calendar create, update +and move, any `calendar focus-time` that auto-declines (it defaults to +`--auto-decline all`, so pass `--auto-decline none`), and focus-time or +out-of-office events written through `calendar create` and `calendar update` +(`--event-type`, the focus and out-of-office flags, and on update any use of +them), and blocks `calendar propose-time` and Drive and Docs comments, because +those notify other people. See [Denied Flag Values](#denied-flag-values). Keeps +`schema` available for command, exit-code, and effective safety-policy discovery. Good for: @@ -163,6 +173,7 @@ Rules: - command names are written as dot paths internally, such as `gmail.drafts.create`. - `aliases:` controls root shortcuts such as `send`, `ls`, `search`, and `upload`. - `locked-flags:` is not a command path; it locks flag values, see [Locked Flags](#locked-flags). +- `denied-values:` is not a command path; it refuses values of string flags on named commands, see [Denied Flag Values](#denied-flag-values). Parent rules are prefix matches. For example, `drive: true` allows every `drive` subcommand unless a child is explicitly blocked. For restrictive profiles, prefer @@ -248,6 +259,70 @@ To make an existing preset stricter without changing its behavior for everyone, copy it and add the locks you need. For example, an agent-oriented copy commonly locks `sanitize-content`, `wrap-untrusted`, and `no-input` to `true`. +## Denied Flag Values + +Command rules decide which commands may run, and locked flags fix boolean flags. +Neither stops an allowed command from being pointed at something destructive or +noisy. `gmail thread modify --add TRASH` moves mail to the trash through a +command the profile allows, and `calendar create ... --send-updates all` emails +every attendee. + +`denied-values` refuses specific values of string and list flags on specific +commands: + +```yaml +denied-values: + gmail.thread.modify: + add: [TRASH, SPAM] + add-label: [TRASH, SPAM] + calendar.create: + send-updates: [all, externalonly] +``` + +Each key is a canonical dotted command path, matched exactly, and maps flag names +to a non-empty list of values. A command reached through an alias, such as +`gmail thread edit`, resolves to its canonical path first and is covered. Paths +are not prefix matches and wildcards (`*`, `all`) are rejected, so a rule applies +only to the command it names. + +A denied value behaves as follows: + +- the check runs after parsing and before the command, so `--dry-run` is refused too. +- comparison is case-insensitive. Each flag value, and each element of a repeated + flag, is compared whole and then split on commas and trimmed, so `trash`, + ` Trash ` and `INBOX,TRASH` all match `TRASH`, and a denied value that itself + contains a comma still matches. Splitting more aggressively than a command does can only + deny more, never less. +- the refusal is a usage error (exit 2) that echoes the value as typed: + +```text +flag --add value "TRASH" is denied for "gmail thread modify" by baked safety profile "agent-safe" +``` + +- Gmail label IDs are case-sensitive, but a denied value matches any casing, so a + user label spelled `Trash` is refused as well. That fails closed. +- a list holding only `"*"` refuses every value of the flag, as typed with no comma + splitting. An empty value counts when it is typed on the command line, because a + command can treat a supplied but empty flag as supplied: `calendar update` infers + an event type from one, and an empty auto-decline then defaults to `all`. A flag + left off the command line is allowed only when its default is empty: with + `calendar.focus-time: {auto-decline: ["*"]}`, omitting `--auto-decline` still + yields the default `all` and is refused. `"*"` must be the only entry in its list. + +```yaml +denied-values: + calendar.update: + focus-chat-status: ["*"] +``` + +Rules the binary cannot enforce are refused when it starts. Every path and flag +must exist on that command itself, and the flag must hold a string or a list of +strings. A misspelled name would otherwise deny nothing while the profile claimed +otherwise. As with locked flags, the names are hashed in the binary, so the check +counts matches against the number of rules. + +Stock builds have no profile, so `denied-values` does nothing there. + ## Choosing A Profile Use `readonly` when the caller should never change Google or local `gog` state. diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 12fd3d170..2c0c455e7 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -155,7 +155,7 @@ func executeWithRuntime(args []string, runtime *app.Runtime) (err error) { if err != nil { return reportEarlyError(kctx, runtimeIO.Err, err) } - if err = verifyLockedFlagsExist(parser.Model.Node); err != nil { + if err = verifyBakedFlagPolicyExists(parser.Model.Node); err != nil { return reportEarlyError(kctx, runtimeIO.Err, err) } args = rewriteDocsCellUpdateContentArgs(parser.Model, args) @@ -210,7 +210,7 @@ func executeWithRuntime(args []string, runtime *app.Runtime) (err error) { if err = enforceBakedSafetyProfile(kctx); err != nil { return reportEarlyError(kctx, runtimeIO.Err, err) } - err = enforceLockedFlags(kctx) + err = enforceBakedFlagPolicy(kctx) jsonErrors = cli.JSON if err != nil { return reportEarlyError(kctx, runtimeIO.Err, err) diff --git a/internal/cmd/safety_profile.go b/internal/cmd/safety_profile.go index 6b62214a6..2ae7be916 100644 --- a/internal/cmd/safety_profile.go +++ b/internal/cmd/safety_profile.go @@ -27,6 +27,15 @@ func bakedSafetyHashPath(parts []string) uint64 { return h.Sum64() } +// bakedSafetyDeniedValueHash returns the hash the generated denied-value switch is keyed +// by, matching internal/safetyprofile.DeniedValueKey. TestSafetyProfileDeniedValueHashAgreement +// asserts the two agree. +func bakedSafetyDeniedValueHash(path []string, flag, value string) uint64 { + h := fnv.New64a() + _, _ = h.Write([]byte(strings.Join(path, ".") + "." + flag + "\x00" + value)) + return h.Sum64() +} + func enforceBakedSafetyProfile(kctx *kong.Context) error { profile, err := loadBakedSafetyProfile() if err != nil { @@ -204,6 +213,127 @@ func enforceLockedFlags(kctx *kong.Context) error { return nil } +// verifyBakedFlagPolicyExists checks, before parsing, that every flag rule in the +// profile names something the CLI has. +func verifyBakedFlagPolicyExists(root *kong.Node) error { + if err := verifyLockedFlagsExist(root); err != nil { + return err + } + return verifyDeniedValueRulesExist(root) +} + +// enforceBakedFlagPolicy applies the profile's flag rules to a parsed command line: +// locked flag values first, then denied values on what remains. +func enforceBakedFlagPolicy(kctx *kong.Context) error { + if err := enforceLockedFlags(kctx); err != nil { + return err + } + return enforceDeniedValues(kctx) +} + +// deniedValueFlagSupported reports whether a flag holds a string or a list of strings, +// the only shapes enforceDeniedValues knows how to read. +func deniedValueFlagSupported(flag *kong.Flag) bool { + if flag.IsBool() { + return false + } + target := flag.Target.Type() + return target.Kind() == reflect.String || (target.Kind() == reflect.Slice && target.Elem().Kind() == reflect.String) +} + +// verifyDeniedValueRulesExist refuses to run when a denied-values rule names a command +// or flag the CLI does not have. Enforcement only ever asks whether the selected +// command's flag has denied values, so a misspelled path or flag would deny nothing +// and the profile would claim a guarantee it does not have. As with locked flags the +// names are hashed in the binary, so matches are counted against the rule count. +func verifyDeniedValueRulesExist(root *kong.Node) error { + want := bakedSafetyDeniedValueRuleCount() + if want == 0 { + return nil + } + seen := 0 + var unsupported error + var walk func(node *kong.Node) + walk = func(node *kong.Node) { + if node == nil { + return + } + if node.Type == kong.CommandNode { + path := commandNodePath(node) + for _, flag := range node.Flags { + if exists, _ := bakedSafetyDeniedValueRule(path, flag.Name); !exists { + continue + } + seen++ + if !deniedValueFlagSupported(flag) && unsupported == nil { + unsupported = usagef("baked safety profile %q denies values of --%s on %q, but only string and list flags can have denied values", bakedSafetyProfileName(), flag.Name, strings.Join(path, " ")) + } + } + } + for _, child := range node.Children { + walk(child) + } + } + walk(root) + if seen < want { + return usagef("baked safety profile %q denies values for %d flag(s) but only %d exist; check the denied-values paths and flag names", bakedSafetyProfileName(), want, seen) + } + return unsupported +} + +// enforceDeniedValues refuses a command line that gives a flag one of the values the +// profile denies for the selected command. It runs after parsing and before the command, +// so --dry-run is refused too. Values are split on commas and compared case-insensitively, +// more aggressively than some commands split them, which can only over-deny. A denied +// value of "*" refuses any value typed on the command line, empty included, and any +// non-empty value from elsewhere. +func enforceDeniedValues(kctx *kong.Context) error { + if !bakedSafetyEnabled() || bakedSafetyDeniedValueRuleCount() == 0 { + return nil + } + path := commandPath(kctx.Command()) + if len(path) == 0 { + return nil + } + for _, flag := range kctx.Flags() { + exists, anyValue := bakedSafetyDeniedValueRule(path, flag.Name) + if !exists { + continue + } + for _, raw := range flagStringValues(flag.Target) { + // "*" refuses any value as typed, with no comma splitting. An empty value + // counts when typed: a command may treat a supplied but empty flag as + // supplied, as calendar update does when it infers an event type. + if trimmed := strings.TrimSpace(raw); anyValue && (trimmed != "" || flagOnCommandLine(kctx, flag.Name)) { + return usagef("flag --%s value %q is denied for %q by baked safety profile %q", flag.Name, trimmed, strings.Join(path, " "), bakedSafetyProfileName()) + } + // The whole value is checked as well as its comma-separated parts, so a + // denied value that itself contains a comma still matches. + for _, value := range append([]string{strings.TrimSpace(raw)}, splitCSV(raw)...) { + if bakedSafetyDeniedValueMatch(path, flag.Name, strings.ToLower(value)) { + return usagef("flag --%s value %q is denied for %q by baked safety profile %q", flag.Name, value, strings.Join(path, " "), bakedSafetyProfileName()) + } + } + } + } + return nil +} + +// flagStringValues returns the strings a string or []string flag target holds. +func flagStringValues(target reflect.Value) []string { + switch target.Kind() { + case reflect.String: + return []string{target.String()} + case reflect.Slice: + out := make([]string, 0, target.Len()) + for i := range target.Len() { + out = append(out, target.Index(i).String()) + } + return out + } + return nil +} + func bakedSafetyProfileError(path []string, profileName string, included bool) error { command := strings.Join(path, " ") if included { diff --git a/internal/cmd/safety_profile_default.go b/internal/cmd/safety_profile_default.go index ca16c0751..12f52b5c6 100644 --- a/internal/cmd/safety_profile_default.go +++ b/internal/cmd/safety_profile_default.go @@ -2,7 +2,10 @@ package cmd -import "strings" +import ( + "slices" + "strings" +) // bakedSafetyTestProfile is the test-only override that backs the // bakedSafety* package-level functions in non-safety builds. Production @@ -19,6 +22,8 @@ var bakedSafetyTestProfile struct { allow map[string]bool deny map[string]bool lockedFlags map[string]string + // deniedValues maps a dotted command path to a flag name to its refused values. + deniedValues map[string]map[string][]string } func bakedSafetyEnabled() bool { return bakedSafetyTestProfile.enabled } @@ -51,3 +56,24 @@ func bakedSafetyLockedFlag(name string) (string, bool) { func bakedSafetyLockedFlagCount() int { return len(bakedSafetyTestProfile.lockedFlags) } + +func bakedSafetyDeniedValueRule(path []string, flag string) (bool, bool) { + values, ok := bakedSafetyTestProfile.deniedValues[strings.Join(path, ".")][flag] + return ok, len(values) == 1 && values[0] == "*" +} + +func bakedSafetyDeniedValueMatch(path []string, flag, value string) bool { + exists, anyValue := bakedSafetyDeniedValueRule(path, flag) + if !exists || anyValue { + return false + } + return slices.Contains(bakedSafetyTestProfile.deniedValues[strings.Join(path, ".")][flag], value) +} + +func bakedSafetyDeniedValueRuleCount() int { + count := 0 + for _, flags := range bakedSafetyTestProfile.deniedValues { + count += len(flags) + } + return count +} diff --git a/internal/cmd/safety_profile_denied_values_test.go b/internal/cmd/safety_profile_denied_values_test.go new file mode 100644 index 000000000..9d55bd901 --- /dev/null +++ b/internal/cmd/safety_profile_denied_values_test.go @@ -0,0 +1,466 @@ +package cmd + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/openclaw/gogcli/internal/safetyprofile" +) + +const deniedValuesProfile = ` +name: denied +denied-values: + gmail.thread.modify: + add: [TRASH, SPAM] + add-label: [TRASH, SPAM] + gmail.messages.modify: + add: [TRASH] + calendar.create: + send-updates: [all, externalOnly] +gmail: + thread: + modify: true + messages: + modify: true + batch: + modify: true +calendar: + create: true +` + +func threadModify(extra ...string) []string { + return append([]string{"--json", "--account", "a@b.com", "gmail", "thread", "modify", "t1"}, extra...) +} + +func calendarCreate(extra ...string) []string { + return append([]string{ + "--json", "--account", "a@b.com", "calendar", "create", "primary", + "--summary", "x", "--from", "2026-11-01T10:00:00Z", "--to", "2026-11-01T11:00:00Z", + }, extra...) +} + +func requireDenied(t *testing.T, args []string, want string) { + t.Helper() + withBakedSafetyProfile(t, deniedValuesProfile) + result := executeWithTestRuntime(t, args, nil) + if result.err == nil { + t.Fatalf("%v must be refused, got stdout=%q", args, result.stdout) + } + if got := result.err.Error(); !strings.Contains(got, want) { + t.Fatalf("err = %q, want it to contain %q", got, want) + } + if code := ExitCode(result.err); code != 2 { + t.Fatalf("exit code = %d, want 2 (err=%v)", code, result.err) + } +} + +func requireNotDenied(t *testing.T, args []string) { + t.Helper() + withBakedSafetyProfile(t, deniedValuesProfile) + result := executeWithTestRuntime(t, args, nil) + if result.err != nil && strings.Contains(result.err.Error(), "is denied") { + t.Fatalf("%v must not be refused: %v", args, result.err) + } +} + +func TestDeniedValues_RefusesEverySpellingOfADeniedValue(t *testing.T) { + for name, extra := range map[string][]string{ + "upper": {"--add", "TRASH"}, + "lower": {"--add", "trash"}, + "padded": {"--add", " Trash "}, + "equals form": {"--add=trash"}, + "csv": {"--add", "TRASH,INBOX"}, + "csv later": {"--add", "INBOX, trash"}, + "repeated": {"--add", "INBOX", "--add", "SPAM"}, + "add-label": {"--add-label", "trash"}, + "dry-run": {"--dry-run", "--add", "TRASH"}, + } { + t.Run(name, func(t *testing.T) { + requireDenied(t, threadModify(extra...), `is denied for "gmail thread modify" by baked safety profile "denied"`) + }) + } +} + +func TestDeniedValues_MessageEchoesTheValueAsTyped(t *testing.T) { + requireDenied(t, threadModify("--add", " Trash "), `flag --add value "Trash" is denied for "gmail thread modify" by baked safety profile "denied"`) + requireDenied(t, threadModify("--add-label", "SPAM"), `flag --add-label value "SPAM" is denied for "gmail thread modify" by baked safety profile "denied"`) +} + +// Aliases resolve to the canonical command path before the rule is looked up. +func TestDeniedValues_RefusesThroughCommandAliases(t *testing.T) { + requireDenied(t, []string{"--json", "--account", "a@b.com", "gmail", "thread", "edit", "t1", "--add", "TRASH"}, `for "gmail thread modify"`) + requireDenied(t, []string{"--json", "--account", "a@b.com", "gmail", "messages", "set", "m1", "--add", "TRASH"}, `for "gmail messages modify"`) +} + +func TestDeniedValues_RefusesCalendarSendUpdates(t *testing.T) { + for _, value := range []string{"all", "ALL", "externalOnly", "externalonly"} { + t.Run(value, func(t *testing.T) { + requireDenied(t, calendarCreate("--send-updates", value), `flag --send-updates value "`+value+`" is denied for "calendar create"`) + }) + } + requireDenied(t, calendarCreate("--dry-run", "--send-updates", "all"), `is denied for "calendar create"`) +} + +func TestDeniedValues_AllowsOtherValues(t *testing.T) { + requireNotDenied(t, threadModify("--add", "INBOX")) + requireNotDenied(t, threadModify("--add", "INBOX", "--remove", "TRASH")) + requireNotDenied(t, threadModify("--remove", "TRASH")) + requireNotDenied(t, threadModify("--add-label", "Label_1")) + requireNotDenied(t, calendarCreate("--send-updates", "none")) + requireNotDenied(t, calendarCreate()) + requireNotDenied(t, calendarCreate("--dry-run")) +} + +// A denied value is not a denied substring: a label whose name merely contains it is fine. +func TestDeniedValues_MatchesWholeValuesOnly(t *testing.T) { + requireNotDenied(t, threadModify("--add", "TRASHCAN")) + requireNotDenied(t, threadModify("--add", "NOT-SPAM")) +} + +// --add-label takes a label name literally, commas included, so a denied value +// containing a comma must match the whole value and not only its parts. +func TestDeniedValues_MatchesADeniedValueContainingAComma(t *testing.T) { + withBakedSafetyProfile(t, ` +name: denied +denied-values: + gmail.thread.modify: + add-label: ["Archive, Old"] +gmail: + thread: + modify: true +`) + result := executeWithTestRuntime(t, threadModify("--add-label", "archive, old"), nil) + if result.err == nil || !strings.Contains(result.err.Error(), `flag --add-label value "archive, old" is denied`) { + t.Fatalf("a denied value containing a comma must be refused, got err=%v stdout=%q", result.err, result.stdout) + } +} + +// The rule is keyed to a command path, so another command with a flag of the same +// name is untouched. +func TestDeniedValues_InertOnOtherCommands(t *testing.T) { + requireNotDenied(t, []string{ + "--json", "--account", "a@b.com", "gmail", "batch", "modify", "m1", "--add", "TRASH", + }) +} + +// Stock builds compile the no-profile stub, so nothing is denied at all. +func TestDeniedValues_IgnoredWithoutBakedProfile(t *testing.T) { + result := executeWithTestRuntime(t, threadModify("--add", "TRASH"), nil) + if result.err != nil && strings.Contains(result.err.Error(), "is denied") { + t.Fatalf("denied value applied without a baked profile: %v", result.err) + } +} + +func TestDeniedValues_NonexistentPathRefusesToRun(t *testing.T) { + withBakedSafetyProfile(t, ` +name: denied +denied-values: + gmail.thread.mdoify: + add: [TRASH] +gmail: + thread: + modify: true +`) + result := executeWithTestRuntime(t, threadModify("--add", "INBOX"), nil) + if result.err == nil { + t.Fatalf("a misspelled command path must fail, got stdout=%q", result.stdout) + } + if !strings.Contains(result.err.Error(), "denies values for 1 flag(s) but only 0 exist") { + t.Fatalf("err = %v", result.err) + } + if code := ExitCode(result.err); code != 2 { + t.Fatalf("exit code = %d, want 2", code) + } +} + +func TestDeniedValues_NonexistentFlagRefusesToRun(t *testing.T) { + withBakedSafetyProfile(t, ` +name: denied +denied-values: + gmail.thread.modify: + ad: [TRASH] +gmail: + thread: + modify: true +`) + result := executeWithTestRuntime(t, threadModify("--add", "INBOX"), nil) + if result.err == nil { + t.Fatalf("a misspelled flag must fail, got stdout=%q", result.stdout) + } + if !strings.Contains(result.err.Error(), "denies values for 1 flag(s) but only 0 exist") { + t.Fatalf("err = %v", result.err) + } +} + +// A rule on a flag the command does not declare itself (a root flag) locks nothing. +func TestDeniedValues_RootFlagRefusesToRun(t *testing.T) { + withBakedSafetyProfile(t, ` +name: denied +denied-values: + gmail.thread.modify: + account: [a@b.com] +gmail: + thread: + modify: true +`) + result := executeWithTestRuntime(t, threadModify("--add", "INBOX"), nil) + if result.err == nil { + t.Fatalf("a rule on a flag the command does not declare must fail, got stdout=%q", result.stdout) + } + if !strings.Contains(result.err.Error(), "denies values for 1 flag(s) but only 0 exist") { + t.Fatalf("err = %v", result.err) + } +} + +func TestDeniedValues_BooleanFlagRefusesToRun(t *testing.T) { + // Quoted: an unquoted YAML boolean is rejected at parse time, and the failure + // under test is the flag type rather than the value type. + withBakedSafetyProfile(t, ` +name: denied +denied-values: + calendar.create: + all-day: ["true"] +calendar: + create: true +`) + result := executeWithTestRuntime(t, calendarCreate(), nil) + if result.err == nil { + t.Fatalf("a boolean flag cannot be denied by value, got stdout=%q", result.stdout) + } + if !strings.Contains(result.err.Error(), "only string and list flags can have denied values") { + t.Fatalf("err = %v", result.err) + } +} + +// The count and type checks must not fire for a profile that uses none of this. +func TestDeniedValues_ProfileWithoutRulesIsUnaffected(t *testing.T) { + withBakedSafetyProfile(t, "name: plain\ngmail:\n thread:\n modify: true\n") + result := executeWithTestRuntime(t, threadModify("--add", "TRASH"), nil) + if result.err != nil && strings.Contains(result.err.Error(), "denied") { + t.Fatalf("profile without denied-values refused a value: %v", result.err) + } +} + +func TestAgentSafeProfileDeniesDestructiveAndNotifyingValues(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "safety-profiles", "agent-safe.yaml")) + if err != nil { + t.Fatalf("read agent-safe profile: %v", err) + } + profile, err := safetyprofile.Parse(string(raw)) + if err != nil { + t.Fatalf("Parse: %v", err) + } + got := map[string][]string{} + for _, rule := range profile.DeniedValues { + got[rule.Path+" --"+rule.Flag] = rule.Values + } + trashSpam := []string{"spam", "trash"} + notify := []string{"all", "externalonly"} + want := map[string][]string{ + "gmail.messages.modify --add": trashSpam, + "gmail.thread.modify --add": trashSpam, + "gmail.thread.modify --add-label": trashSpam, + "gmail.labels.modify --add": trashSpam, + "gmail.batch.modify --add": trashSpam, + "gmail.batch.modify --add-label": trashSpam, + "calendar.create --send-updates": notify, + "calendar.update --send-updates": notify, + "calendar.move --send-updates": notify, + // --auto-decline defaults to all, and declining a conflicting invitation + // notifies its organizer, so only an explicit --auto-decline none passes. + "calendar.focus-time --auto-decline": {"all", "new"}, + } + // create and update can also write focus-time and out-of-office events, whose + // auto-decline defaults to all, either by --event-type or by type inference from + // any focus or out-of-office flag. + anyValue := []string{"*"} + for _, command := range []string{"calendar.create", "calendar.update"} { + want[command+" --event-type"] = []string{"focus", "focus-time", "focus_time", "focustime", "ooo", "out-of-office", "out_of_office", "outofoffice"} + // create ignores an empty auto-decline, so it can pass none. update infers the + // type from a supplied flag and defaults an empty value to all, so any use is refused. + autoDecline := []string{"all", "new"} + if command == "calendar.update" { + autoDecline = anyValue + } + want[command+" --focus-auto-decline"] = autoDecline + want[command+" --ooo-auto-decline"] = autoDecline + want[command+" --focus-decline-message"] = anyValue + want[command+" --focus-chat-status"] = anyValue + want[command+" --ooo-decline-message"] = anyValue + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("agent-safe denied-values = %#v, want %#v", got, want) + } +} + +// Every rule in the shipped preset must name a real flag, or the binary refuses to +// run. Executing any command proves the pre-parse validation accepts the profile. +func TestAgentSafeProfileDeniedValueRulesAllExist(t *testing.T) { + setTestConfigHome(t) + raw, err := os.ReadFile(filepath.Join("..", "..", "safety-profiles", "agent-safe.yaml")) + if err != nil { + t.Fatalf("read agent-safe profile: %v", err) + } + withBakedSafetyProfile(t, string(raw)) + result := executeWithTestRuntime(t, []string{"version"}, nil) + if result.err != nil { + t.Fatalf("agent-safe must start: %v (stderr=%q)", result.err, result.stderr) + } +} + +// "*" refuses any non-empty value; an omitted or empty flag is not a value. +func TestDeniedValues_AnyValueRefusesNonEmptyValues(t *testing.T) { + const profile = ` +name: denied +denied-values: + gmail.thread.modify: + add: ["*"] +gmail: + thread: + modify: true +` + for _, extra := range [][]string{{"--add", "x"}, {"--add", " x "}, {"--add", ","}, {"--add", "INBOX", "--add", "x"}} { + withBakedSafetyProfile(t, profile) + result := executeWithTestRuntime(t, threadModify(extra...), nil) + if result.err == nil || !strings.Contains(result.err.Error(), "is denied for \"gmail thread modify\"") { + t.Fatalf("%v must be refused, got err=%v", extra, result.err) + } + if code := ExitCode(result.err); code != 2 { + t.Fatalf("%v exit code = %d, want 2", extra, code) + } + } + // An empty value typed on the command line is refused too: update treats a + // supplied but empty flag as supplied. + for _, extra := range [][]string{{"--add", ""}, {"--add", " "}, {"--add="}} { + withBakedSafetyProfile(t, profile) + result := executeWithTestRuntime(t, threadModify(extra...), nil) + if result.err == nil || !strings.Contains(result.err.Error(), "is denied for \"gmail thread modify\"") { + t.Fatalf("%v must be refused, got err=%v", extra, result.err) + } + } + for _, extra := range [][]string{{"--remove", "x"}, nil} { + withBakedSafetyProfile(t, profile) + result := executeWithTestRuntime(t, threadModify(extra...), nil) + if result.err != nil && strings.Contains(result.err.Error(), "is denied") { + t.Fatalf("%v must not be refused: %v", extra, result.err) + } + } +} + +// Leaving a flag off allows it under "*" only when its default is empty. +func TestDeniedValues_AnyValueRefusesANonEmptyDefault(t *testing.T) { + withBakedSafetyProfile(t, ` +name: denied +denied-values: + calendar.focus-time: + auto-decline: ["*"] +calendar: + focus-time: true +`) + args := []string{"--json", "--account", "a@b.com", "--dry-run", "calendar", "focus-time", "--from", "2026-11-01T10:00:00Z", "--to", "2026-11-01T11:00:00Z"} + result := executeWithTestRuntime(t, args, nil) + if result.err == nil || !strings.Contains(result.err.Error(), `flag --auto-decline value "all" is denied for "calendar focus-time"`) { + t.Fatalf("omitted --auto-decline defaults to all and must be refused, got err=%v stdout=%q", result.err, result.stdout) + } +} + +func agentSafeProfile(t *testing.T) { + t.Helper() + setTestConfigHome(t) + raw, err := os.ReadFile(filepath.Join("..", "..", "safety-profiles", "agent-safe.yaml")) + if err != nil { + t.Fatalf("read agent-safe profile: %v", err) + } + withBakedSafetyProfile(t, string(raw)) +} + +func calendarUpdate(extra ...string) []string { + return append([]string{"--json", "--account", "a@b.com", "calendar", "update", "primary", "evt1"}, extra...) +} + +// Focus-time and out-of-office events auto-decline conflicting invitations by default, +// which notifies the organizers, and create/update reach them by --event-type or by +// inference from any focus or out-of-office flag. +func TestAgentSafeProfileRefusesFocusAndOutOfOfficeRoutes(t *testing.T) { + for name, args := range map[string][]string{ + "create focus-time": calendarCreate("--event-type", "focus-time"), + "create focus alias": calendarCreate("--event-type", " Focus "), + "create focus_time": calendarCreate("--event-type", "focus_time"), + "create ooo": calendarCreate("--event-type", "OOO"), + "create out-of-office": calendarCreate("--event-type", "out-of-office"), + "create outofoffice": calendarCreate("--event-type", "outofoffice"), + "create focus chat": calendarCreate("--focus-chat-status", "doNotDisturb"), + "create focus message": calendarCreate("--focus-decline-message", "hi"), + "create ooo message": calendarCreate("--ooo-decline-message", "hi"), + "create focus all": calendarCreate("--focus-auto-decline", "all"), + "create focus new": calendarCreate("--focus-auto-decline", "NEW"), + "create ooo all": calendarCreate("--ooo-auto-decline", "all"), + "create focus dry-run": calendarCreate("--dry-run", "--event-type", "focus"), + "update focus-time": calendarUpdate("--event-type", "focus"), + "update ooo": calendarUpdate("--event-type", "ooo"), + "update focus chat": calendarUpdate("--focus-chat-status", "doNotDisturb"), + "update ooo message": calendarUpdate("--ooo-decline-message", "hi"), + "update ooo all": calendarUpdate("--ooo-auto-decline", "all"), + "update focus all dryrun": calendarUpdate("--dry-run", "--focus-auto-decline", "all"), + // update infers the type from a flag that was supplied even when its value is + // empty, and an empty auto-decline then defaults to all. + "update focus none": calendarUpdate("--focus-auto-decline", "none"), + "update ooo none": calendarUpdate("--ooo-auto-decline", "none"), + "update empty focus auto": calendarUpdate("--focus-auto-decline", ""), + "update empty ooo auto": calendarUpdate("--ooo-auto-decline", ""), + "update empty focus msg": calendarUpdate("--focus-decline-message", ""), + "update empty focus chat": calendarUpdate("--focus-chat-status", ""), + "update empty ooo message": calendarUpdate("--ooo-decline-message", ""), + } { + t.Run(name, func(t *testing.T) { + agentSafeProfile(t) + result := executeWithTestRuntime(t, args, nil) + if result.err == nil || !strings.Contains(result.err.Error(), "is denied for") { + t.Fatalf("agent-safe must refuse %v, got err=%v stdout=%q", args, result.err, result.stdout) + } + if code := ExitCode(result.err); code != 2 { + t.Fatalf("exit code = %d, want 2", code) + } + }) + } +} + +// An explicit none sends no declines, so it must keep working, as must ordinary events. +func TestAgentSafeProfileAllowsFocusWithoutAutoDecline(t *testing.T) { + for name, args := range map[string][]string{ + "create focus none": calendarCreate("--dry-run", "--focus-auto-decline", "none"), + "create ooo none": calendarCreate("--dry-run", "--ooo-auto-decline", "none"), + "create default type": calendarCreate("--dry-run", "--event-type", "default"), + "create plain": calendarCreate("--dry-run"), + "update summary": calendarUpdate("--dry-run", "--summary", "y"), + } { + t.Run(name, func(t *testing.T) { + agentSafeProfile(t) + result := executeWithTestRuntime(t, args, nil) + if result.err != nil && strings.Contains(result.err.Error(), "is denied") { + t.Fatalf("agent-safe must allow %v: %v", args, result.err) + } + }) + } +} + +func TestAgentSafeProfileRefusesTrashAndNotifyingSends(t *testing.T) { + setTestConfigHome(t) + raw, err := os.ReadFile(filepath.Join("..", "..", "safety-profiles", "agent-safe.yaml")) + if err != nil { + t.Fatalf("read agent-safe profile: %v", err) + } + withBakedSafetyProfile(t, string(raw)) + for _, args := range [][]string{ + threadModify("--add", "TRASH"), + calendarCreate("--send-updates", "all"), + } { + result := executeWithTestRuntime(t, args, nil) + if result.err == nil || !strings.Contains(result.err.Error(), "is denied") { + t.Fatalf("agent-safe must refuse %v, got err=%v", args, result.err) + } + } +} diff --git a/internal/cmd/safety_profile_test.go b/internal/cmd/safety_profile_test.go index 122263b2b..d983fed15 100644 --- a/internal/cmd/safety_profile_test.go +++ b/internal/cmd/safety_profile_test.go @@ -38,6 +38,14 @@ func withBakedSafetyProfile(t *testing.T, raw string) { locked[f.Name] = f.Value } bakedSafetyTestProfile.lockedFlags = locked + denied := make(map[string]map[string][]string, len(profile.DeniedValues)) + for _, rule := range profile.DeniedValues { + if denied[rule.Path] == nil { + denied[rule.Path] = map[string][]string{} + } + denied[rule.Path][rule.Flag] = rule.Values + } + bakedSafetyTestProfile.deniedValues = denied t.Cleanup(func() { bakedSafetyTestProfile = prev }) } @@ -62,6 +70,32 @@ func TestSafetyProfileHashAgreement(t *testing.T) { } } +// The generated denied-value switch is keyed by DeniedValueKey hashes, and the runtime +// looks values up with bakedSafetyDeniedValueHash, so the two must agree exactly. +func TestSafetyProfileDeniedValueHashAgreement(t *testing.T) { + cases := []struct { + path []string + flag, value string + }{ + {[]string{"gmail", "thread", "modify"}, "add", "trash"}, + {[]string{"calendar", "create"}, "send-updates", "all"}, + {[]string{"drive", "upload"}, "name", "private,report.txt"}, + {[]string{"drive", "upload"}, "name", "a.b"}, + } + for _, c := range cases { + runtime := bakedSafetyDeniedValueHash(c.path, c.flag, c.value) + codegen := safetyprofile.HashRule(safetyprofile.DeniedValueKey(strings.Join(c.path, "."), c.flag, c.value)) + if runtime != codegen { + t.Fatalf("hash mismatch for %v %s %q: runtime=%#x codegen=%#x", c.path, c.flag, c.value, runtime, codegen) + } + } + // The value is set apart from the flag, so a rule for one flag cannot collide + // with a rule for a dotted flag-and-value spelling of another. + if bakedSafetyDeniedValueHash([]string{"a"}, "b", "c.d") == bakedSafetyDeniedValueHash([]string{"a", "b"}, "c", "d") { + t.Fatalf("denied value keys for distinct rules must differ") + } +} + func TestBakedSafetyProfileBlocksBeforeRuntimeAllowlist(t *testing.T) { setTestConfigHome(t) withBakedSafetyProfile(t, ` diff --git a/internal/safetyprofile/denied_values_test.go b/internal/safetyprofile/denied_values_test.go new file mode 100644 index 000000000..f39a82b8b --- /dev/null +++ b/internal/safetyprofile/denied_values_test.go @@ -0,0 +1,124 @@ +package safetyprofile + +import ( + "reflect" + "strings" + "testing" +) + +func TestParse_DeniedValues(t *testing.T) { + profile, err := Parse(` +name: denied +denied-values: + gmail.thread.modify: + add: [TRASH, " Spam "] + add-label: [TRASH, SPAM, trash] + Calendar Create: + send-updates: [all, externalOnly] +gmail: + thread: + modify: true +calendar: + create: true +`) + if err != nil { + t.Fatalf("Parse: %v", err) + } + want := []DeniedValue{ + {Path: "calendar.create", Flag: "send-updates", Values: []string{"all", "externalonly"}}, + {Path: "gmail.thread.modify", Flag: "add", Values: []string{"spam", "trash"}}, + {Path: "gmail.thread.modify", Flag: "add-label", Values: []string{"spam", "trash"}}, + } + if !reflect.DeepEqual(profile.DeniedValues, want) { + t.Fatalf("denied values = %#v, want %#v", profile.DeniedValues, want) + } +} + +func TestParse_DeniedValuesRejectsMalformedRules(t *testing.T) { + cases := map[string]string{ + "non-list": "gmail.thread.modify:\n add: TRASH", + "empty list": "gmail.thread.modify:\n add: []", + "nested map": "gmail.thread.modify:\n add:\n nested: [TRASH]", + "empty string": "gmail.thread.modify:\n add: [\"\"]", + "blank string": "gmail.thread.modify:\n add: [\" \"]", + "non-string": "gmail.thread.modify:\n add: [true]", + "nested item": "gmail.thread.modify:\n add: [[TRASH]]", + "wildcard path": "'*':\n add: [TRASH]", + "all path": "all:\n add: [TRASH]", + "empty flag": "gmail.thread.modify:\n \"\": [TRASH]", + "flags not map": "gmail.thread.modify: [TRASH]", + "top not map": "[gmail.thread.modify]", + "empty path key": "\"\":\n add: [TRASH]", + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + _, err := Parse("name: denied\ngmail:\n thread:\n modify: true\ndenied-values:\n " + strings.ReplaceAll(body, "\n", "\n ")) + if err == nil { + t.Fatal("malformed denied-values must be rejected") + } + if !strings.HasPrefix(err.Error(), "denied-values: ") { + t.Fatalf("error must come from the denied-values parser, got: %v", err) + } + }) + } +} + +func TestParse_DeniedValuesAnyValue(t *testing.T) { + profile, err := Parse(` +name: denied +denied-values: + calendar.create: + focus-chat-status: ["*"] +calendar: + create: true +`) + if err != nil { + t.Fatalf("Parse: %v", err) + } + want := []DeniedValue{{Path: "calendar.create", Flag: "focus-chat-status", Values: []string{"*"}}} + if !reflect.DeepEqual(profile.DeniedValues, want) { + t.Fatalf("denied values = %#v, want %#v", profile.DeniedValues, want) + } +} + +// "*" means any value, so listing other values beside it is ambiguous. +func TestParse_DeniedValuesAnyValueMustStandAlone(t *testing.T) { + for _, list := range []string{`["*", all]`, `[all, "*"]`, `[" * ", x]`} { + _, err := Parse("name: denied\ncalendar:\n create: true\ndenied-values:\n calendar.create:\n send-updates: " + list + "\n") + if err == nil || !strings.HasPrefix(err.Error(), "denied-values: ") { + t.Fatalf("%s must be rejected by the denied-values parser, got %v", list, err) + } + } +} + +// denied-values must not be flattened into command rules the way other top-level +// keys are. +func TestParse_DeniedValuesAreNotCommandRules(t *testing.T) { + profile, err := Parse(` +name: denied +denied-values: + gmail.thread.modify: + add: [TRASH] +gmail: + thread: + modify: true +`) + if err != nil { + t.Fatalf("Parse: %v", err) + } + for _, rule := range append(profile.AllowRules, profile.DenyRules...) { + if rule != "gmail.thread.modify" { + t.Fatalf("denied value leaked into command rules: %q", rule) + } + } +} + +func TestParse_WithoutDeniedValues(t *testing.T) { + profile, err := Parse("name: plain\ngmail:\n get: true\n") + if err != nil { + t.Fatalf("Parse: %v", err) + } + if len(profile.DeniedValues) != 0 { + t.Fatalf("denied values = %#v", profile.DeniedValues) + } +} diff --git a/internal/safetyprofile/hash.go b/internal/safetyprofile/hash.go index bc7bc7130..74822a821 100644 --- a/internal/safetyprofile/hash.go +++ b/internal/safetyprofile/hash.go @@ -11,3 +11,11 @@ func HashRule(rule string) uint64 { _, _ = h.Write([]byte(rule)) return h.Sum64() } + +// DeniedValueKey is the string hashed for one refused value of a denied-values rule: +// the dotted command path, the flag, and the lowercased value after a NUL, so a value +// containing dots cannot collide with another rule's path or flag. Hashing the values +// keeps them out of the binary, like the command rules. +func DeniedValueKey(path, flag, value string) string { + return path + "." + flag + "\x00" + value +} diff --git a/internal/safetyprofile/parse.go b/internal/safetyprofile/parse.go index 6b2c5f905..1db2bb212 100644 --- a/internal/safetyprofile/parse.go +++ b/internal/safetyprofile/parse.go @@ -10,6 +10,9 @@ import ( const literalAll = "all" +// anyValue as the sole entry of a denied-values list refuses every non-empty value. +const anyValue = "*" + // Parse validates the YAML form of a safety profile and returns the Profile // the generator emits as code. Allow and deny lists are sorted and // deduplicated; "all" / "*" entries on the allow side collapse into the @@ -29,6 +32,23 @@ func Parse(raw string) (*Profile, error) { out.LockedFlags = append(out.LockedFlags, LockedFlag{Name: name, Value: value}) } sort.Slice(out.LockedFlags, func(i, j int) bool { return out.LockedFlags[i].Name < out.LockedFlags[j].Name }) + for path, flags := range parsed.deniedValues { + for flag, values := range flags { + rule := DeniedValue{Path: path, Flag: flag} + for value := range values { + rule.Values = append(rule.Values, value) + } + sort.Strings(rule.Values) + out.DeniedValues = append(out.DeniedValues, rule) + } + } + sort.Slice(out.DeniedValues, func(i, j int) bool { + a, b := out.DeniedValues[i], out.DeniedValues[j] + if a.Path != b.Path { + return a.Path < b.Path + } + return a.Flag < b.Flag + }) for k := range parsed.allow { if k == literalAll || k == "*" { continue @@ -48,6 +68,8 @@ type rawProfile struct { allow map[string]bool deny map[string]bool lockedFlags map[string]string + // deniedValues maps a command path to a flag name to the set of refused values. + deniedValues map[string]map[string]map[string]bool } func parseRaw(raw string) (*rawProfile, error) { @@ -57,10 +79,11 @@ func parseRaw(raw string) (*rawProfile, error) { } profile := &rawProfile{ - name: "unnamed", - allow: map[string]bool{}, - deny: map[string]bool{}, - lockedFlags: map[string]string{}, + name: "unnamed", + allow: map[string]bool{}, + deny: map[string]bool{}, + lockedFlags: map[string]string{}, + deniedValues: map[string]map[string]map[string]bool{}, } if rawName, present := root["name"]; present { @@ -79,10 +102,13 @@ func parseRaw(raw string) (*rawProfile, error) { if err := addLockedFlags(profile.lockedFlags, root["locked-flags"]); err != nil { return nil, fmt.Errorf("locked-flags: %w", err) } + if err := addDeniedValues(profile.deniedValues, root["denied-values"]); err != nil { + return nil, fmt.Errorf("denied-values: %w", err) + } for key, value := range root { switch key { - case "name", "description", "allow", "deny", "locked-flags": + case "name", "description", "allow", "deny", "locked-flags", "denied-values": continue } prefix := []string{key} @@ -149,6 +175,67 @@ func addLockedFlags(out map[string]string, value any) error { return nil } +// addDeniedValues reads the denied-values mapping of command path to flag name to a +// list of refused values. Paths are normalized like command rules, flag names and +// values are lowercased and trimmed so the runtime compares case-insensitively. +// A list holding only "*" refuses any non-empty value of the flag. +func addDeniedValues(out map[string]map[string]map[string]bool, value any) error { + if value == nil { + return nil + } + commands, ok := value.(map[string]any) + if !ok { + return fmt.Errorf("expected mapping of command path to flags") + } + for rawPath, rawFlags := range commands { + path := normalize(rawPath) + if path == "" { + return fmt.Errorf("empty command path") + } + if path == literalAll || path == "*" { + return fmt.Errorf("%s: wildcard paths are not allowed; list specific commands", rawPath) + } + flags, ok := rawFlags.(map[string]any) + if !ok { + return fmt.Errorf("%s: expected mapping of flag name to list of values, got %T", path, rawFlags) + } + for rawFlag, rawValues := range flags { + flag := strings.TrimSpace(strings.ToLower(rawFlag)) + if flag == "" { + return fmt.Errorf("%s: empty flag name", path) + } + items, ok := rawValues.([]any) + if !ok { + return fmt.Errorf("%s.%s: expected list of values, got %T", path, flag, rawValues) + } + if len(items) == 0 { + return fmt.Errorf("%s.%s: expected at least one value", path, flag) + } + if out[path] == nil { + out[path] = map[string]map[string]bool{} + } + if out[path][flag] == nil { + out[path][flag] = map[string]bool{} + } + for _, item := range items { + s, ok := item.(string) + if !ok { + return fmt.Errorf("%s.%s: expected string value, got %T", path, flag, item) + } + s = strings.TrimSpace(strings.ToLower(s)) + if s == "" { + return fmt.Errorf("%s.%s: empty value", path, flag) + } + out[path][flag][s] = true + } + if out[path][flag][anyValue] && len(out[path][flag]) > 1 { + return fmt.Errorf("%s.%s: %q denies every value and cannot be combined with others", path, flag, anyValue) + } + } + } + return nil +} + func flatten(profile *rawProfile, prefix []string, value any) error { switch typed := value.(type) { case bool: diff --git a/internal/safetyprofile/profile.go b/internal/safetyprofile/profile.go index f314c912c..0a3b49008 100644 --- a/internal/safetyprofile/profile.go +++ b/internal/safetyprofile/profile.go @@ -17,6 +17,18 @@ type Profile struct { // LockedFlags fix a flag to a value the command line cannot change. Sorted by // name so the generated switch is stable across builds. LockedFlags []LockedFlag + // DeniedValues refuse specific values of string flags on specific commands. + // Sorted by path then flag so the generated switch is stable across builds. + DeniedValues []DeniedValue +} + +// DeniedValue is one flag of one command and the values it may not be given. +// Path is the canonical dotted command path, Flag the canonical flag name, and +// Values the lowercased, deduplicated, sorted values to refuse. +type DeniedValue struct { + Path string + Flag string + Values []string } // LockedFlag is one locked boolean flag. Value is "true" or "false" in the form diff --git a/safety-profiles/agent-safe.yaml b/safety-profiles/agent-safe.yaml index a75921044..760b94bff 100644 --- a/safety-profiles/agent-safe.yaml +++ b/safety-profiles/agent-safe.yaml @@ -4,6 +4,48 @@ description: Agent workflow profile. Allows reading, drafting, organizing, and r version: true schema: true +# Allowed label commands must not move mail to the trash or spam, and allowed +# calendar writes must not email the guests. +denied-values: + gmail.messages.modify: + add: [TRASH, SPAM] + gmail.thread.modify: + add: [TRASH, SPAM] + add-label: [TRASH, SPAM] + gmail.labels.modify: + add: [TRASH, SPAM] + gmail.batch.modify: + add: [TRASH, SPAM] + add-label: [TRASH, SPAM] + # create and update also write focus-time and out-of-office events, whose + # auto-decline defaults to all, by --event-type or by type inference from any + # focus or out-of-office flag. Only an explicit auto-decline none passes. + calendar.create: + send-updates: [all, externalonly] + event-type: [focus, focus-time, focus_time, focustime, ooo, out-of-office, out_of_office, outofoffice] + focus-auto-decline: [all, new] + ooo-auto-decline: [all, new] + focus-decline-message: ["*"] + focus-chat-status: ["*"] + ooo-decline-message: ["*"] + calendar.update: + send-updates: [all, externalonly] + event-type: [focus, focus-time, focus_time, focustime, ooo, out-of-office, out_of_office, outofoffice] + # update infers the type from any supplied focus or out-of-office flag, even + # with an empty value, and an empty auto-decline defaults to all. Every use of + # these flags is refused, including an explicit none. + focus-auto-decline: ["*"] + ooo-auto-decline: ["*"] + focus-decline-message: ["*"] + focus-chat-status: ["*"] + ooo-decline-message: ["*"] + calendar.move: + send-updates: [all, externalonly] + # --auto-decline defaults to all; declining a conflicting invitation notifies + # its organizer, so focus time needs an explicit --auto-decline none. + calendar.focus-time: + auto-decline: [all, new] + gmail: search: true get: true @@ -67,7 +109,7 @@ calendar: delete: false freebusy: true respond: false - propose-time: true + propose-time: false colors: true conflicts: true search: true @@ -99,10 +141,10 @@ drive: comments: list: true get: true - create: true - update: true + create: false + update: false delete: false - reply: true + reply: false sites: list: true @@ -173,8 +215,8 @@ docs: comments: list: true get: true - add: true - reply: true + add: false + reply: false resolve: false delete: false