From 841c3779fc294e35f00fb0a5ae9c0642dd53714c Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Sat, 24 Oct 2026 12:58:37 -0500 Subject: [PATCH 1/9] feat(safety): deny specific flag values in baked profiles Add a denied-values profile key that refuses named values of string and list flags on a specific command. agent-safe uses it to refuse the TRASH and SPAM labels on the Gmail modify commands and --send-updates all|externalOnly on calendar create, update and move, which were reachable through allowed commands. agent-safe also blocks calendar propose-time and Drive and Docs comment writes, which notify other people. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1fj3CKEioe5f7QqomgCCv --- CHANGELOG.md | 2 + cmd/bake-safety-profile/denied_values_test.go | 70 +++++ cmd/bake-safety-profile/main.go | 34 ++ docs/safety-profiles.md | 58 +++- internal/cmd/root.go | 4 +- internal/cmd/safety_profile.go | 112 +++++++ internal/cmd/safety_profile_default.go | 14 + .../cmd/safety_profile_denied_values_test.go | 291 ++++++++++++++++++ internal/cmd/safety_profile_test.go | 8 + internal/safetyprofile/denied_values_test.go | 96 ++++++ internal/safetyprofile/parse.go | 90 +++++- internal/safetyprofile/profile.go | 12 + safety-profiles/agent-safe.yaml | 32 +- 13 files changed, 808 insertions(+), 15 deletions(-) create mode 100644 cmd/bake-safety-profile/denied_values_test.go create mode 100644 internal/cmd/safety_profile_denied_values_test.go create mode 100644 internal/safetyprofile/denied_values_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index cc8593e54..ec652e46d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,8 @@ The backup changes in #1303 and #1304 preserve existing saved remotes and Git or - Dependencies: update Google IAM, GAX, enterprise certificate support, Workers types, Wrangler, and oxlint-tsgolint while retaining Go 1.26 and the tracking worker’s 24-hour release cooldown. +- 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; `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#TBD) + ## 0.47.0 - 2026-10-23 **Highlights:** Opt-in HTML Gmail bodies, selected search headers, and calendar settings updates, with OAuth error redaction and certificate trust fixes. 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..79bf3270e --- /dev/null +++ b/cmd/bake-safety-profile/denied_values_test.go @@ -0,0 +1,70 @@ +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"}}, + }, + } + + 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; the values are the + // literals the runtime compares against. + for _, rule := range profile.DeniedValues { + quoted := "" + for i, v := range rule.Values { + if i > 0 { + quoted += ", " + } + quoted += fmt.Sprintf("%q", v) + } + want := fmt.Sprintf("\tcase 0x%016x:\n\t\treturn []string{%s}\n", safetyprofile.HashRule(rule.Path+"."+rule.Flag), quoted) + if !bytes.Contains(out, []byte(want)) { + t.Fatalf("generated output missing case for %s %s:\n%s\n\nfull output:\n%s", rule.Path, rule.Flag, want, out) + } + for _, verbatim := range []string{rule.Path, rule.Flag} { + 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 !bytes.Contains(out, []byte("func bakedSafetyDeniedValueRuleCount() int { return 2 }\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 bakedSafetyDeniedValues(path []string, flag string) []string {\n\treturn nil\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..db9a7ebd5 100644 --- a/cmd/bake-safety-profile/main.go +++ b/cmd/bake-safety-profile/main.go @@ -68,10 +68,44 @@ 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 lookup. The command path and flag name are +// hashed together like a command rule; the refused values are literals because the +// runtime compares user input against them. 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 bakedSafetyDeniedValues(path []string, flag string) []string {\n") + if len(rules) == 0 { + out.WriteString("\treturn nil\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)) + 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 + quoted := make([]string, len(rule.Values)) + for i, value := range rule.Values { + quoted[i] = strconv.Quote(value) + } + fmt.Fprintf(out, "\tcase 0x%016x:\n\t\treturn []string{%s}\n", h, strings.Join(quoted, ", ")) + } + out.WriteString("\t}\n\treturn nil\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..d87c859e8 100644 --- a/docs/safety-profiles.md +++ b/docs/safety-profiles.md @@ -108,8 +108,11 @@ 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 and `--send-updates all|externalOnly` on calendar create, update +and move, 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 +166,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 +252,56 @@ 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 split on commas and trimmed, so `trash`, ` Trash ` and `INBOX,TRASH` + all match `TRASH`. 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. + +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..8ab29f5c1 100644 --- a/internal/cmd/safety_profile.go +++ b/internal/cmd/safety_profile.go @@ -4,6 +4,7 @@ import ( "fmt" "hash/fnv" "reflect" + "slices" "sort" "strings" @@ -204,6 +205,117 @@ 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 len(bakedSafetyDeniedValues(path, flag.Name)) == 0 { + 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. +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() { + denied := bakedSafetyDeniedValues(path, flag.Name) + if len(denied) == 0 { + continue + } + for _, raw := range flagStringValues(flag.Target) { + for _, value := range splitCSV(raw) { + if slices.Contains(denied, 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..add9d018b 100644 --- a/internal/cmd/safety_profile_default.go +++ b/internal/cmd/safety_profile_default.go @@ -19,6 +19,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 +53,15 @@ func bakedSafetyLockedFlag(name string) (string, bool) { func bakedSafetyLockedFlagCount() int { return len(bakedSafetyTestProfile.lockedFlags) } + +func bakedSafetyDeniedValues(path []string, flag string) []string { + return bakedSafetyTestProfile.deniedValues[strings.Join(path, ".")][flag] +} + +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..aef989f50 --- /dev/null +++ b/internal/cmd/safety_profile_denied_values_test.go @@ -0,0 +1,291 @@ +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")) +} + +// 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, + } + 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) + } +} + +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..5be37adf6 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 }) } diff --git a/internal/safetyprofile/denied_values_test.go b/internal/safetyprofile/denied_values_test.go new file mode 100644 index 000000000..62fd0d1e5 --- /dev/null +++ b/internal/safetyprofile/denied_values_test.go @@ -0,0 +1,96 @@ +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) + } + }) + } +} + +// 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/parse.go b/internal/safetyprofile/parse.go index 6b2c5f905..f67c6c776 100644 --- a/internal/safetyprofile/parse.go +++ b/internal/safetyprofile/parse.go @@ -29,6 +29,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 +65,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 +76,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 +99,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 +172,63 @@ 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. +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 + } + } + } + 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..f14bdead8 100644 --- a/safety-profiles/agent-safe.yaml +++ b/safety-profiles/agent-safe.yaml @@ -4,6 +4,26 @@ 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] + calendar.create: + send-updates: [all, externalonly] + calendar.update: + send-updates: [all, externalonly] + calendar.move: + send-updates: [all, externalonly] + gmail: search: true get: true @@ -67,7 +87,7 @@ calendar: delete: false freebusy: true respond: false - propose-time: true + propose-time: false colors: true conflicts: true search: true @@ -99,10 +119,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 +193,8 @@ docs: comments: list: true get: true - add: true - reply: true + add: false + reply: false resolve: false delete: false From b5c26df9575d0aa4450696b9630b50550b80afec Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Sat, 24 Oct 2026 12:59:05 -0500 Subject: [PATCH 2/9] docs(changelog): reference #1263 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1fj3CKEioe5f7QqomgCCv --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec652e46d..46423084f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,7 @@ The backup changes in #1303 and #1304 preserve existing saved remotes and Git or - Dependencies: update Google IAM, GAX, enterprise certificate support, Workers types, Wrangler, and oxlint-tsgolint while retaining Go 1.26 and the tracking worker’s 24-hour release cooldown. -- 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; `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#TBD) +- 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; `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#1263) ## 0.47.0 - 2026-10-23 From 2c308ccd5f52b0f376ad9443181ae34234a38532 Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Sat, 24 Oct 2026 13:03:33 -0500 Subject: [PATCH 3/9] fix(safety): deny auto-declining focus time in agent-safe calendar focus-time defaults to --auto-decline all, and declining a conflicting invitation notifies its organizer. Deny all and new so agent-safe only creates focus time with an explicit --auto-decline none. Denied values are read from the parsed flag, so the default is refused too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1fj3CKEioe5f7QqomgCCv --- CHANGELOG.md | 2 +- docs/safety-profiles.md | 5 +++-- internal/cmd/safety_profile_denied_values_test.go | 3 +++ safety-profiles/agent-safe.yaml | 4 ++++ 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46423084f..e5f9422b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,7 @@ The backup changes in #1303 and #1304 preserve existing saved remotes and Git or - Dependencies: update Google IAM, GAX, enterprise certificate support, Workers types, Wrangler, and oxlint-tsgolint while retaining Go 1.26 and the tracking worker’s 24-hour release cooldown. -- 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; `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#1263) +- 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, and auto-declining `calendar focus-time` (pass `--auto-decline none`); `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#1263) ## 0.47.0 - 2026-10-23 diff --git a/docs/safety-profiles.md b/docs/safety-profiles.md index d87c859e8..d77ee47e7 100644 --- a/docs/safety-profiles.md +++ b/docs/safety-profiles.md @@ -109,8 +109,9 @@ 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. Refuses the `TRASH` and `SPAM` labels on the Gmail -modify commands and `--send-updates all|externalOnly` on calendar create, update -and move, and blocks `calendar propose-time` and Drive and Docs comments, because +modify commands, `--send-updates all|externalOnly` on calendar create, update +and move, and any `calendar focus-time` that auto-declines (it defaults to +`--auto-decline all`, so pass `--auto-decline none`), 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. diff --git a/internal/cmd/safety_profile_denied_values_test.go b/internal/cmd/safety_profile_denied_values_test.go index aef989f50..e2a23ffee 100644 --- a/internal/cmd/safety_profile_denied_values_test.go +++ b/internal/cmd/safety_profile_denied_values_test.go @@ -251,6 +251,9 @@ func TestAgentSafeProfileDeniesDestructiveAndNotifyingValues(t *testing.T) { "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"}, } if !reflect.DeepEqual(got, want) { t.Fatalf("agent-safe denied-values = %#v, want %#v", got, want) diff --git a/safety-profiles/agent-safe.yaml b/safety-profiles/agent-safe.yaml index f14bdead8..99824b5fe 100644 --- a/safety-profiles/agent-safe.yaml +++ b/safety-profiles/agent-safe.yaml @@ -23,6 +23,10 @@ denied-values: send-updates: [all, externalonly] 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 From 8ec781e66200e8d29673750789282f44cf2db5a4 Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Sat, 24 Oct 2026 13:39:40 -0500 Subject: [PATCH 4/9] feat(safety): any-value denies; close focus and OOO auto-decline in agent-safe A denied-values list of ["*"] refuses any value typed for the flag. agent-safe uses it, plus the focus-time and out-of-office event-type aliases, to stop calendar create and update from making focus or OOO events whose auto-decline defaults to all and notifies organizers. Explicit --focus-auto-decline none and --ooo-auto-decline none still work on create. update infers the type from any supplied focus or OOO flag, even an empty one, so its auto-decline flags take ["*"]. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1fj3CKEioe5f7QqomgCCv --- CHANGELOG.md | 2 +- docs/safety-profiles.md | 18 ++- internal/cmd/safety_profile.go | 11 +- .../cmd/safety_profile_denied_values_test.go | 137 ++++++++++++++++++ internal/safetyprofile/denied_values_test.go | 28 ++++ internal/safetyprofile/parse.go | 7 + safety-profiles/agent-safe.yaml | 18 +++ 7 files changed, 217 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5f9422b4..4e3586a84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,7 @@ The backup changes in #1303 and #1304 preserve existing saved remotes and Git or - Dependencies: update Google IAM, GAX, enterprise certificate support, Workers types, Wrangler, and oxlint-tsgolint while retaining Go 1.26 and the tracking worker’s 24-hour release cooldown. -- 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, and auto-declining `calendar focus-time` (pass `--auto-decline none`); `agent-safe` also blocks `calendar propose-time` and Drive and Docs comments, which notify other people. (#1263) +- 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) ## 0.47.0 - 2026-10-23 diff --git a/docs/safety-profiles.md b/docs/safety-profiles.md index d77ee47e7..f292e5660 100644 --- a/docs/safety-profiles.md +++ b/docs/safety-profiles.md @@ -110,8 +110,11 @@ Allows reading, searching, drafting, labeling, archiving, organizing files, and other low-risk recoverable actions. Blocks sends, deletes, sharing changes, admin 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, and any `calendar focus-time` that auto-declines (it defaults to -`--auto-decline all`, so pass `--auto-decline none`), and blocks `calendar propose-time` and Drive and Docs comments, because +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. @@ -294,6 +297,17 @@ flag --add value "TRASH" is denied for "gmail thread modify" by baked safety pro - 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. `"*"` 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 diff --git a/internal/cmd/safety_profile.go b/internal/cmd/safety_profile.go index 8ab29f5c1..e566226e8 100644 --- a/internal/cmd/safety_profile.go +++ b/internal/cmd/safety_profile.go @@ -276,7 +276,9 @@ func verifyDeniedValueRulesExist(root *kong.Node) error { // 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. +// 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 @@ -290,7 +292,14 @@ func enforceDeniedValues(kctx *kong.Context) error { if len(denied) == 0 { continue } + anyValue := slices.Contains(denied, "*") 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()) + } for _, value := range splitCSV(raw) { if slices.Contains(denied, 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()) diff --git a/internal/cmd/safety_profile_denied_values_test.go b/internal/cmd/safety_profile_denied_values_test.go index e2a23ffee..e838dafda 100644 --- a/internal/cmd/safety_profile_denied_values_test.go +++ b/internal/cmd/safety_profile_denied_values_test.go @@ -255,6 +255,24 @@ func TestAgentSafeProfileDeniesDestructiveAndNotifyingValues(t *testing.T) { // 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) } @@ -275,6 +293,125 @@ func TestAgentSafeProfileDeniedValueRulesAllExist(t *testing.T) { } } +// "*" 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) + } + } +} + +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")) diff --git a/internal/safetyprofile/denied_values_test.go b/internal/safetyprofile/denied_values_test.go index 62fd0d1e5..f39a82b8b 100644 --- a/internal/safetyprofile/denied_values_test.go +++ b/internal/safetyprofile/denied_values_test.go @@ -63,6 +63,34 @@ func TestParse_DeniedValuesRejectsMalformedRules(t *testing.T) { } } +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) { diff --git a/internal/safetyprofile/parse.go b/internal/safetyprofile/parse.go index f67c6c776..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 @@ -175,6 +178,7 @@ func addLockedFlags(out map[string]string, value any) error { // 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 @@ -224,6 +228,9 @@ func addDeniedValues(out map[string]map[string]map[string]bool, value any) error } 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 diff --git a/safety-profiles/agent-safe.yaml b/safety-profiles/agent-safe.yaml index 99824b5fe..760b94bff 100644 --- a/safety-profiles/agent-safe.yaml +++ b/safety-profiles/agent-safe.yaml @@ -17,10 +17,28 @@ denied-values: 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 From d3387ab708f851b1ef688d3baf97e1e9b77b418b Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Sat, 24 Oct 2026 13:48:29 -0500 Subject: [PATCH 5/9] fix(review): pass 1 - match whole denied values before comma parts - codex: a denied value containing a comma never matched, because only the comma-separated parts of the input were compared. The whole trimmed value is now compared too (--add-label takes names literally, commas included). Test fails without the change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1fj3CKEioe5f7QqomgCCv --- internal/cmd/safety_profile.go | 4 +++- .../cmd/safety_profile_denied_values_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/cmd/safety_profile.go b/internal/cmd/safety_profile.go index e566226e8..cc48973a5 100644 --- a/internal/cmd/safety_profile.go +++ b/internal/cmd/safety_profile.go @@ -300,7 +300,9 @@ func enforceDeniedValues(kctx *kong.Context) error { 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()) } - for _, value := range splitCSV(raw) { + // 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 slices.Contains(denied, 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()) } diff --git a/internal/cmd/safety_profile_denied_values_test.go b/internal/cmd/safety_profile_denied_values_test.go index e838dafda..18dd8982f 100644 --- a/internal/cmd/safety_profile_denied_values_test.go +++ b/internal/cmd/safety_profile_denied_values_test.go @@ -120,6 +120,24 @@ func TestDeniedValues_MatchesWholeValuesOnly(t *testing.T) { 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) { From b984dde3f06addb5a24e98b3c78f7c1ee55cfc0a Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Sat, 24 Oct 2026 13:54:14 -0500 Subject: [PATCH 6/9] docs(changelog): thank the contributor for #1263 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1fj3CKEioe5f7QqomgCCv --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e3586a84..01964edd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,7 @@ The backup changes in #1303 and #1304 preserve existing saved remotes and Git or - Dependencies: update Google IAM, GAX, enterprise certificate support, Workers types, Wrangler, and oxlint-tsgolint while retaining Go 1.26 and the tracking worker’s 24-hour release cooldown. -- 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) +- 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.47.0 - 2026-10-23 From 85925a05ec0da24fb1d0f24dff2b64e5b72eae1c Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Wed, 4 Nov 2026 17:49:44 -0600 Subject: [PATCH 7/9] docs(safety): wildcard denials refuse a non-empty default An omitted flag is allowed under "*" only when its default is empty. calendar focus-time with auto-decline: ["*"] still refuses an omitted --auto-decline, whose default is all. Also say values are compared whole before comma splitting. The new test fails when the default branch of the check is removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T2aiSKKPHZ2qnjrALo2Y1A --- docs/safety-profiles.md | 9 ++++++--- .../cmd/safety_profile_denied_values_test.go | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/docs/safety-profiles.md b/docs/safety-profiles.md index f292e5660..9fb268c00 100644 --- a/docs/safety-profiles.md +++ b/docs/safety-profiles.md @@ -286,8 +286,9 @@ 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 split on commas and trimmed, so `trash`, ` Trash ` and `INBOX,TRASH` - all match `TRASH`. Splitting more aggressively than a command does can only + 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: @@ -301,7 +302,9 @@ flag --add value "TRASH" is denied for "gmail thread modify" by baked safety pro 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. `"*"` must be the only entry in its list. + 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: diff --git a/internal/cmd/safety_profile_denied_values_test.go b/internal/cmd/safety_profile_denied_values_test.go index 18dd8982f..9d55bd901 100644 --- a/internal/cmd/safety_profile_denied_values_test.go +++ b/internal/cmd/safety_profile_denied_values_test.go @@ -350,6 +350,23 @@ gmail: } } +// 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) From b59796aaa9a295523590f3320c3724d24191b02e Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Wed, 4 Nov 2026 17:59:26 -0600 Subject: [PATCH 8/9] docs(changelog): move #1263 under 0.47.2 Unreleased 0.47.1 shipped on 2026-10-26 without this change, so the entry belongs in the open release. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T2aiSKKPHZ2qnjrALo2Y1A --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01964edd0..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. @@ -66,8 +68,6 @@ The backup changes in #1303 and #1304 preserve existing saved remotes and Git or - Dependencies: update Google IAM, GAX, enterprise certificate support, Workers types, Wrangler, and oxlint-tsgolint while retaining Go 1.26 and the tracking worker’s 24-hour release cooldown. -- 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.47.0 - 2026-10-23 **Highlights:** Opt-in HTML Gmail bodies, selected search headers, and calendar settings updates, with OAuth error redaction and certificate trust fixes. From aef4aaa41dd75ea214195aa82f08bcbd003b55be Mon Sep 17 00:00:00 2001 From: Burke Autrey Date: Fri, 13 Nov 2026 14:52:49 -0600 Subject: [PATCH 9/9] fix(safety): hash denied values instead of embedding them The generator hashed the command path and flag of a denied-values rule but emitted the refused values as string literals, so an equal-length edit of the binary (private,report.txt -> private,report.csv) could lift a denial without touching compiled code. That reopened the ASCII patching the Tamper Resistance section and #540 closed. Each refused value is now hashed with its path and flag (safetyprofile.DeniedValueKey, NUL before the value), and the runtime hashes the whole value and each comma part the same way before the switch. The rule case reports whether it refuses any value, so "*" is compiled control flow too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NAC67iQrvrvQdbbutzzLzg --- cmd/bake-safety-profile/denied_values_test.go | 34 +++++++------ cmd/bake-safety-profile/main.go | 48 ++++++++++++++----- docs/safety-profiles.md | 5 +- internal/cmd/safety_profile.go | 19 +++++--- internal/cmd/safety_profile_default.go | 18 +++++-- internal/cmd/safety_profile_test.go | 26 ++++++++++ internal/safetyprofile/hash.go | 8 ++++ 7 files changed, 122 insertions(+), 36 deletions(-) diff --git a/cmd/bake-safety-profile/denied_values_test.go b/cmd/bake-safety-profile/denied_values_test.go index 79bf3270e..e99ea1017 100644 --- a/cmd/bake-safety-profile/denied_values_test.go +++ b/cmd/bake-safety-profile/denied_values_test.go @@ -17,6 +17,8 @@ func TestGenerateDeniedValuesEmitsHashedLookup(t *testing.T) { 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{"*"}}, }, } @@ -26,27 +28,30 @@ func TestGenerateDeniedValuesEmitsHashedLookup(t *testing.T) { 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; the values are the - // literals the runtime compares against. + // 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 { - quoted := "" - for i, v := range rule.Values { - if i > 0 { - quoted += ", " - } - quoted += fmt.Sprintf("%q", v) - } - want := fmt.Sprintf("\tcase 0x%016x:\n\t\treturn []string{%s}\n", safetyprofile.HashRule(rule.Path+"."+rule.Flag), quoted) + 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 case for %s %s:\n%s\n\nfull output:\n%s", rule.Path, rule.Flag, want, out) + 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 []string{rule.Path, rule.Flag} { + 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 2 }\n")) { + if !bytes.Contains(out, []byte("func bakedSafetyDeniedValueRuleCount() int { return 4 }\n")) { t.Fatalf("generated output missing the rule count:\n%s", out) } } @@ -60,7 +65,8 @@ func TestGenerateWithoutDeniedValuesStillDefinesLookup(t *testing.T) { t.Fatalf("generated code does not parse as Go:\n%s\n\nerror: %v", out, err) } for _, want := range []string{ - "func bakedSafetyDeniedValues(path []string, flag string) []string {\n\treturn nil\n}\n", + "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)) { diff --git a/cmd/bake-safety-profile/main.go b/cmd/bake-safety-profile/main.go index db9a7ebd5..1e4f5e614 100644 --- a/cmd/bake-safety-profile/main.go +++ b/cmd/bake-safety-profile/main.go @@ -74,20 +74,23 @@ func generate(profile *safetyprofile.Profile) []byte { return out.Bytes() } -// writeDeniedValues emits the denied value lookup. The command path and flag name are -// hashed together like a command rule; the refused values are literals because the -// runtime compares user input against them. The count travels alongside so the -// runtime can tell that every rule matched a real flag without the names being -// written down. +// 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 bakedSafetyDeniedValues(path []string, flag string) []string {\n") + out.WriteString("func bakedSafetyDeniedValueRule(path []string, flag string) (bool, bool) {\n") if len(rules) == 0 { - out.WriteString("\treturn nil\n}\n") + 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) @@ -96,13 +99,34 @@ func writeDeniedValues(out *bytes.Buffer, rules []safetyprofile.DeniedValue) { os.Exit(1) } seen[h] = key - quoted := make([]string, len(rule.Values)) - for i, value := range rule.Values { - quoted[i] = strconv.Quote(value) + 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 } - fmt.Fprintf(out, "\tcase 0x%016x:\n\t\treturn []string{%s}\n", h, strings.Join(quoted, ", ")) + 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") } - out.WriteString("\t}\n\treturn nil\n}\n") fmt.Fprintf(out, "\nfunc bakedSafetyDeniedValueRuleCount() int { return %d }\n", len(rules)) } diff --git a/docs/safety-profiles.md b/docs/safety-profiles.md index 9fb268c00..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 diff --git a/internal/cmd/safety_profile.go b/internal/cmd/safety_profile.go index cc48973a5..2ae7be916 100644 --- a/internal/cmd/safety_profile.go +++ b/internal/cmd/safety_profile.go @@ -4,7 +4,6 @@ import ( "fmt" "hash/fnv" "reflect" - "slices" "sort" "strings" @@ -28,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 { @@ -253,7 +261,7 @@ func verifyDeniedValueRulesExist(root *kong.Node) error { if node.Type == kong.CommandNode { path := commandNodePath(node) for _, flag := range node.Flags { - if len(bakedSafetyDeniedValues(path, flag.Name)) == 0 { + if exists, _ := bakedSafetyDeniedValueRule(path, flag.Name); !exists { continue } seen++ @@ -288,11 +296,10 @@ func enforceDeniedValues(kctx *kong.Context) error { return nil } for _, flag := range kctx.Flags() { - denied := bakedSafetyDeniedValues(path, flag.Name) - if len(denied) == 0 { + exists, anyValue := bakedSafetyDeniedValueRule(path, flag.Name) + if !exists { continue } - anyValue := slices.Contains(denied, "*") 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 @@ -303,7 +310,7 @@ func enforceDeniedValues(kctx *kong.Context) error { // 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 slices.Contains(denied, strings.ToLower(value)) { + 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()) } } diff --git a/internal/cmd/safety_profile_default.go b/internal/cmd/safety_profile_default.go index add9d018b..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 @@ -54,8 +57,17 @@ func bakedSafetyLockedFlagCount() int { return len(bakedSafetyTestProfile.lockedFlags) } -func bakedSafetyDeniedValues(path []string, flag string) []string { - return bakedSafetyTestProfile.deniedValues[strings.Join(path, ".")][flag] +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 { diff --git a/internal/cmd/safety_profile_test.go b/internal/cmd/safety_profile_test.go index 5be37adf6..d983fed15 100644 --- a/internal/cmd/safety_profile_test.go +++ b/internal/cmd/safety_profile_test.go @@ -70,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/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 +}