From 39a6aa966ad3151e65df660cc102416758c9e360 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 11:34:34 +0000 Subject: [PATCH 1/3] Waive named vulnerabilities and licenses, and edit the license gate The policy contract (safedep/api#265) adds the trust scopes LICENSE and NAMED_VULNERABILITY and the license gate of the scan gate. The CLI could not create these rules, did not show them, and treated a license list as a group of settings, so an edit dropped "deny: {licenses: []}". Bump the generated api SDK to the build of the merge, 20261107111754. `policy rule create --trust` takes --scope license. --scope vulnerability with one or more --vulnerability ID[:JUSTIFICATION] flags creates a rule with the one scope NAMED_VULNERABILITY and its waived ids. The suffix is the short OpenVEX name. An id can hold a ":", so the value splits at the last ":" only when the text after it is a justification name. The command refuses --vulnerability with another scope, with all or on a block, and refuses an id given twice. --scope all now adds LICENSE and never adds NAMED_VULNERABILITY, because that scope needs ids. The rule list and show views print the waived ids with their justifications in the table, plain and JSON forms. The policy document reads a message field with a merge option as one setting, as the contract says. scan_gate.licenses.deny is a path, a set list with no items stays an empty list through an edit, and an uncommented "deny:" alone sets nothing. The edit template shows the license gate as commented fields with notes on what a list, an empty list and unknown do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-edit.md | 17 +++ docs/cmd/policy-rule-create.md | 59 +++++++- docs/cmd/policy-rule-list.md | 14 +- docs/cmd/policy-rule-show.md | 8 ++ go.mod | 4 +- go.sum | 8 +- internal/cloudpolicy/fields.go | 76 +++++++++- internal/cloudpolicy/fields_test.go | 22 +++ internal/cloudpolicy/protoyaml.go | 13 +- internal/cloudpolicy/template.go | 31 +++- internal/cloudpolicy/template_test.go | 94 ++++++++++++ internal/cmd/policy/rule_create.go | 42 +++--- internal/cmd/policy/rule_filters.go | 23 ++- internal/cmd/policy/rule_input.go | 33 ++++- internal/cmd/policy/rule_list.go | 6 +- internal/cmd/policy/rule_show.go | 12 +- internal/cmd/policy/rule_test.go | 47 ++++-- internal/cmd/policy/rule_view.go | 103 ++++++++++--- internal/cmd/policy/rule_vulnerability.go | 127 ++++++++++++++++ .../cmd/policy/rule_vulnerability_test.go | 135 ++++++++++++++++++ 20 files changed, 788 insertions(+), 86 deletions(-) create mode 100644 internal/cmd/policy/rule_vulnerability.go create mode 100644 internal/cmd/policy/rule_vulnerability_test.go diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index 1c203d2..1a36b3b 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -61,6 +61,18 @@ The document of a tenant that has not published a policy yet: # scan_gate: # fail_on: high # critical, high, medium, low, info. Now: high (default policy, revision 1) # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1) + # licenses: + # The licenses that fail the gate. A list replaces the list below it. deny: {licenses: []} + # denies nothing. Values: {licenses: [text, ...]}. Now: not set, each tool uses its local + # value + # deny: + # With entries, a license outside the list fails the gate. A list replaces the list below it. + # An empty list turns the allow list off. Values: {licenses: [text, ...]}. Now: not set, each + # tool uses its local value + # allow: + # What the gate does on a package with an unknown license that the lists do not fail. Values: + # allow, report, fail. Now: not set, each tool uses its local value + # unknown: allow # base_description: Why the base has these values # text # An example policy override. It applies to the subjects that its selector matches. @@ -138,6 +150,11 @@ safedep policy edit --override payments - The command warns when the file holds a comment that it did not write. The policy keeps no comments. - A parent key that you uncomment with no field below it makes no change. +- A license list is one setting. `deny: {licenses: []}` sets a deny list with no + entries, so it denies nothing. `allow: {licenses: []}` turns off the allow list + of the layer below. A `deny:` or `allow:` line that you uncomment with nothing + below it makes no change. A list replaces the list of the layer below. No + layer merges two lists. - The command warns when an added or changed policy override selects on a `managed/`, `reported/` or `scm-property/` label. A tool sets such a label, so a person on the endpoint can change it. The save continues. diff --git a/docs/cmd/policy-rule-create.md b/docs/cmd/policy-rule-create.md index 1b71f19..76cc66c 100644 --- a/docs/cmd/policy-rule-create.md +++ b/docs/cmd/policy-rule-create.md @@ -11,6 +11,7 @@ verified malware. safedep policy rule create --block PURL [--vers RANGE] --reason TEXT [flags] safedep policy rule create --block -f FILE --reason TEXT [flags] safedep policy rule create --trust PURL --scope SCOPE --expires DURATION --reason TEXT [flags] +safedep policy rule create --trust PURL --scope vulnerability --vulnerability ID[:JUSTIFICATION]... --expires DURATION --reason TEXT [flags] ``` ## Flags @@ -21,7 +22,8 @@ safedep policy rule create --trust PURL --scope SCOPE --expires DURATION --reaso | `--trust` | Create a trust entry. | | `-f`, `--file ` | With `--block`: a file with one selector on each line, a PURL and an optional range after a space. `#` starts a comment. `-` reads stdin. At most 1,000 selectors, in one revision. | | `--vers ` | A version range, as `'>=1.2.0'` or `'vers:npm/>=1.2.0\|<2.0.0'`. A bare range gets the `vers:` prefix and the type of the PURL. | -| `--scope ` | With `--trust`: `malware`, `cooldown`, `vulnerability` or `all`. Repeatable. Required. | +| `--scope ` | With `--trust`: `malware`, `cooldown`, `vulnerability`, `license` or `all`. Repeatable. Required. | +| `--vulnerability [:]` | With `--scope vulnerability` as the only scope: waive only this vulnerability id, as `CVE-2024-3094`. Repeatable, at most 100 ids, each one time. See below. | | `--expires ` | A duration from now, as `30d`, or a date, as `2027-01-26`. Required with `--trust`, and at most 90 days from now for a trust entry. | | `--reason ` | Why the rule exists. Required. Tools show it in a block message. | | `--ticket ` | A ticket or incident reference, as `IR-2291`. | @@ -40,8 +42,39 @@ Selector rules, which the CLI checks before the request: - A prefix such as `pkg:npm/*` selects every package of an ecosystem. The command warns, because such a block stops every install of that ecosystem in the tenant. +Trust scopes: + +| Scope | Waives | +|-------|--------| +| `malware` | A malware verdict that is not verified. | +| `cooldown` | The dependency cooldown. | +| `vulnerability` | Every vulnerability finding of a scan gate, also one that is published later. With `--vulnerability`, only the named vulnerabilities. | +| `license` | Every license finding of a scan gate: a denied license, a license outside the allow list and an unknown license. | + `--scope all` expands to every trust scope that this CLI knows. The contract has no "all" value, so a scope that a later release adds never widens a stored entry. +`all` never waives named vulnerabilities, because that scope needs ids. + +`--scope vulnerability` with one or more `--vulnerability` flags creates a trust +entry with the one scope `named-vulnerability`. It waives only the vulnerabilities +that it names and their aliases, so a CVE id also waives the GHSA id of the same +vulnerability. A scan gate still fails on every other vulnerability of the +package. The command refuses `--vulnerability` with another scope or with `all`. + +Write the id as its advisory publishes it, as `CVE-2024-3094`, +`GHSA-jfh8-c2jp-5v3q` or `RHSA-2024:1234`. The optional justification says why +the vulnerability does not affect the package, with an OpenVEX name: + +- `component_not_present` +- `vulnerable_code_not_present` +- `vulnerable_code_not_in_execute_path` +- `vulnerable_code_cannot_be_controlled_by_adversary` +- `inline_mitigations_already_exist` + +An id can hold a `:`. The command splits the value at its last `:` only when the +text after it is a justification name. Otherwise the whole value is the id, so +`RHSA-2024:1234` is one id. Without a justification, `--reason` is the only +explanation. ## Examples @@ -75,6 +108,30 @@ Applies to every endpoint and project of the tenant (base). Use --override NAME The rule expires in 30d (2026-11-30) ``` +Waive two vulnerabilities of one version, the first with a justification: + +```bash +safedep policy rule create --trust pkg:npm/foo@1.2.3 --scope vulnerability \ + --vulnerability CVE-2024-1234:vulnerable_code_not_in_execute_path \ + --vulnerability GHSA-jfh8-c2jp-5v3q --reason "Not reachable, S-90" --expires 30d +``` + +``` +Applies to every endpoint and project of the tenant (base). Use --override NAME to narrow it. +! This rule loosens the policy: it waives the scan gate findings of CVE-2024-1234, GHSA-jfh8-c2jp-5v3q for pkg:npm/foo@1.2.3. +A scan gate still fails on every other vulnerability of the package. +! Verified malware stays blocked +✓ rule r_5d2 created · revision 50 published + The rule expires in 30d (2026-12-07) +``` + +Waive the license findings of one version: + +```bash +safedep policy rule create --trust pkg:npm/bar@2.0.0 --scope license \ + --reason "Legal approved the dual license, LEG-12" --expires 90d +``` + Block a list of packages in one revision: ```bash diff --git a/docs/cmd/policy-rule-list.md b/docs/cmd/policy-rule-list.md index ed3d2c5..ff3e496 100644 --- a/docs/cmd/policy-rule-list.md +++ b/docs/cmd/policy-rule-list.md @@ -15,7 +15,7 @@ safedep policy rule list [--effect trust|block] [--scope SCOPE] [--selector-pref | Flag | Description | |------|-------------| | `--effect ` | `trust` or `block`. | -| `--scope ` | Trust entries with this scope: `malware`, `cooldown` or `vulnerability`. | +| `--scope ` | Trust entries with this scope: `malware`, `cooldown`, `vulnerability`, `license` or `named-vulnerability`. | | `--selector-prefix ` | Rules whose selector starts with this text, as `pkg:npm/`. | | `--expiring ` | Rules that expire within this time from now, as `7d`. | | `--override ` | Rules that attach to this policy override. | @@ -42,10 +42,14 @@ r_80b pkg:npm/leftpad trust malware FP, S-71 web ## Output -`json` holds `rules` (rule id, purl, vers, effect, scopes, reason, ticket, -requester, override id, `attaches_to`, author, added, updated and removed revision, times) -and `next_page_token`. `plain` writes a tab-separated header and one row for each -rule. The table humanizes the expiry. +`json` holds `rules` (rule id, purl, vers, effect, scopes, `vulnerabilities`, reason, +ticket, requester, override id, `attaches_to`, author, added, updated and removed +revision, times) and `next_page_token`. `vulnerabilities` lists each waived `id` and +its `justification` for a trust entry with the scope `named-vulnerability`. `plain` +writes a tab-separated header and one row for each rule. Its last column, +`vulnerabilities`, has the form of the `--vulnerability` flag, as +`CVE-2024-1234:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q`. The table +shows the waived vulnerabilities after the scope, and humanizes the expiry. ## Authentication diff --git a/docs/cmd/policy-rule-show.md b/docs/cmd/policy-rule-show.md index 50fb5d8..20e9055 100644 --- a/docs/cmd/policy-rule-show.md +++ b/docs/cmd/policy-rule-show.md @@ -28,6 +28,14 @@ Created by carol Revisions added in revision 48 · active ``` +A trust entry that waives named vulnerabilities has a `Vulnerabilities` row +after `Scope`, with the justification of each id: + +``` +Scope named-vulnerability +Vulnerabilities CVE-2024-1234 (vulnerable_code_not_in_execute_path), GHSA-jfh8-c2jp-5v3q +``` + After an update of the rule, `Revisions` also names the revision of the last update, as `added in revision 48, updated in revision 52 · active`. diff --git a/go.mod b/go.mod index 3aef120..71fa4af 100644 --- a/go.mod +++ b/go.mod @@ -4,8 +4,8 @@ go 1.26.2 require ( buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1 - buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261106062459-79f98cf26185.1 - buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261106062459-79f98cf26185.2 + buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261107111754-29a1adb160aa.1 + buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261107111754-29a1adb160aa.2 github.com/charmbracelet/huh v1.0.0 github.com/charmbracelet/lipgloss v1.1.0 github.com/cli/browser v1.3.0 diff --git a/go.sum b/go.sum index 22a6bf3..3e27fb3 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,9 @@ buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1 h1:6nlcxMOui23ZRVAfJM451duu79P1npA5JRdZqMilrrQ= buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.12-20260709200747-435963d16310.1/go.mod h1:TCt1lluMFnctISJXvkIQ4x3ABrPuUKCWKyjKdkJNBpw= -buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261106062459-79f98cf26185.1 h1:S0e3r4qsk7fVC2kEP+WDvLG2s4MmuNWFOMZcsF0mc5s= -buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261106062459-79f98cf26185.1/go.mod h1:C0+UQn8fXxnhC1ifFxYYMFbXoxcS9wmInwIxbApfsx0= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261106062459-79f98cf26185.2 h1:gef9XLbPemfcQJ96qCb0CQPaAXUjX/Jo8iC80gaEOZ0= -buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261106062459-79f98cf26185.2/go.mod h1:LfbopTmazyAppwhYT2vdRDLDH8ZTm4QNbp9yFjGRbHs= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261107111754-29a1adb160aa.1 h1:4uXBhgLhLEn7IOW9avcfYIYKNOI77vOcYm9XQbvfRHo= +buf.build/gen/go/safedep/api/grpc/go v1.6.2-20261107111754-29a1adb160aa.1/go.mod h1:4i7HWcBq17WJ1/i+2RMe/hFwUloX8o4PaviS3I9gd5I= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261107111754-29a1adb160aa.2 h1:1VyJgN+9Z4T+dEVSffnJV/ETVLPsqKkYEvWHguZ/jzc= +buf.build/gen/go/safedep/api/protocolbuffers/go v1.36.12-20261107111754-29a1adb160aa.2/go.mod h1:LfbopTmazyAppwhYT2vdRDLDH8ZTm4QNbp9yFjGRbHs= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= diff --git a/internal/cloudpolicy/fields.go b/internal/cloudpolicy/fields.go index ca0b858..c412dc8 100644 --- a/internal/cloudpolicy/fields.go +++ b/internal/cloudpolicy/fields.go @@ -7,8 +7,10 @@ import ( "strings" "time" + optionsv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/options/v1" specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" "github.com/safedep/dry/tui/humanize" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" @@ -16,9 +18,15 @@ import ( "github.com/safedep/cli/internal/duration" ) -// coreCapability is the capability of the package rules. It is not a policy -// setting, so the field lists and the restore leave it out. -const coreCapability = "core" +const ( + // coreCapability is the capability of the package rules. It is not a + // policy setting, so the field lists and the restore leave it out. + coreCapability = "core" + + // emptyList is the value of a list setting that a layer sets to no + // items. It differs from a setting that the layer does not set. + emptyList = "[]" +) // FieldValue is one set field of a PolicySpec. type FieldValue struct { @@ -134,11 +142,39 @@ func isLeaf(fd protoreflect.FieldDescriptor) bool { if fd.Kind() != protoreflect.MessageKind || fd.IsList() || fd.IsMap() { return true } - return isFormattedMessage(fd.Message()) + return isFormattedMessage(fd.Message()) || isListSetting(fd) +} + +// isListSetting reports a message field that the contract marks as one +// setting with a merge option, such as scan_gate.licenses.deny. The message +// wraps one list, so a layer can set the list to no items. Its path is the +// path of the field, and a set wrapper with no items is an empty list, not +// "not set". +func isListSetting(fd protoreflect.FieldDescriptor) bool { + if fd.Kind() != protoreflect.MessageKind || fd.IsList() || fd.IsMap() || isFormattedMessage(fd.Message()) { + return false + } + contract, ok := proto.GetExtension(fd.Options(), optionsv1.E_Field).(*optionsv1.FieldContract) + return ok && contract.GetMerge() != optionsv1.Merge_MERGE_UNSPECIFIED && wrappedList(fd.Message()) != nil +} + +// wrappedList is the one repeated field of a list setting, or nil. +func wrappedList(md protoreflect.MessageDescriptor) protoreflect.FieldDescriptor { + if md.Fields().Len() != 1 || !md.Fields().Get(0).IsList() { + return nil + } + return md.Fields().Get(0) } func formatFieldValue(fd protoreflect.FieldDescriptor, v protoreflect.Value) (string, string) { switch { + case isListSetting(fd): + inner := wrappedList(fd.Message()) + items := v.Message().Get(inner) + if items.List().Len() == 0 { + return emptyList, emptyList + } + return formatFieldValue(inner, items) case fd.IsList(): list := v.List() values := make([]string, 0, list.Len()) @@ -224,6 +260,15 @@ func FormatJSONValue(path, raw string) (string, string) { return duration.Format(d), humanDuration(d) } return text, text + case fd != nil && isListSetting(fd): + if items, ok := jsonListItems(value, wrappedList(fd.Message())); ok { + return items, items + } + compact, err := json.Marshal(value) + if err != nil { + return raw, raw + } + return string(compact), string(compact) case isString: return text, text default: @@ -235,6 +280,29 @@ func FormatJSONValue(path, raw string) (string, string) { } } +// jsonListItems reads the items of a list setting from its JSON value: the +// protojson of the wrapper, as {"licenses": ["MIT"]}, or the list itself. +func jsonListItems(value any, inner protoreflect.FieldDescriptor) (string, bool) { + if wrapper, ok := value.(map[string]any); ok { + value, ok = wrapper[inner.JSONName()] + if !ok { + value = []any{} + } + } + list, ok := value.([]any) + if !ok { + return "", false + } + if len(list) == 0 { + return emptyList, true + } + items := make([]string, 0, len(list)) + for _, item := range list { + items = append(items, fmt.Sprint(item)) + } + return strings.Join(items, ", "), true +} + func fieldByPath(path string) protoreflect.FieldDescriptor { md := (&specv1.PolicySpec{}).ProtoReflect().Descriptor() var fd protoreflect.FieldDescriptor diff --git a/internal/cloudpolicy/fields_test.go b/internal/cloudpolicy/fields_test.go index 0178b86..317f0f9 100644 --- a/internal/cloudpolicy/fields_test.go +++ b/internal/cloudpolicy/fields_test.go @@ -18,11 +18,30 @@ func TestFields(t *testing.T) { assert.Empty(t, Fields(nil)) } +func TestFields_ListSettings(t *testing.T) { + licenses := &scangatev1.LicenseGate{} + deny := &scangatev1.LicenseList{} + deny.SetLicenses([]string{"GPL-3.0-only", "AGPL-3.0-only"}) + licenses.SetDeny(deny) + licenses.SetAllow(&scangatev1.LicenseList{}) + spec := specWith(scangatev1.Severity_SEVERITY_HIGH, 0) + spec.GetScanGate().SetLicenses(licenses) + + assert.Equal(t, []FieldValue{ + {Path: "scan_gate.fail_on", Value: "high", Human: "high"}, + {Path: "scan_gate.licenses.deny", Value: "GPL-3.0-only, AGPL-3.0-only", Human: "GPL-3.0-only, AGPL-3.0-only"}, + {Path: "scan_gate.licenses.allow", Value: "[]", Human: "[]"}, + }, Fields(spec)) +} + func TestLeafPathsAndCapabilities(t *testing.T) { paths := LeafPaths() assert.Contains(t, paths, "scan_gate.fail_on") assert.Contains(t, paths, "scan_gate.fail_on_attacks") assert.Contains(t, paths, "package_admission.cooldown.min_age") + assert.Contains(t, paths, "scan_gate.licenses.deny", "a list setting is one setting") + assert.Contains(t, paths, "scan_gate.licenses.unknown") + assert.NotContains(t, paths, "scan_gate.licenses.deny.licenses") for _, p := range paths { assert.NotContains(t, p, "core", "package rules are not settings") } @@ -54,6 +73,9 @@ func TestFormatJSONValue(t *testing.T) { {"package_admission.cooldown.min_age", `"604800s"`, "168h", "7d"}, {"package_admission.cooldown.min_age", `"0s"`, "0s", "0s"}, {"scan_gate.fail_on", "", "-", "-"}, + {"scan_gate.licenses.deny", `{"licenses":["GPL-3.0-only","MIT"]}`, "GPL-3.0-only, MIT", "GPL-3.0-only, MIT"}, + {"scan_gate.licenses.deny", `{}`, "[]", "[]"}, + {"scan_gate.licenses.allow", `["MIT"]`, "MIT", "MIT"}, {"unknown.path", `"text"`, "text", "text"}, {"unknown.path", `{"a":1}`, `{"a":1}`, `{"a":1}`}, {"unknown.path", `not json`, "not json", "not json"}, diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index cde6bb0..0e5b786 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -111,6 +111,13 @@ func (c *yamlCodec) encodeField(fd protoreflect.FieldDescriptor, v protoreflect. out.Content = append(out.Content, scalarNode(k.String()), c.encodeSingular(fd.MapValue(), entries.Get(k))) } return out + case isListSetting(fd): + // The wrapper keeps its list key also with no items, so a layer + // that sets an empty list writes "licenses: []" and not "{}". + inner := wrappedList(fd.Message()) + out := &yaml.Node{Kind: yaml.MappingNode} + out.Content = append(out.Content, scalarNode(c.key(inner)), c.encodeField(inner, v.Message().Get(inner))) + return out default: return c.encodeSingular(fd, v) } @@ -308,8 +315,10 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str // "key:" with only commented lines below sets a message with no // fields, so the edit template of a set but empty spec round // trips. A label selector stays unset, because an empty selector - // selects every subject. - if !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && !isFormattedMessage(fd.Message()) { + // selects every subject. A list setting stays unset too, because + // a set wrapper with no items is an empty list: an uncommented + // "deny:" alone must not remove every license from a deny list. + if !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && !isFormattedMessage(fd.Message()) && !isListSetting(fd) { m.Mutable(fd) } continue diff --git a/internal/cloudpolicy/template.go b/internal/cloudpolicy/template.go index d399308..86670c2 100644 --- a/internal/cloudpolicy/template.go +++ b/internal/cloudpolicy/template.go @@ -9,6 +9,7 @@ import ( validate "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" packageadmissionv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/packageadmission/v1" + scangatev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/scangate/v1" specv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/spec/v1" policyv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/policy/v1" yaml "go.yaml.in/yaml/v3" @@ -45,6 +46,20 @@ var ( // values of the base. The template shows it commented when it is unset, // because the header asks for the reason in a description field. baseDescriptionFullName = policyFullName.Append("base_description") + + licenseGateFullName = (&scangatev1.LicenseGate{}).ProtoReflect().Descriptor().FullName() + + // fieldNotes give the meaning of a field whose value form alone misleads + // a person. An empty license list is a value, and the gate reads the + // lists before unknown. + fieldNotes = map[protoreflect.FullName]string{ + licenseGateFullName.Append("deny"): "The licenses that fail the gate. A list replaces the list below it. " + + "deny: {licenses: []} denies nothing.", + licenseGateFullName.Append("allow"): "With entries, a license outside the list fails the gate. " + + "A list replaces the list below it. An empty list turns the allow list off.", + licenseGateFullName.Append("unknown"): "What the gate does on a package with an unknown license " + + "that the lists do not fail.", + } ) // DefaultLayer is the SafeDep default policy, the layer below the base. @@ -312,7 +327,11 @@ func (w *templateWriter) commentedLeaf( return err } } - text := tui.EscapeLine(valueForm(fd) + ". " + now) + text := valueForm(fd) + ". " + now + if note, ok := fieldNotes[fd.FullName()]; ok { + text = note + " Values: " + text + } + text = tui.EscapeLine(text) first := strings.Repeat(" ", indent) + "# " + lines[0] if len(first)+len(" # ")+len(text) <= templateWidth { w.lines = append(w.lines, first+" # "+text) @@ -509,6 +528,9 @@ func placeholderValue(fd protoreflect.FieldDescriptor) (protoreflect.Value, bool // valueForm describes the values that a field accepts, in the words of the // codec. func valueForm(fd protoreflect.FieldDescriptor) string { + if isListSetting(fd) { + return "{" + documentCodec.key(wrappedList(fd.Message())) + ": [text, ...]}" + } form := singularForm(fd) switch { case fd.IsList(): @@ -597,8 +619,9 @@ func valueAtPath(spec *specv1.PolicySpec, path string) (protoreflect.Value, bool } // PruneEmpty returns a copy of m with every message field that holds no -// field cleared, at every level. A label selector, a duration and a time -// stay, because their empty value means something: every subject, or zero. +// field cleared, at every level. A label selector, a duration, a time and a +// list setting stay, because their empty value means something: every +// subject, zero, or a list with no items. // An edit compares pruned messages, so a parent key that a person uncomments // with no field below it is no change. func PruneEmpty(m proto.Message) proto.Message { @@ -611,7 +634,7 @@ func pruneMessage(m protoreflect.Message) { var empty []protoreflect.FieldDescriptor m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { switch { - case !isMessageKind(fd) || fd.IsMap(): + case !isMessageKind(fd) || fd.IsMap() || isListSetting(fd): case fd.IsList(): list := v.List() for i := 0; i < list.Len(); i++ { diff --git a/internal/cloudpolicy/template_test.go b/internal/cloudpolicy/template_test.go index f1a860e..d8dced0 100644 --- a/internal/cloudpolicy/template_test.go +++ b/internal/cloudpolicy/template_test.go @@ -36,6 +36,18 @@ func TestMarshalPolicyTemplate_NewTenant(t *testing.T) { # scan_gate: # fail_on: high # critical, high, medium, low, info. Now: high (default policy, revision 1) # fail_on_attacks: fail # report, fail. Now: fail (default policy, revision 1) + # licenses: + # The licenses that fail the gate. A list replaces the list below it. deny: {licenses: []} + # denies nothing. Values: {licenses: [text, ...]}. Now: not set, each tool uses its local + # value + # deny: + # With entries, a license outside the list fails the gate. A list replaces the list below it. + # An empty list turns the allow list off. Values: {licenses: [text, ...]}. Now: not set, each + # tool uses its local value + # allow: + # What the gate does on a package with an unknown license that the lists do not fail. Values: + # allow, report, fail. Now: not set, each tool uses its local value + # unknown: allow # base_description: Why the base has these values # text # An example policy override. It applies to the subjects that its selector matches. @@ -295,3 +307,85 @@ func TestPruneEmpty(t *testing.T) { }) } } + +// licenseList builds a list setting. With no licenses it is set and empty. +func licenseList(licenses ...string) *scangatev1.LicenseList { + l := &scangatev1.LicenseList{} + l.SetLicenses(licenses) + return l +} + +func specWithLicenses(deny, allow *scangatev1.LicenseList, unknown scangatev1.UnknownLicenseGate) *specv1.PolicySpec { + licenses := &scangatev1.LicenseGate{} + if deny != nil { + licenses.SetDeny(deny) + } + if allow != nil { + licenses.SetAllow(allow) + } + if unknown != scangatev1.UnknownLicenseGate_UNKNOWN_LICENSE_GATE_UNSPECIFIED { + licenses.SetUnknown(unknown) + } + gate := &scangatev1.ScanGate{} + gate.SetLicenses(licenses) + spec := &specv1.PolicySpec{} + spec.SetScanGate(gate) + return spec +} + +func TestMarshalPolicyTemplate_LicenseGateOfTheDefaultPolicy(t *testing.T) { + def := DefaultLayer{ + Revision: 2, + Spec: specWithLicenses(licenseList("GPL-2.0-only", "GPL-3.0-only"), nil, + scangatev1.UnknownLicenseGate_UNKNOWN_LICENSE_GATE_ALLOW), + } + b, err := MarshalPolicyTemplate(&policyv1.Policy{}, "", def) + require.NoError(t, err) + text := string(b) + + assert.Contains(t, text, "Now: GPL-2.0-only, GPL-3.0-only (default\n # policy, revision 2)\n"+ + " # deny:\n"+ + " # licenses:\n"+ + " # - GPL-2.0-only\n"+ + " # - GPL-3.0-only\n") + assert.Contains(t, text, "Values: {licenses: [text, ...]}. Now: not set, each\n # tool uses its local value\n # allow:\n") + assert.Contains(t, text, "allow, report, fail. Now: allow (default policy, revision 2)\n # unknown: allow\n") + for _, line := range strings.Split(text, "\n") { + assert.LessOrEqual(t, len(line), templateWidth, line) + } +} + +func TestMarshalPolicyTemplate_LicenseListsRoundTrip(t *testing.T) { + tests := []struct { + name string + spec *specv1.PolicySpec + want string + }{ + {"an empty deny list denies nothing", specWithLicenses(licenseList(), nil, 0), " deny:\n licenses: []\n"}, + {"an empty allow list turns the allow list off", specWithLicenses(nil, licenseList(), 0), " allow:\n licenses: []\n"}, + {"lists with entries", specWithLicenses(licenseList("AGPL-3.0-only"), licenseList("MIT", "Apache-2.0"), + scangatev1.UnknownLicenseGate_UNKNOWN_LICENSE_GATE_FAIL), + " deny:\n licenses:\n - AGPL-3.0-only\n allow:\n licenses:\n - MIT\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := &policyv1.Policy{} + p.SetBase(tt.spec) + b, err := MarshalPolicyTemplate(p, "", defaultPolicy()) + require.NoError(t, err) + assert.Contains(t, string(b), tt.want) + + got, err := UnmarshalPolicy(b) + require.NoError(t, err) + assert.True(t, proto.Equal(p, got), "got %v\n%s", got, b) + assert.True(t, proto.Equal(p, PruneEmpty(got)), "a set list with no items is a value") + }) + } +} + +func TestUnmarshalPolicy_AnUncommentedListKeyAloneSetsNothing(t *testing.T) { + got, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n deny:\n")) + require.NoError(t, err) + assert.False(t, got.GetBase().GetScanGate().GetLicenses().HasDeny(), "deny: alone must not empty the deny list") + assert.False(t, PruneEmpty(got).(*policyv1.Policy).HasBase()) +} diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go index 54d2faa..a94ee7c 100644 --- a/internal/cmd/policy/rule_create.go +++ b/internal/cmd/policy/rule_create.go @@ -23,18 +23,19 @@ const ( ) type ruleCreateInput struct { - Block bool - Trust bool - Selector string - File string - Vers string - Scopes []string - Reason string - Ticket string - RequestedBy string - Expires string - Override string - Message string + Block bool + Trust bool + Selector string + File string + Vers string + Scopes []string + Vulnerabilities []string + Reason string + Ticket string + RequestedBy string + Expires string + Override string + Message string } type ruleCreateResult struct { @@ -53,6 +54,8 @@ func ruleCreateCmd(a *app.App) *cobra.Command { "revision: one PURL on each line, with an optional vers range after a space. A trust entry " + "selects one package and waives the verdicts of its --scope. It needs --expires. It never " + "waives verified malware. --scope all expands to every trust scope that this CLI knows. " + + "--scope vulnerability with --vulnerability ID[:JUSTIFICATION] waives only the named " + + "vulnerabilities, and every other vulnerability of the package still fails a scan gate. " + "A rule attaches to the policy base unless you pass --override NAME.", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.MaximumNArgs(1)(cmd, args); err != nil { @@ -80,7 +83,10 @@ func ruleCreateCmd(a *app.App) *cobra.Command { f.StringVarP(&in.File, "file", "f", "", "with --block: a file of selectors, one on each line, or - for stdin") f.StringVar(&in.Vers, "vers", "", "a version range, as in '>=1.2.0' or 'vers:npm/>=1.2.0|<2.0.0'") f.StringSliceVar(&in.Scopes, "scope", nil, - "with --trust: a verdict to waive, one of "+strings.Join(trustScopeTokens(), ", ")+", or all (repeatable)") + "with --trust: a verdict to waive, one of "+strings.Join(createScopeTokens(), ", ")+", or all (repeatable)") + f.StringArrayVar(&in.Vulnerabilities, "vulnerability", nil, + "with --scope vulnerability: waive only this id, as CVE-2024-3094, with an optional :JUSTIFICATION, one of "+ + strings.Join(justificationNames(), ", ")+" (repeatable)") f.StringVar(&in.Reason, "reason", "", "why the rule exists, which tools show in a block message (required)") f.StringVar(&in.Ticket, "ticket", "", "a ticket or incident reference, as in IR-2291") f.StringVar(&in.RequestedBy, "requested-by", "", "the team or person that asked for the rule") @@ -165,9 +171,13 @@ func announceRuleCreate(in ruleCreateInput, creates []*policyv1.PackageRuleCreat tui.Info("A block stops new installs. It does not remove installed copies.") return } - purl := creates[0].GetRule().GetSelector().GetPurl() - for _, scope := range creates[0].GetRule().GetScopes() { - tui.Warning("This rule loosens the policy: it waives %s for %s.", scopeEffect(scope), clitui.EscapeLine(purl)) + rule := creates[0].GetRule() + purl := rule.GetSelector().GetPurl() + for _, scope := range rule.GetScopes() { + tui.Warning("This rule loosens the policy: it waives %s for %s.", scopeEffect(rule, scope), clitui.EscapeLine(purl)) + } + if len(rule.GetVulnerabilities()) > 0 { + tui.Info("A scan gate still fails on every other vulnerability of the package.") } tui.Warning("Verified malware stays blocked") } diff --git a/internal/cmd/policy/rule_filters.go b/internal/cmd/policy/rule_filters.go index d234446..753fdb4 100644 --- a/internal/cmd/policy/rule_filters.go +++ b/internal/cmd/policy/rule_filters.go @@ -2,6 +2,7 @@ package policy import ( "fmt" + "slices" "strings" corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" @@ -15,6 +16,14 @@ func trustScopeTokens() []string { return tui.EnumTokens(corev1.TrustScope_name, trustScopePrefix) } +// createScopeTokens are the values of --scope in a create. A trust entry +// gets NAMED_VULNERABILITY from --scope vulnerability with --vulnerability, +// because that scope needs ids. So "all" leaves it out too. +func createScopeTokens() []string { + named := tui.EnumToken(corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY.String(), trustScopePrefix) + return slices.DeleteFunc(trustScopeTokens(), func(token string) bool { return token == named }) +} + func parseEffect(token string) (corev1.Effect, error) { n, ok := tui.ParseEnumToken(corev1.Effect_name, effectPrefix, token) if !ok { @@ -24,12 +33,14 @@ func parseEffect(token string) (corev1.Effect, error) { return corev1.Effect(n), nil } -func parseTrustScope(token string) (corev1.TrustScope, error) { - n, ok := tui.ParseEnumToken(corev1.TrustScope_name, trustScopePrefix, strings.ToLower(strings.TrimSpace(token))) - if !ok { +// parseTrustScope reads one of the allowed tokens. +func parseTrustScope(token string, allowed []string) (corev1.TrustScope, error) { + normalized := strings.ToLower(strings.TrimSpace(token)) + n, ok := tui.ParseEnumToken(corev1.TrustScope_name, trustScopePrefix, normalized) + if !ok || !slices.Contains(allowed, normalized) { return 0, invalidInputError( - fmt.Errorf("unknown trust scope %q: allowed values are %s", token, strings.Join(trustScopeTokens(), ", ")), - "Retry with one of: "+strings.Join(trustScopeTokens(), ", ")) + fmt.Errorf("unknown trust scope %q: allowed values are %s", token, strings.Join(allowed, ", ")), + "Retry with one of: "+strings.Join(allowed, ", ")) } return corev1.TrustScope(n), nil } @@ -51,7 +62,7 @@ func ruleListFilters(in *ruleListInput, overrideID string) (*policyv1.ListPackag set = true } if in.Scope != "" { - scope, err := parseTrustScope(in.Scope) + scope, err := parseTrustScope(in.Scope, trustScopeTokens()) if err != nil { return nil, err } diff --git a/internal/cmd/policy/rule_input.go b/internal/cmd/policy/rule_input.go index 2e1f9f5..08b8daa 100644 --- a/internal/cmd/policy/rule_input.go +++ b/internal/cmd/policy/rule_input.go @@ -65,16 +65,36 @@ func validateRuleCreate(in ruleCreateInput) error { return invalidInputError(errors.New("--reason is required"), "Say why the rule exists, as in --reason \"IR-2291 credential stealer\"") case in.Trust && len(in.Scopes) == 0: return invalidInputError(errors.New("a trust entry needs --scope"), - "Name each verdict that it waives: --scope "+strings.Join(trustScopeTokens(), ", --scope ")+", or --scope all") + "Name each verdict that it waives: --scope "+strings.Join(createScopeTokens(), ", --scope ")+", or --scope all") case in.Trust && in.Expires == "": return invalidInputError(errors.New("a trust entry needs --expires"), "As in --expires 30d") case in.Block && len(in.Scopes) > 0: return invalidInputError(errors.New("a block entry has no scope"), "Remove --scope") + case in.Block && len(in.Vulnerabilities) > 0: + return invalidInputError(errors.New("a block entry waives no vulnerability"), "Remove --vulnerability") } - _, err := expandScopes(in.Scopes) + _, _, err := ruleScopes(in) return err } +// ruleScopes gives the scopes of the rule and the vulnerabilities that it +// waives. --scope vulnerability with --vulnerability gives the one scope +// NAMED_VULNERABILITY. Without --vulnerability it waives every vulnerability. +func ruleScopes(in ruleCreateInput) ([]corev1.TrustScope, []*corev1.WaivedVulnerability, error) { + scopes, err := expandScopes(in.Scopes) + if err != nil || len(in.Vulnerabilities) == 0 { + return scopes, nil, err + } + if err := checkWaivedScope(scopes); err != nil { + return nil, nil, err + } + waived, err := parseWaivedVulnerabilities(in.Vulnerabilities) + if err != nil { + return nil, nil, err + } + return []corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY}, waived, nil +} + // expandScopes reads the --scope values. "all" expands to every trust scope // that this SDK knows, because the contract has no "all" value: a scope that // a later release adds never widens a stored entry. @@ -83,8 +103,8 @@ func expandScopes(values []string) ([]corev1.TrustScope, error) { for _, v := range values { if strings.EqualFold(strings.TrimSpace(v), scopeAll) { out = out[:0] - for _, token := range trustScopeTokens() { - scope, err := parseTrustScope(token) + for _, token := range createScopeTokens() { + scope, err := parseTrustScope(token, createScopeTokens()) if err != nil { return nil, err } @@ -92,7 +112,7 @@ func expandScopes(values []string) ([]corev1.TrustScope, error) { } return out, nil } - scope, err := parseTrustScope(v) + scope, err := parseTrustScope(v, createScopeTokens()) if err != nil { return nil, err } @@ -113,7 +133,7 @@ func buildRuleCreates(in ruleCreateInput, stdin io.Reader, now time.Time) ([]*po if in.Trust { effect = corev1.Effect_EFFECT_TRUST } - scopes, err := expandScopes(in.Scopes) + scopes, waived, err := ruleScopes(in) if err != nil { return nil, err } @@ -152,6 +172,7 @@ func buildRuleCreates(in ruleCreateInput, stdin io.Reader, now time.Time) ([]*po rule.SetSelector(selector) rule.SetEffect(effect) rule.SetScopes(scopes) + rule.SetVulnerabilities(waived) rule.SetReason(in.Reason) if expires != nil { rule.SetExpiresAt(expires) diff --git a/internal/cmd/policy/rule_list.go b/internal/cmd/policy/rule_list.go index 546584f..99297b0 100644 --- a/internal/cmd/policy/rule_list.go +++ b/internal/cmd/policy/rule_list.go @@ -161,7 +161,7 @@ func (r *ruleListResult) RenderTable() string { rows := make([][]string, 0, len(r.Rules)) for _, rule := range r.Rules { rows = append(rows, []string{ - rule.ID, rule.selector(), rule.Effect, cloudpolicy.EmptyDash(strings.Join(rule.Scopes, ",")), + rule.ID, rule.selector(), rule.Effect, rule.scopeText(), rule.Reason, cloudpolicy.EmptyDash(rule.RequestedBy), rule.AttachesTo, rule.expiresCell(now), }) } @@ -182,10 +182,10 @@ func (r *ruleListResult) RenderTable() string { func (r *ruleListResult) RenderPlain() string { var b strings.Builder - b.WriteString("rule_id\tpurl\tvers\teffect\tscopes\treason\trequested_by\toverride_id\texpires_at") + b.WriteString("rule_id\tpurl\tvers\teffect\tscopes\treason\trequested_by\toverride_id\texpires_at\tvulnerabilities") for _, rule := range r.Rules { b.WriteString("\n" + tui.PlainRow(rule.ID, rule.Purl, rule.Vers, rule.Effect, strings.Join(rule.Scopes, ","), - rule.Reason, rule.RequestedBy, rule.OverrideID, rule.ExpiresAt)) + rule.Reason, rule.RequestedBy, rule.OverrideID, rule.ExpiresAt, rule.waivedPlain())) } return b.String() } diff --git a/internal/cmd/policy/rule_show.go b/internal/cmd/policy/rule_show.go index 366a186..658131d 100644 --- a/internal/cmd/policy/rule_show.go +++ b/internal/cmd/policy/rule_show.go @@ -24,7 +24,7 @@ func ruleShowCmd(a *app.App) *cobra.Command { return &cobra.Command{ Use: "show RULE", Short: "Show one package rule", - Long: "Show one package rule: its selector, effect, trust scopes, reason, ticket, requester, the " + + Long: "Show one package rule: its selector, effect, trust scopes, the vulnerabilities that it waives, reason, ticket, requester, the " + "policy override that it attaches to, its expiry, and the revisions that added, updated and removed it. " + "A block message of a tool cites the rule id.", Args: cobra.ExactArgs(1), @@ -78,11 +78,16 @@ func (r *ruleShowResult) table(now time.Time) string { if v.expires != nil { expires = expiryText(*v.expires, now) } - return cloudpolicy.KeyValues([][2]string{ + rows := [][2]string{ {"Rule", v.ID}, {"Selector", v.selector()}, {"Effect", v.Effect}, {"Scope", cloudpolicy.EmptyDash(strings.Join(v.Scopes, ", "))}, + } + if len(v.Vulnerabilities) > 0 { + rows = append(rows, [2]string{"Vulnerabilities", v.waivedText()}) + } + return cloudpolicy.KeyValues(append(rows, [][2]string{ {"Reason", v.Reason}, {"Ticket", cloudpolicy.EmptyDash(v.Ticket)}, {"Requested by", cloudpolicy.EmptyDash(v.RequestedBy)}, @@ -90,7 +95,7 @@ func (r *ruleShowResult) table(now time.Time) string { {"Expires", expires}, {"Created by", cloudpolicy.EmptyDash(v.CreatedBy)}, {"Revisions", v.revisions() + sep + removed}, - }) + }...)) } // The server sends updated_revision 0 when no update changed the rule. An @@ -112,6 +117,7 @@ func (r *ruleShowResult) RenderPlain() string { clitui.PlainRow("vers", v.Vers), clitui.PlainRow("effect", v.Effect), clitui.PlainRow("scopes", strings.Join(v.Scopes, ",")), + clitui.PlainRow("vulnerabilities", v.waivedPlain()), clitui.PlainRow("reason", v.Reason), clitui.PlainRow("ticket", v.Ticket), clitui.PlainRow("requested_by", v.RequestedBy), diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go index 16b6582..6f8c6ba 100644 --- a/internal/cmd/policy/rule_test.go +++ b/internal/cmd/policy/rule_test.go @@ -45,7 +45,28 @@ func TestValidateRuleCreate(t *testing.T) { {"trust without scope", func(in *ruleCreateInput) { in.Scopes = nil }, trust, "a trust entry needs --scope"}, {"trust without expiry", func(in *ruleCreateInput) { in.Expires = "" }, trust, "a trust entry needs --expires"}, {"block with scope", func(in *ruleCreateInput) { in.Scopes = []string{"malware"} }, block, "a block entry has no scope"}, - {"unknown scope", func(in *ruleCreateInput) { in.Scopes = []string{"license"} }, trust, `unknown trust scope "license"`}, + {"unknown scope", func(in *ruleCreateInput) { in.Scopes = []string{"secrets"} }, trust, `unknown trust scope "secrets"`}, + {"license", func(in *ruleCreateInput) { in.Scopes = []string{"license"} }, trust, ""}, + {"named vulnerability needs ids", func(in *ruleCreateInput) { in.Scopes = []string{"named-vulnerability"} }, trust, + `unknown trust scope "named-vulnerability": allowed values are malware, cooldown, vulnerability, license`}, + {"waived vulnerabilities", func(in *ruleCreateInput) { + in.Scopes, in.Vulnerabilities = []string{"vulnerability"}, []string{"CVE-2024-1234", "GHSA-jfh8-c2jp-5v3q"} + }, trust, ""}, + {"waived vulnerabilities with another scope", func(in *ruleCreateInput) { + in.Scopes, in.Vulnerabilities = []string{"malware"}, []string{"CVE-2024-1234"} + }, trust, "--vulnerability needs --scope vulnerability"}, + {"waived vulnerabilities with a second scope", func(in *ruleCreateInput) { + in.Scopes, in.Vulnerabilities = []string{"vulnerability", "license"}, []string{"CVE-2024-1234"} + }, trust, "--vulnerability needs --scope vulnerability as the only scope"}, + {"waived vulnerabilities with all", func(in *ruleCreateInput) { + in.Scopes, in.Vulnerabilities = []string{"all"}, []string{"CVE-2024-1234"} + }, trust, "--vulnerability needs --scope vulnerability as the only scope"}, + {"waived vulnerabilities on a block", func(in *ruleCreateInput) { in.Vulnerabilities = []string{"CVE-2024-1234"} }, block, + "a block entry waives no vulnerability"}, + {"a waived vulnerability twice", func(in *ruleCreateInput) { + in.Scopes = []string{"vulnerability"} + in.Vulnerabilities = []string{"CVE-2024-1234", "CVE-2024-1234:component_not_present"} + }, trust, "--vulnerability CVE-2024-1234 is given more than once"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -61,14 +82,20 @@ func TestValidateRuleCreate(t *testing.T) { } } +// allScopes is what --scope all expands to. It leaves out +// NAMED_VULNERABILITY, because that scope needs vulnerability ids. +var allScopes = []corev1.TrustScope{ + corev1.TrustScope_TRUST_SCOPE_MALWARE, + corev1.TrustScope_TRUST_SCOPE_COOLDOWN, + corev1.TrustScope_TRUST_SCOPE_VULNERABILITY, + corev1.TrustScope_TRUST_SCOPE_LICENSE, +} + func TestExpandScopes_AllIsEveryKnownScope(t *testing.T) { all, err := expandScopes([]string{"all"}) require.NoError(t, err) - assert.Equal(t, []corev1.TrustScope{ - corev1.TrustScope_TRUST_SCOPE_MALWARE, - corev1.TrustScope_TRUST_SCOPE_COOLDOWN, - corev1.TrustScope_TRUST_SCOPE_VULNERABILITY, - }, all) + assert.Equal(t, allScopes, all) + assert.NotContains(t, all, corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY) for _, s := range all { assert.NotEqual(t, corev1.TrustScope_TRUST_SCOPE_UNSPECIFIED, s) } @@ -386,11 +413,7 @@ func TestExpandScopes_AllMixedWithANamedScope(t *testing.T) { for _, in := range [][]string{{"malware", "all"}, {"all", "cooldown"}, {"ALL"}} { got, err := expandScopes(in) require.NoError(t, err) - assert.Equal(t, []corev1.TrustScope{ - corev1.TrustScope_TRUST_SCOPE_MALWARE, - corev1.TrustScope_TRUST_SCOPE_COOLDOWN, - corev1.TrustScope_TRUST_SCOPE_VULNERABILITY, - }, got, "%v", in) + assert.Equal(t, allScopes, got, "%v", in) } } @@ -455,7 +478,7 @@ func TestRuleList_RenderPlainEscapesServerText(t *testing.T) { assert.Contains(t, plain, `IR-1\x1b[2J\tsecond column?`) lines := strings.Split(plain, "\n") require.Len(t, lines, 2) - assert.Len(t, strings.Split(lines[1], "\t"), 9, "a tab in a value adds no column") + assert.Len(t, strings.Split(lines[1], "\t"), 10, "a tab in a value adds no column") assert.NotContains(t, res.RenderTable(), "\x1b") } diff --git a/internal/cmd/policy/rule_view.go b/internal/cmd/policy/rule_view.go index 6d70857..0eb323c 100644 --- a/internal/cmd/policy/rule_view.go +++ b/internal/cmd/policy/rule_view.go @@ -2,6 +2,7 @@ package policy import ( "fmt" + "strings" "time" corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" @@ -16,23 +17,24 @@ import ( // `rule create` print. type ruleView struct { - ID string `json:"rule_id"` - Purl string `json:"purl"` - Vers string `json:"vers,omitempty"` - Effect string `json:"effect"` - Scopes []string `json:"scopes"` - Reason string `json:"reason"` - Ticket string `json:"ticket,omitempty"` - RequestedBy string `json:"requested_by,omitempty"` - OverrideID string `json:"override_id,omitempty"` - AttachesTo string `json:"attaches_to"` - CreatedBy string `json:"created_by,omitempty"` - AddedRevision uint64 `json:"added_revision"` - UpdatedRevision uint64 `json:"updated_revision,omitempty"` - RemovedRevision uint64 `json:"removed_revision,omitempty"` - ExpiresAt string `json:"expires_at,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` + ID string `json:"rule_id"` + Purl string `json:"purl"` + Vers string `json:"vers,omitempty"` + Effect string `json:"effect"` + Scopes []string `json:"scopes"` + Vulnerabilities []waivedVulnerabilityView `json:"vulnerabilities,omitempty"` + Reason string `json:"reason"` + Ticket string `json:"ticket,omitempty"` + RequestedBy string `json:"requested_by,omitempty"` + OverrideID string `json:"override_id,omitempty"` + AttachesTo string `json:"attaches_to"` + CreatedBy string `json:"created_by,omitempty"` + AddedRevision uint64 `json:"added_revision"` + UpdatedRevision uint64 `json:"updated_revision,omitempty"` + RemovedRevision uint64 `json:"removed_revision,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` expires *time.Time } @@ -47,6 +49,7 @@ func newRuleView(r *policyv1.PackageRuleWithAttributes, names map[string]string) Vers: rule.GetSelector().GetVers(), Effect: tui.EnumToken(rule.GetEffect().String(), effectPrefix), Scopes: scopeTokens(rule.GetScopes()), + Vulnerabilities: waivedViews(rule.GetVulnerabilities()), Reason: rule.GetReason(), Ticket: r.GetTicket(), RequestedBy: r.GetRequestedBy(), @@ -70,6 +73,62 @@ func newRuleView(r *policyv1.PackageRuleWithAttributes, names map[string]string) return v } +// waivedVulnerabilityView is one vulnerability that a trust entry waives. +// The justification is its short OpenVEX name. +type waivedVulnerabilityView struct { + ID string `json:"id"` + Justification string `json:"justification,omitempty"` +} + +func waivedViews(waived []*corev1.WaivedVulnerability) []waivedVulnerabilityView { + if len(waived) == 0 { + return nil + } + out := make([]waivedVulnerabilityView, 0, len(waived)) + for _, w := range waived { + out = append(out, waivedVulnerabilityView{ID: w.GetId(), Justification: justificationName(w.GetJustification())}) + } + return out +} + +// waivedText is the form for people, as +// "CVE-2024-3094 (vulnerable_code_not_in_execute_path), GHSA-jfh8-c2jp-5v3q". +func (v ruleView) waivedText() string { + texts := make([]string, 0, len(v.Vulnerabilities)) + for _, w := range v.Vulnerabilities { + text := w.ID + if w.Justification != "" { + text += " (" + w.Justification + ")" + } + texts = append(texts, text) + } + return strings.Join(texts, ", ") +} + +// waivedPlain is the form of the --vulnerability flag, as +// "CVE-2024-3094:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q". +func (v ruleView) waivedPlain() string { + values := make([]string, 0, len(v.Vulnerabilities)) + for _, w := range v.Vulnerabilities { + value := w.ID + if w.Justification != "" { + value += ":" + w.Justification + } + values = append(values, value) + } + return strings.Join(values, ",") +} + +// scopeText is the scope cell of a table. A trust entry that names +// vulnerabilities shows them after its scope. +func (v ruleView) scopeText() string { + text := strings.Join(v.Scopes, ",") + if len(v.Vulnerabilities) > 0 { + text += ": " + v.waivedText() + } + return cloudpolicy.EmptyDash(text) +} + func (v ruleView) selector() string { if v.Vers == "" { return v.Purl @@ -120,7 +179,7 @@ func blockPlace(override string) string { return fmt.Sprintf("on the subjects that policy override %q selects", tui.EscapeLine(override)) } -func scopeEffect(scope corev1.TrustScope) string { +func scopeEffect(rule *corev1.PackageRule, scope corev1.TrustScope) string { switch scope { case corev1.TrustScope_TRUST_SCOPE_MALWARE: return "a malware verdict that is not verified" @@ -128,6 +187,14 @@ func scopeEffect(scope corev1.TrustScope) string { return "the dependency cooldown" case corev1.TrustScope_TRUST_SCOPE_VULNERABILITY: return "the vulnerability findings of a scan gate" + case corev1.TrustScope_TRUST_SCOPE_LICENSE: + return "the license findings of a scan gate" + case corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY: + ids := make([]string, 0, len(rule.GetVulnerabilities())) + for _, w := range rule.GetVulnerabilities() { + ids = append(ids, w.GetId()) + } + return "the scan gate findings of " + strings.Join(ids, ", ") default: return "the verdicts of scope " + scope.String() } diff --git a/internal/cmd/policy/rule_vulnerability.go b/internal/cmd/policy/rule_vulnerability.go new file mode 100644 index 0000000..2be1582 --- /dev/null +++ b/internal/cmd/policy/rule_vulnerability.go @@ -0,0 +1,127 @@ +package policy + +import ( + "errors" + "fmt" + "regexp" + "slices" + "strings" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" +) + +// This file reads the --vulnerability values of `policy rule create`. A +// trust entry with them waives only the vulnerabilities that it names. + +const ( + justificationPrefix = "VULNERABILITY_JUSTIFICATION_" + + // maxWaivedVulnerabilities is the limit of the contract. The server + // checks it again. + maxWaivedVulnerabilities = 100 + maxVulnerabilityIDLength = 64 +) + +// vulnerabilityIDPattern is the id pattern of the contract. An id can hold +// a ":", as RHSA-2024:1234. +var vulnerabilityIDPattern = regexp.MustCompile(`^[A-Z][A-Z0-9]*-[A-Za-z0-9.:-]+$`) + +// justificationName is the short OpenVEX name of a justification, as +// vulnerable_code_not_in_execute_path, or empty when it is unset. +func justificationName(j corev1.VulnerabilityJustification) string { + if j == corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_UNSPECIFIED { + return "" + } + return strings.ToLower(strings.TrimPrefix(j.String(), justificationPrefix)) +} + +// justificationNames lists the short OpenVEX names that this SDK knows, in +// enum order. +func justificationNames() []string { + numbers := make([]int32, 0, len(corev1.VulnerabilityJustification_name)) + for n := range corev1.VulnerabilityJustification_name { + if n != 0 { + numbers = append(numbers, n) + } + } + slices.Sort(numbers) + names := make([]string, 0, len(numbers)) + for _, n := range numbers { + names = append(names, justificationName(corev1.VulnerabilityJustification(n))) + } + return names +} + +func parseJustification(name string) (corev1.VulnerabilityJustification, bool) { + for n := range corev1.VulnerabilityJustification_name { + j := corev1.VulnerabilityJustification(n) + if n != 0 && justificationName(j) == name { + return j, true + } + } + return 0, false +} + +// parseWaivedVulnerability reads ID[:JUSTIFICATION]. An id can hold a ":", +// so the value splits at its last ":" only when the text after it is a +// justification name. Otherwise the whole value is the id. +func parseWaivedVulnerability(value string) (*corev1.WaivedVulnerability, error) { + id := strings.TrimSpace(value) + justification := corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_UNSPECIFIED + if i := strings.LastIndex(id, ":"); i >= 0 { + if j, ok := parseJustification(id[i+1:]); ok { + id, justification = id[:i], j + } + } + if len(id) > maxVulnerabilityIDLength || !vulnerabilityIDPattern.MatchString(id) { + return nil, invalidInputError( + fmt.Errorf("--vulnerability %q is not a vulnerability id", value), + "Write the id as its advisory publishes it, as CVE-2024-3094 or GHSA-jfh8-c2jp-5v3q. "+ + "Add :JUSTIFICATION with one of: "+strings.Join(justificationNames(), ", ")) + } + w := &corev1.WaivedVulnerability{} + w.SetId(id) + w.SetJustification(justification) + return w, nil +} + +// parseWaivedVulnerabilities reads every --vulnerability value. The contract +// compares ids exactly, so the check of a duplicate does too. +func parseWaivedVulnerabilities(values []string) ([]*corev1.WaivedVulnerability, error) { + if len(values) > maxWaivedVulnerabilities { + return nil, invalidInputError( + fmt.Errorf("a trust entry waives at most %d vulnerabilities, not %d", maxWaivedVulnerabilities, len(values)), + "Split the ids into more trust entries") + } + out := make([]*corev1.WaivedVulnerability, 0, len(values)) + seen := make(map[string]struct{}, len(values)) + for _, v := range values { + w, err := parseWaivedVulnerability(v) + if err != nil { + return nil, err + } + if _, dup := seen[w.GetId()]; dup { + return nil, invalidInputError(fmt.Errorf("--vulnerability %s is given more than once", w.GetId()), + "Give each vulnerability id one time") + } + seen[w.GetId()] = struct{}{} + out = append(out, w) + } + return out, nil +} + +// checkWaivedScope refuses --vulnerability unless --scope vulnerability is +// the only scope. A trust entry that names vulnerabilities has the one +// scope NAMED_VULNERABILITY. +func checkWaivedScope(scopes []corev1.TrustScope) error { + vulnerability := corev1.TrustScope_TRUST_SCOPE_VULNERABILITY + switch { + case !slices.Contains(scopes, vulnerability): + return invalidInputError(errors.New("--vulnerability needs --scope vulnerability"), + "As in: --scope vulnerability --vulnerability CVE-2024-3094") + case len(scopes) > 1: + return invalidInputError(errors.New("--vulnerability needs --scope vulnerability as the only scope"), + "Create a second trust entry for the other scopes") + } + return nil +} diff --git a/internal/cmd/policy/rule_vulnerability_test.go b/internal/cmd/policy/rule_vulnerability_test.go new file mode 100644 index 0000000..0db41bb --- /dev/null +++ b/internal/cmd/policy/rule_vulnerability_test.go @@ -0,0 +1,135 @@ +package policy + +import ( + "strings" + "testing" + + corev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/policy/core/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseWaivedVulnerability(t *testing.T) { + tests := []struct { + name string + value string + id string + justification corev1.VulnerabilityJustification + err string + }{ + {"plain id", "CVE-2024-3094", "CVE-2024-3094", 0, ""}, + {"id with a justification", "CVE-2024-3094:vulnerable_code_not_in_execute_path", "CVE-2024-3094", + corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_VULNERABLE_CODE_NOT_IN_EXECUTE_PATH, ""}, + {"id with a colon", "RHSA-2024:1234", "RHSA-2024:1234", 0, ""}, + {"id with a colon and a justification", "RHSA-2024:1234:inline_mitigations_already_exist", "RHSA-2024:1234", + corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_INLINE_MITIGATIONS_ALREADY_EXIST, ""}, + {"an unknown suffix stays in the id", "CVE-2024-3094:fixed", "CVE-2024-3094:fixed", 0, ""}, + {"a misspelled justification fails as an id", "CVE-2024-3094:not_in_execute_path", "", 0, + `"CVE-2024-3094:not_in_execute_path" is not a vulnerability id`}, + {"lower case prefix", "cve-2024-3094", "", 0, `"cve-2024-3094" is not a vulnerability id`}, + {"too long", "CVE-" + strings.Repeat("1", 61), "", 0, "is not a vulnerability id"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := parseWaivedVulnerability(tt.value) + if tt.err != "" { + assert.ErrorContains(t, err, tt.err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.id, got.GetId()) + assert.Equal(t, tt.justification, got.GetJustification()) + }) + } +} + +func TestBuildRuleCreates_TrustScopes(t *testing.T) { + tests := []struct { + name string + scopes []string + vulns []string + want []corev1.TrustScope + waived []string + }{ + {"license", []string{"license"}, nil, []corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_LICENSE}, nil}, + {"every vulnerability", []string{"vulnerability"}, nil, []corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_VULNERABILITY}, nil}, + {"all", []string{"all"}, nil, allScopes, nil}, + { + "named vulnerabilities", []string{"vulnerability"}, + []string{"CVE-2024-1234:vulnerable_code_not_in_execute_path", "GHSA-jfh8-c2jp-5v3q"}, + []corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY}, + []string{"CVE-2024-1234:vulnerable_code_not_in_execute_path", "GHSA-jfh8-c2jp-5v3q:"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + in := ruleCreateInput{ + Trust: true, Selector: "pkg:npm/foo@1.2.3", Scopes: tt.scopes, Vulnerabilities: tt.vulns, + Reason: "Not reachable, S-90", Expires: "30d", + } + creates, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + require.Len(t, creates, 1) + rule := creates[0].GetRule() + assert.Equal(t, tt.want, rule.GetScopes()) + var waived []string + for _, w := range rule.GetVulnerabilities() { + waived = append(waived, w.GetId()+":"+justificationName(w.GetJustification())) + } + assert.Equal(t, tt.waived, waived) + }) + } +} + +func TestAnnounceRuleCreate_NamesTheWaivedVulnerabilities(t *testing.T) { + stderr := captureStderr(t) + in := ruleCreateInput{ + Trust: true, Selector: "pkg:npm/foo@1.2.3", Scopes: []string{"vulnerability"}, + Vulnerabilities: []string{"CVE-2024-1234", "GHSA-jfh8-c2jp-5v3q"}, Reason: "x", Expires: "30d", + } + creates, err := buildRuleCreates(in, nil, fixedNow) + require.NoError(t, err) + announceRuleCreate(in, creates) + assert.Contains(t, stderr.String(), + "it waives the scan gate findings of CVE-2024-1234, GHSA-jfh8-c2jp-5v3q for pkg:npm/foo@1.2.3.") + assert.Contains(t, stderr.String(), "A scan gate still fails on every other vulnerability of the package.") +} + +func TestRuleViews_ShowTheWaivedVulnerabilities(t *testing.T) { + r := ruleWithAttributes("r_5d2", corev1.Effect_EFFECT_TRUST, "") + cve := &corev1.WaivedVulnerability{} + cve.SetId("CVE-2024-1234") + cve.SetJustification(corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_VULNERABLE_CODE_NOT_IN_EXECUTE_PATH) + ghsa := &corev1.WaivedVulnerability{} + ghsa.SetId("GHSA-jfh8-c2jp-5v3q") + r.GetRule().SetScopes([]corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY}) + r.GetRule().SetVulnerabilities([]*corev1.WaivedVulnerability{cve, ghsa}) + license := ruleWithAttributes("r_5d3", corev1.Effect_EFFECT_TRUST, "") + license.GetRule().SetScopes([]corev1.TrustScope{corev1.TrustScope_TRUST_SCOPE_LICENSE}) + + list := &ruleListResult{Rules: []ruleView{newRuleView(r, nil), newRuleView(license, nil)}} + assert.Contains(t, list.RenderTable(), + "named-vulnerability: CVE-2024-1234 (vulnerable_code_not_in_execute_path), GHSA-jfh8-c2jp-5v3q") + plain := list.RenderPlain() + assert.Contains(t, plain, "\tnamed-vulnerability\t") + assert.Contains(t, plain, "\tCVE-2024-1234:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q\n") + assert.Contains(t, plain, "r_5d3\tpkg:npm/leftpad\t\ttrust\tlicense\t") + j, err := list.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(j), `"vulnerabilities": [ + { + "id": "CVE-2024-1234", + "justification": "vulnerable_code_not_in_execute_path" + }, + { + "id": "GHSA-jfh8-c2jp-5v3q" + } + ]`) + + show := &ruleShowResult{Rule: newRuleView(r, nil)} + assert.Contains(t, show.table(fixedNow), + "Vulnerabilities CVE-2024-1234 (vulnerable_code_not_in_execute_path), GHSA-jfh8-c2jp-5v3q\n") + assert.Contains(t, show.RenderPlain(), "vulnerabilities\tCVE-2024-1234:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q\n") + assert.NotContains(t, (&ruleShowResult{Rule: newRuleView(license, nil)}).table(fixedNow), "Vulnerabilities", + "a rule that waives no named vulnerability has no row for them") +} From d15e505163f6444033db573f80887cb955ad1b7b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 11:51:31 +0000 Subject: [PATCH 2/3] Tighten --vulnerability parsing and the license list decode A review of the first commit found inputs that the CLI took in a wrong way, and outputs with two shapes. --vulnerability: - An id that ends with ":" is refused. The contract pattern allows it, but no finding matches it. - The flag takes a comma-separated list, as --scope does, so the plain vulnerabilities cell of rule list passes back to the flag. The check of a duplicate id spans every value. - A justification name matches in any case. A suffix with "_" that is not a name gives "unknown justification" and lists the names, because an id never holds "_". - --scope named-vulnerability and --vulnerability with no --scope give a message that names --scope vulnerability. License lists in the policy document: - A list setting is set only by a list. A key with no list, as an uncommented "deny:" and "licenses:" with commented items, sets nothing, so a partial uncomment never empties the deny list. - "deny: [GPL-3.0-only]" and "deny: []" read as the list itself, as the contract defines the value of the setting. The document still writes the wrapper form. - A preview value at the inner path scan_gate.licenses.deny.licenses reads as the list, for a server that walks into the wrapper. Rule views keep one shape: JSON always holds vulnerabilities, and rule show always has a vulnerabilities row, as it has for an empty ticket. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- docs/cmd/policy-edit.md | 13 ++-- docs/cmd/policy-rule-create.md | 10 +-- docs/cmd/policy-rule-list.md | 6 +- docs/cmd/policy-rule-show.md | 31 +++++---- internal/cloudpolicy/fields.go | 22 ++++-- internal/cloudpolicy/fields_test.go | 3 + internal/cloudpolicy/protoyaml.go | 40 +++++++++-- internal/cloudpolicy/template_test.go | 44 ++++++++++-- internal/cmd/policy/rule_create.go | 4 +- internal/cmd/policy/rule_filters.go | 11 ++- internal/cmd/policy/rule_input.go | 6 ++ internal/cmd/policy/rule_show.go | 10 +-- internal/cmd/policy/rule_test.go | 13 +++- internal/cmd/policy/rule_view.go | 5 +- internal/cmd/policy/rule_vulnerability.go | 23 +++++-- .../cmd/policy/rule_vulnerability_test.go | 67 +++++++++++++++++-- 16 files changed, 244 insertions(+), 64 deletions(-) diff --git a/docs/cmd/policy-edit.md b/docs/cmd/policy-edit.md index 1a36b3b..e1396c3 100644 --- a/docs/cmd/policy-edit.md +++ b/docs/cmd/policy-edit.md @@ -150,11 +150,14 @@ safedep policy edit --override payments - The command warns when the file holds a comment that it did not write. The policy keeps no comments. - A parent key that you uncomment with no field below it makes no change. -- A license list is one setting. `deny: {licenses: []}` sets a deny list with no - entries, so it denies nothing. `allow: {licenses: []}` turns off the allow list - of the layer below. A `deny:` or `allow:` line that you uncomment with nothing - below it makes no change. A list replaces the list of the layer below. No - layer merges two lists. +- A license list is one setting. Only a list sets it: `deny: [GPL-3.0-only]`, + or the form that the document writes, `deny: {licenses: [GPL-3.0-only]}`. A list + replaces the list of the layer below. No layer merges two lists. +- `deny: []` or `deny: {licenses: []}` sets a deny list with no entries, so it + denies nothing. `allow: []` turns off the allow list of the layer below. +- A `deny:` or `allow:` key with no list makes no change. This is also true when + you uncomment `deny:` and `licenses:` but leave the items commented, and for + `deny: {}`. - The command warns when an added or changed policy override selects on a `managed/`, `reported/` or `scm-property/` label. A tool sets such a label, so a person on the endpoint can change it. The save continues. diff --git a/docs/cmd/policy-rule-create.md b/docs/cmd/policy-rule-create.md index 76cc66c..c759d82 100644 --- a/docs/cmd/policy-rule-create.md +++ b/docs/cmd/policy-rule-create.md @@ -23,7 +23,7 @@ safedep policy rule create --trust PURL --scope vulnerability --vulnerability ID | `-f`, `--file ` | With `--block`: a file with one selector on each line, a PURL and an optional range after a space. `#` starts a comment. `-` reads stdin. At most 1,000 selectors, in one revision. | | `--vers ` | A version range, as `'>=1.2.0'` or `'vers:npm/>=1.2.0\|<2.0.0'`. A bare range gets the `vers:` prefix and the type of the PURL. | | `--scope ` | With `--trust`: `malware`, `cooldown`, `vulnerability`, `license` or `all`. Repeatable. Required. | -| `--vulnerability [:]` | With `--scope vulnerability` as the only scope: waive only this vulnerability id, as `CVE-2024-3094`. Repeatable, at most 100 ids, each one time. See below. | +| `--vulnerability [:]` | With `--scope vulnerability` as the only scope: waive only this vulnerability id, as `CVE-2024-3094`. Repeatable, or comma-separated. At most 100 ids, each one time. See below. | | `--expires ` | A duration from now, as `30d`, or a date, as `2027-01-26`. Required with `--trust`, and at most 90 days from now for a trust entry. | | `--reason ` | Why the rule exists. Required. Tools show it in a block message. | | `--ticket ` | A ticket or incident reference, as `IR-2291`. | @@ -60,6 +60,7 @@ entry with the one scope `named-vulnerability`. It waives only the vulnerabiliti that it names and their aliases, so a CVE id also waives the GHSA id of the same vulnerability. A scan gate still fails on every other vulnerability of the package. The command refuses `--vulnerability` with another scope or with `all`. +`--scope named-vulnerability` is not a value of this command. Write the id as its advisory publishes it, as `CVE-2024-3094`, `GHSA-jfh8-c2jp-5v3q` or `RHSA-2024:1234`. The optional justification says why @@ -72,9 +73,10 @@ the vulnerability does not affect the package, with an OpenVEX name: - `inline_mitigations_already_exist` An id can hold a `:`. The command splits the value at its last `:` only when the -text after it is a justification name. Otherwise the whole value is the id, so -`RHSA-2024:1234` is one id. Without a justification, `--reason` is the only -explanation. +text after it is a justification name, in any case. Otherwise the whole value is +the id, so `RHSA-2024:1234` is one id. A suffix with `_` that is not a name is an +unknown justification. An id that ends with `:` is refused. Without a +justification, `--reason` is the only explanation. ## Examples diff --git a/docs/cmd/policy-rule-list.md b/docs/cmd/policy-rule-list.md index ff3e496..a9c2e4d 100644 --- a/docs/cmd/policy-rule-list.md +++ b/docs/cmd/policy-rule-list.md @@ -45,10 +45,12 @@ r_80b pkg:npm/leftpad trust malware FP, S-71 web `json` holds `rules` (rule id, purl, vers, effect, scopes, `vulnerabilities`, reason, ticket, requester, override id, `attaches_to`, author, added, updated and removed revision, times) and `next_page_token`. `vulnerabilities` lists each waived `id` and -its `justification` for a trust entry with the scope `named-vulnerability`. `plain` +its `justification` for a trust entry with the scope `named-vulnerability`, and is +an empty list for every other rule. `plain` writes a tab-separated header and one row for each rule. Its last column, `vulnerabilities`, has the form of the `--vulnerability` flag, as -`CVE-2024-1234:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q`. The table +`CVE-2024-1234:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q`, so you +can pass the value back to `--vulnerability`. The table shows the waived vulnerabilities after the scope, and humanizes the expiry. ## Authentication diff --git a/docs/cmd/policy-rule-show.md b/docs/cmd/policy-rule-show.md index 20e9055..26749f2 100644 --- a/docs/cmd/policy-rule-show.md +++ b/docs/cmd/policy-rule-show.md @@ -15,27 +15,32 @@ safedep policy rule show r_9c1 ``` ``` -Rule r_9c1 -Selector pkg:npm/evil vers:npm/>=1.2.0 -Effect block -Scope - -Reason IR-2291 credential stealer -Ticket IR-2291 -Requested by - -Attaches to base -Expires never -Created by carol -Revisions added in revision 48 · active +Rule r_9c1 +Selector pkg:npm/evil vers:npm/>=1.2.0 +Effect block +Scope - +Vulnerabilities - +Reason IR-2291 credential stealer +Ticket IR-2291 +Requested by - +Attaches to base +Expires never +Created by carol +Revisions added in revision 48 · active ``` -A trust entry that waives named vulnerabilities has a `Vulnerabilities` row -after `Scope`, with the justification of each id: +For a trust entry that waives named vulnerabilities, the `Vulnerabilities` row +shows each id with its justification: ``` Scope named-vulnerability Vulnerabilities CVE-2024-1234 (vulnerable_code_not_in_execute_path), GHSA-jfh8-c2jp-5v3q ``` +`json` holds `rule`, with `vulnerabilities`: an empty list, or each waived `id` +and its `justification`. `plain` writes one tab-separated key and value on each +line. Its `vulnerabilities` value has the form of the `--vulnerability` flag. + After an update of the rule, `Revisions` also names the revision of the last update, as `added in revision 48, updated in revision 52 · active`. diff --git a/internal/cloudpolicy/fields.go b/internal/cloudpolicy/fields.go index c412dc8..265eb2b 100644 --- a/internal/cloudpolicy/fields.go +++ b/internal/cloudpolicy/fields.go @@ -260,8 +260,8 @@ func FormatJSONValue(path, raw string) (string, string) { return duration.Format(d), humanDuration(d) } return text, text - case fd != nil && isListSetting(fd): - if items, ok := jsonListItems(value, wrappedList(fd.Message())); ok { + case fd != nil && (isListSetting(fd) || isWrappedList(path)): + if items, ok := jsonListItems(value, fd); ok { return items, items } compact, err := json.Marshal(value) @@ -280,11 +280,23 @@ func FormatJSONValue(path, raw string) (string, string) { } } +// isWrappedList reports the path of the list inside a list setting, as +// scan_gate.licenses.deny.licenses. A server that walks into the wrapper +// reports a change at this path, so its value reads as the setting's. +func isWrappedList(path string) bool { + i := strings.LastIndex(path, ".") + if i < 0 { + return false + } + parent := fieldByPath(path[:i]) + return parent != nil && isListSetting(parent) +} + // jsonListItems reads the items of a list setting from its JSON value: the // protojson of the wrapper, as {"licenses": ["MIT"]}, or the list itself. -func jsonListItems(value any, inner protoreflect.FieldDescriptor) (string, bool) { - if wrapper, ok := value.(map[string]any); ok { - value, ok = wrapper[inner.JSONName()] +func jsonListItems(value any, fd protoreflect.FieldDescriptor) (string, bool) { + if wrapper, ok := value.(map[string]any); ok && isListSetting(fd) { + value, ok = wrapper[wrappedList(fd.Message()).JSONName()] if !ok { value = []any{} } diff --git a/internal/cloudpolicy/fields_test.go b/internal/cloudpolicy/fields_test.go index 317f0f9..3e45ff5 100644 --- a/internal/cloudpolicy/fields_test.go +++ b/internal/cloudpolicy/fields_test.go @@ -76,6 +76,9 @@ func TestFormatJSONValue(t *testing.T) { {"scan_gate.licenses.deny", `{"licenses":["GPL-3.0-only","MIT"]}`, "GPL-3.0-only, MIT", "GPL-3.0-only, MIT"}, {"scan_gate.licenses.deny", `{}`, "[]", "[]"}, {"scan_gate.licenses.allow", `["MIT"]`, "MIT", "MIT"}, + // A server that walks into the wrapper reports the inner list. + {"scan_gate.licenses.deny.licenses", `["GPL-3.0-only","MIT"]`, "GPL-3.0-only, MIT", "GPL-3.0-only, MIT"}, + {"scan_gate.licenses.deny.licenses", `[]`, "[]", "[]"}, {"unknown.path", `"text"`, "text", "text"}, {"unknown.path", `{"a":1}`, `{"a":1}`, `{"a":1}`}, {"unknown.path", `not json`, "not json", "not json"}, diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index 0e5b786..e5d18bc 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -311,14 +311,18 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str return errAt(key, fieldPath, "the field is set twice") } seen[fd.Name()] = struct{}{} + if isListSetting(fd) { + if err := c.decodeListSetting(value, m, fd, fieldPath); err != nil { + return err + } + continue + } if isNull(value) { // "key:" with only commented lines below sets a message with no // fields, so the edit template of a set but empty spec round // trips. A label selector stays unset, because an empty selector - // selects every subject. A list setting stays unset too, because - // a set wrapper with no items is an empty list: an uncommented - // "deny:" alone must not remove every license from a deny list. - if !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && !isFormattedMessage(fd.Message()) && !isListSetting(fd) { + // selects every subject. + if !fd.IsList() && !fd.IsMap() && isMessageKind(fd) && !isFormattedMessage(fd.Message()) { m.Mutable(fd) } continue @@ -330,6 +334,34 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str return nil } +// decodeListSetting reads a list setting in the wrapper form, as +// "deny: {licenses: [MIT]}", or as the bare list, as "deny: [MIT]". Only a +// list sets it, because a set wrapper with no items is an empty list. A key +// with nothing below it, as "deny:" or "licenses:" whose items stay +// commented, sets nothing, so a partial uncomment never empties a list. +func (c *yamlCodec) decodeListSetting(n *yaml.Node, m protoreflect.Message, fd protoreflect.FieldDescriptor, path string) error { + inner := wrappedList(fd.Message()) + list := n + if n.Kind == yaml.MappingNode { + list = nil + for i := 0; i+1 < len(n.Content); i += 2 { + key := n.Content[i] + if c.fieldByKey(fd.Message(), key.Value) != inner { + return errAt(key, joinPath(path, key.Value), "unknown field. Known fields: %s", c.key(inner)) + } + if list != nil { + return errAt(key, joinPath(path, key.Value), "the field is set twice") + } + list = n.Content[i+1] + } + path = joinPath(path, c.key(inner)) + } + if list == nil || isNull(list) { + return nil + } + return c.decodeField(list, m.Mutable(fd).Message(), inner, path) +} + func (c *yamlCodec) knownFields(md protoreflect.MessageDescriptor) []string { names := make([]string, 0, md.Fields().Len()) for i := 0; i < md.Fields().Len(); i++ { diff --git a/internal/cloudpolicy/template_test.go b/internal/cloudpolicy/template_test.go index d8dced0..744a363 100644 --- a/internal/cloudpolicy/template_test.go +++ b/internal/cloudpolicy/template_test.go @@ -384,8 +384,44 @@ func TestMarshalPolicyTemplate_LicenseListsRoundTrip(t *testing.T) { } func TestUnmarshalPolicy_AnUncommentedListKeyAloneSetsNothing(t *testing.T) { - got, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n deny:\n")) - require.NoError(t, err) - assert.False(t, got.GetBase().GetScanGate().GetLicenses().HasDeny(), "deny: alone must not empty the deny list") - assert.False(t, PruneEmpty(got).(*policyv1.Policy).HasBase()) + for name, doc := range map[string]string{ + "the setting key": " deny:\n", + "the setting key and its list key": " deny:\n licenses:\n # - GPL-3.0-only\n", + "the wrapper form with no list key": " deny: {}\n", + "the wrapper form with a null list": " deny: {licenses: }\n", + } { + t.Run(name, func(t *testing.T) { + got, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n" + doc)) + require.NoError(t, err) + assert.False(t, got.GetBase().GetScanGate().GetLicenses().HasDeny(), "a key with no list must not empty the deny list") + assert.False(t, PruneEmpty(got).(*policyv1.Policy).HasBase()) + }) + } +} + +func TestUnmarshalPolicy_ListSettingForms(t *testing.T) { + tests := []struct { + name string + doc string + want []string + }{ + {"the bare empty list", "deny: []", []string{}}, + {"the bare list", "deny: [GPL-3.0-only]", []string{"GPL-3.0-only"}}, + {"the wrapper form with an empty list", "deny: {licenses: []}", []string{}}, + {"the wrapper form", "deny:\n licenses:\n - GPL-3.0-only", []string{"GPL-3.0-only"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n " + tt.doc + "\n")) + require.NoError(t, err) + licenses := got.GetBase().GetScanGate().GetLicenses() + require.True(t, licenses.HasDeny(), "a list sets the deny list") + assert.Equal(t, tt.want, append([]string{}, licenses.GetDeny().GetLicenses()...)) + }) + } + + _, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n deny: {licenses: [MIT], licences: [MIT]}\n")) + assert.ErrorContains(t, err, "scan_gate.licenses.deny.licences: unknown field. Known fields: licenses") + _, err = UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n deny: MIT\n")) + assert.ErrorContains(t, err, "expected a list") } diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go index a94ee7c..c2dff3e 100644 --- a/internal/cmd/policy/rule_create.go +++ b/internal/cmd/policy/rule_create.go @@ -84,9 +84,9 @@ func ruleCreateCmd(a *app.App) *cobra.Command { f.StringVar(&in.Vers, "vers", "", "a version range, as in '>=1.2.0' or 'vers:npm/>=1.2.0|<2.0.0'") f.StringSliceVar(&in.Scopes, "scope", nil, "with --trust: a verdict to waive, one of "+strings.Join(createScopeTokens(), ", ")+", or all (repeatable)") - f.StringArrayVar(&in.Vulnerabilities, "vulnerability", nil, + f.StringSliceVar(&in.Vulnerabilities, "vulnerability", nil, "with --scope vulnerability: waive only this id, as CVE-2024-3094, with an optional :JUSTIFICATION, one of "+ - strings.Join(justificationNames(), ", ")+" (repeatable)") + strings.Join(justificationNames(), ", ")+" (repeatable, or comma-separated)") f.StringVar(&in.Reason, "reason", "", "why the rule exists, which tools show in a block message (required)") f.StringVar(&in.Ticket, "ticket", "", "a ticket or incident reference, as in IR-2291") f.StringVar(&in.RequestedBy, "requested-by", "", "the team or person that asked for the rule") diff --git a/internal/cmd/policy/rule_filters.go b/internal/cmd/policy/rule_filters.go index 753fdb4..1e17c3a 100644 --- a/internal/cmd/policy/rule_filters.go +++ b/internal/cmd/policy/rule_filters.go @@ -16,11 +16,18 @@ func trustScopeTokens() []string { return tui.EnumTokens(corev1.TrustScope_name, trustScopePrefix) } +func namedVulnerabilityToken() string { + return tui.EnumToken(corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY.String(), trustScopePrefix) +} + // createScopeTokens are the values of --scope in a create. A trust entry // gets NAMED_VULNERABILITY from --scope vulnerability with --vulnerability, -// because that scope needs ids. So "all" leaves it out too. +// because that scope needs ids. So "all" leaves it out too. The exclusion is +// by name on purpose: the contract has no property that says a scope needs +// data, so a scope that a later SDK adds joins "all" and fails the test of +// allScopes, which forces a decision at the bump. func createScopeTokens() []string { - named := tui.EnumToken(corev1.TrustScope_TRUST_SCOPE_NAMED_VULNERABILITY.String(), trustScopePrefix) + named := namedVulnerabilityToken() return slices.DeleteFunc(trustScopeTokens(), func(token string) bool { return token == named }) } diff --git a/internal/cmd/policy/rule_input.go b/internal/cmd/policy/rule_input.go index 08b8daa..a2da3fb 100644 --- a/internal/cmd/policy/rule_input.go +++ b/internal/cmd/policy/rule_input.go @@ -63,6 +63,8 @@ func validateRuleCreate(in ruleCreateInput) error { "Write each line as: PURL [RANGE]") case strings.TrimSpace(in.Reason) == "": return invalidInputError(errors.New("--reason is required"), "Say why the rule exists, as in --reason \"IR-2291 credential stealer\"") + case in.Trust && len(in.Scopes) == 0 && len(in.Vulnerabilities) > 0: + return waivedNeedsScopeError() case in.Trust && len(in.Scopes) == 0: return invalidInputError(errors.New("a trust entry needs --scope"), "Name each verdict that it waives: --scope "+strings.Join(createScopeTokens(), ", --scope ")+", or --scope all") @@ -112,6 +114,10 @@ func expandScopes(values []string) ([]corev1.TrustScope, error) { } return out, nil } + if strings.EqualFold(strings.TrimSpace(v), namedVulnerabilityToken()) { + return nil, invalidInputError(fmt.Errorf("--scope %s is not a value of create: it needs vulnerability ids", v), + "Use --scope vulnerability with --vulnerability ID") + } scope, err := parseTrustScope(v, createScopeTokens()) if err != nil { return nil, err diff --git a/internal/cmd/policy/rule_show.go b/internal/cmd/policy/rule_show.go index 658131d..5ad1109 100644 --- a/internal/cmd/policy/rule_show.go +++ b/internal/cmd/policy/rule_show.go @@ -78,16 +78,12 @@ func (r *ruleShowResult) table(now time.Time) string { if v.expires != nil { expires = expiryText(*v.expires, now) } - rows := [][2]string{ + return cloudpolicy.KeyValues([][2]string{ {"Rule", v.ID}, {"Selector", v.selector()}, {"Effect", v.Effect}, {"Scope", cloudpolicy.EmptyDash(strings.Join(v.Scopes, ", "))}, - } - if len(v.Vulnerabilities) > 0 { - rows = append(rows, [2]string{"Vulnerabilities", v.waivedText()}) - } - return cloudpolicy.KeyValues(append(rows, [][2]string{ + {"Vulnerabilities", cloudpolicy.EmptyDash(v.waivedText())}, {"Reason", v.Reason}, {"Ticket", cloudpolicy.EmptyDash(v.Ticket)}, {"Requested by", cloudpolicy.EmptyDash(v.RequestedBy)}, @@ -95,7 +91,7 @@ func (r *ruleShowResult) table(now time.Time) string { {"Expires", expires}, {"Created by", cloudpolicy.EmptyDash(v.CreatedBy)}, {"Revisions", v.revisions() + sep + removed}, - }...)) + }) } // The server sends updated_revision 0 when no update changed the rule. An diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go index 6f8c6ba..42254f1 100644 --- a/internal/cmd/policy/rule_test.go +++ b/internal/cmd/policy/rule_test.go @@ -48,7 +48,10 @@ func TestValidateRuleCreate(t *testing.T) { {"unknown scope", func(in *ruleCreateInput) { in.Scopes = []string{"secrets"} }, trust, `unknown trust scope "secrets"`}, {"license", func(in *ruleCreateInput) { in.Scopes = []string{"license"} }, trust, ""}, {"named vulnerability needs ids", func(in *ruleCreateInput) { in.Scopes = []string{"named-vulnerability"} }, trust, - `unknown trust scope "named-vulnerability": allowed values are malware, cooldown, vulnerability, license`}, + "--scope named-vulnerability is not a value of create: it needs vulnerability ids"}, + {"waived vulnerabilities with no scope", func(in *ruleCreateInput) { + in.Scopes, in.Vulnerabilities = nil, []string{"CVE-2024-1234"} + }, trust, "--vulnerability needs --scope vulnerability"}, {"waived vulnerabilities", func(in *ruleCreateInput) { in.Scopes, in.Vulnerabilities = []string{"vulnerability"}, []string{"CVE-2024-1234", "GHSA-jfh8-c2jp-5v3q"} }, trust, ""}, @@ -83,7 +86,10 @@ func TestValidateRuleCreate(t *testing.T) { } // allScopes is what --scope all expands to. It leaves out -// NAMED_VULNERABILITY, because that scope needs vulnerability ids. +// NAMED_VULNERABILITY, because that scope needs vulnerability ids. The list +// is hard-coded on purpose: the contract has no property that says a scope +// needs data, so a scope that a later SDK adds must fail this test and force +// a decision at the bump. var allScopes = []corev1.TrustScope{ corev1.TrustScope_TRUST_SCOPE_MALWARE, corev1.TrustScope_TRUST_SCOPE_COOLDOWN, @@ -340,7 +346,8 @@ func TestRunRuleShow(t *testing.T) { got, err := runRuleShow(context.Background(), client, "r_9c1") require.NoError(t, err) table := got.RenderTable() - assert.Contains(t, table, "Rule r_9c1") + assert.Contains(t, table, "Rule r_9c1") + assert.Contains(t, table, "Vulnerabilities -") assert.Contains(t, table, "added in revision 40 · active") updated := ruleWithAttributes("r_9c1", corev1.Effect_EFFECT_BLOCK, "") diff --git a/internal/cmd/policy/rule_view.go b/internal/cmd/policy/rule_view.go index 0eb323c..9ae6c4a 100644 --- a/internal/cmd/policy/rule_view.go +++ b/internal/cmd/policy/rule_view.go @@ -22,7 +22,7 @@ type ruleView struct { Vers string `json:"vers,omitempty"` Effect string `json:"effect"` Scopes []string `json:"scopes"` - Vulnerabilities []waivedVulnerabilityView `json:"vulnerabilities,omitempty"` + Vulnerabilities []waivedVulnerabilityView `json:"vulnerabilities"` Reason string `json:"reason"` Ticket string `json:"ticket,omitempty"` RequestedBy string `json:"requested_by,omitempty"` @@ -81,9 +81,6 @@ type waivedVulnerabilityView struct { } func waivedViews(waived []*corev1.WaivedVulnerability) []waivedVulnerabilityView { - if len(waived) == 0 { - return nil - } out := make([]waivedVulnerabilityView, 0, len(waived)) for _, w := range waived { out = append(out, waivedVulnerabilityView{ID: w.GetId(), Justification: justificationName(w.GetJustification())}) diff --git a/internal/cmd/policy/rule_vulnerability.go b/internal/cmd/policy/rule_vulnerability.go index 2be1582..8a04435 100644 --- a/internal/cmd/policy/rule_vulnerability.go +++ b/internal/cmd/policy/rule_vulnerability.go @@ -64,16 +64,25 @@ func parseJustification(name string) (corev1.VulnerabilityJustification, bool) { // parseWaivedVulnerability reads ID[:JUSTIFICATION]. An id can hold a ":", // so the value splits at its last ":" only when the text after it is a -// justification name. Otherwise the whole value is the id. +// justification name. Otherwise the whole value is the id. An id never holds +// "_", so a suffix with "_" that is not a name is a wrong justification. The +// contract pattern allows an id that ends with ":", but no advisory +// publishes one and no finding would match it. func parseWaivedVulnerability(value string) (*corev1.WaivedVulnerability, error) { id := strings.TrimSpace(value) justification := corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_UNSPECIFIED if i := strings.LastIndex(id, ":"); i >= 0 { - if j, ok := parseJustification(id[i+1:]); ok { + suffix := strings.ToLower(id[i+1:]) + j, ok := parseJustification(suffix) + switch { + case ok: id, justification = id[:i], j + case strings.Contains(suffix, "_"): + return nil, invalidInputError(fmt.Errorf("--vulnerability %q: unknown justification %q", value, id[i+1:]), + "Use one of: "+strings.Join(justificationNames(), ", ")) } } - if len(id) > maxVulnerabilityIDLength || !vulnerabilityIDPattern.MatchString(id) { + if strings.HasSuffix(id, ":") || len(id) > maxVulnerabilityIDLength || !vulnerabilityIDPattern.MatchString(id) { return nil, invalidInputError( fmt.Errorf("--vulnerability %q is not a vulnerability id", value), "Write the id as its advisory publishes it, as CVE-2024-3094 or GHSA-jfh8-c2jp-5v3q. "+ @@ -110,6 +119,11 @@ func parseWaivedVulnerabilities(values []string) ([]*corev1.WaivedVulnerability, return out, nil } +func waivedNeedsScopeError() error { + return invalidInputError(errors.New("--vulnerability needs --scope vulnerability"), + "As in: --scope vulnerability --vulnerability CVE-2024-3094") +} + // checkWaivedScope refuses --vulnerability unless --scope vulnerability is // the only scope. A trust entry that names vulnerabilities has the one // scope NAMED_VULNERABILITY. @@ -117,8 +131,7 @@ func checkWaivedScope(scopes []corev1.TrustScope) error { vulnerability := corev1.TrustScope_TRUST_SCOPE_VULNERABILITY switch { case !slices.Contains(scopes, vulnerability): - return invalidInputError(errors.New("--vulnerability needs --scope vulnerability"), - "As in: --scope vulnerability --vulnerability CVE-2024-3094") + return waivedNeedsScopeError() case len(scopes) > 1: return invalidInputError(errors.New("--vulnerability needs --scope vulnerability as the only scope"), "Create a second trust entry for the other scopes") diff --git a/internal/cmd/policy/rule_vulnerability_test.go b/internal/cmd/policy/rule_vulnerability_test.go index 0db41bb..ec02db1 100644 --- a/internal/cmd/policy/rule_vulnerability_test.go +++ b/internal/cmd/policy/rule_vulnerability_test.go @@ -1,6 +1,7 @@ package policy import ( + "fmt" "strings" "testing" @@ -24,8 +25,13 @@ func TestParseWaivedVulnerability(t *testing.T) { {"id with a colon and a justification", "RHSA-2024:1234:inline_mitigations_already_exist", "RHSA-2024:1234", corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_INLINE_MITIGATIONS_ALREADY_EXIST, ""}, {"an unknown suffix stays in the id", "CVE-2024-3094:fixed", "CVE-2024-3094:fixed", 0, ""}, - {"a misspelled justification fails as an id", "CVE-2024-3094:not_in_execute_path", "", 0, - `"CVE-2024-3094:not_in_execute_path" is not a vulnerability id`}, + {"a justification in upper case", "CVE-2024-3094:COMPONENT_NOT_PRESENT", "CVE-2024-3094", + corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_COMPONENT_NOT_PRESENT, ""}, + {"an unknown justification", "CVE-2024-3094:not_in_execute_path", "", 0, + `unknown justification "not_in_execute_path"`}, + {"a trailing colon", "CVE-2024-1:", "", 0, `"CVE-2024-1:" is not a vulnerability id`}, + {"a trailing colon before a justification", "CVE-2024-1::component_not_present", "", 0, + `"CVE-2024-1::component_not_present" is not a vulnerability id`}, {"lower case prefix", "cve-2024-3094", "", 0, `"cve-2024-3094" is not a vulnerability id`}, {"too long", "CVE-" + strings.Repeat("1", 61), "", 0, "is not a vulnerability id"}, } @@ -43,6 +49,52 @@ func TestParseWaivedVulnerability(t *testing.T) { } } +func TestParseWaivedVulnerabilities_Limits(t *testing.T) { + ids := make([]string, maxWaivedVulnerabilities+1) + for i := range ids { + ids[i] = fmt.Sprintf("CVE-2024-%d", 1000+i) + } + got, err := parseWaivedVulnerabilities(ids[:maxWaivedVulnerabilities]) + require.NoError(t, err) + assert.Len(t, got, maxWaivedVulnerabilities) + + _, err = parseWaivedVulnerabilities(ids) + assert.ErrorContains(t, err, "a trust entry waives at most 100 vulnerabilities, not 101") +} + +func TestRuleCreateCmd_VulnerabilityFlag(t *testing.T) { + tests := []struct { + name string + args []string + want []string + err string + }{ + {"repeated", []string{"--vulnerability", "CVE-1-1", "--vulnerability", "CVE-1-2:component_not_present"}, + []string{"CVE-1-1", "CVE-1-2:component_not_present"}, ""}, + {"comma-separated, as rule list prints it", []string{"--vulnerability", "CVE-1-1,CVE-1-2:component_not_present"}, + []string{"CVE-1-1", "CVE-1-2:component_not_present"}, ""}, + {"a duplicate across the split", []string{"--vulnerability", "CVE-1-1,CVE-1-2", "--vulnerability", "CVE-1-1"}, + nil, "--vulnerability CVE-1-1 is given more than once"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := ruleCreateCmd(nil) + args := append([]string{"--trust", "pkg:npm/foo@1.2.3", "--scope", "vulnerability", "--reason", "x", "--expires", "30d"}, + tt.args...) + require.NoError(t, cmd.ParseFlags(args)) + err := cmd.Args(cmd, cmd.Flags().Args()) + if tt.err != "" { + assert.ErrorContains(t, err, tt.err) + return + } + require.NoError(t, err) + got, err := cmd.Flags().GetStringSlice("vulnerability") + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + func TestBuildRuleCreates_TrustScopes(t *testing.T) { tests := []struct { name string @@ -130,6 +182,13 @@ func TestRuleViews_ShowTheWaivedVulnerabilities(t *testing.T) { assert.Contains(t, show.table(fixedNow), "Vulnerabilities CVE-2024-1234 (vulnerable_code_not_in_execute_path), GHSA-jfh8-c2jp-5v3q\n") assert.Contains(t, show.RenderPlain(), "vulnerabilities\tCVE-2024-1234:vulnerable_code_not_in_execute_path,GHSA-jfh8-c2jp-5v3q\n") - assert.NotContains(t, (&ruleShowResult{Rule: newRuleView(license, nil)}).table(fixedNow), "Vulnerabilities", - "a rule that waives no named vulnerability has no row for them") + + // A rule that waives no named vulnerability keeps the row and the key, + // as an empty ticket does. + none := &ruleShowResult{Rule: newRuleView(license, nil)} + assert.Contains(t, none.table(fixedNow), "Vulnerabilities -\n") + assert.Contains(t, none.RenderPlain(), "vulnerabilities\t\n") + j, err = none.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(j), `"vulnerabilities": []`) } From 9139f14c228586555073e45faca02e04e0ff5005 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 12:03:37 +0000 Subject: [PATCH 3/3] Refuse an empty --vulnerability and named-vulnerability after all Three inputs from the review of safedep/cli#75 did the wrong thing. - An empty --vulnerability value, as "--vulnerability=", parsed to no ids, so the command created a rule that waives every vulnerability of the package. A --vulnerability flag that is present now needs an id, and an empty item of a comma list fails too. An omitted flag keeps its meaning. - "--scope all,named-vulnerability" expanded "all" before it read the next value, so the command published a rule with every scope. Every --scope value is now checked before "all" expands. - A YAML alias for a license list, as "allow: *empty", failed with "expected a list". The decoder now follows an alias to its anchor for the setting and for its list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MhRi597EX9odoSDXbVBsxz --- internal/cloudpolicy/protoyaml.go | 12 ++++- internal/cloudpolicy/template_test.go | 20 +++++++++ internal/cmd/policy/rule_create.go | 16 ++++--- internal/cmd/policy/rule_input.go | 45 +++++++++++-------- internal/cmd/policy/rule_test.go | 6 +++ internal/cmd/policy/rule_vulnerability.go | 18 ++++++++ .../cmd/policy/rule_vulnerability_test.go | 4 ++ 7 files changed, 95 insertions(+), 26 deletions(-) diff --git a/internal/cloudpolicy/protoyaml.go b/internal/cloudpolicy/protoyaml.go index e5d18bc..f6721a3 100644 --- a/internal/cloudpolicy/protoyaml.go +++ b/internal/cloudpolicy/protoyaml.go @@ -341,6 +341,7 @@ func (c *yamlCodec) decodeMessage(n *yaml.Node, m protoreflect.Message, path str // commented, sets nothing, so a partial uncomment never empties a list. func (c *yamlCodec) decodeListSetting(n *yaml.Node, m protoreflect.Message, fd protoreflect.FieldDescriptor, path string) error { inner := wrappedList(fd.Message()) + n = resolveAlias(n) list := n if n.Kind == yaml.MappingNode { list = nil @@ -352,7 +353,7 @@ func (c *yamlCodec) decodeListSetting(n *yaml.Node, m protoreflect.Message, fd p if list != nil { return errAt(key, joinPath(path, key.Value), "the field is set twice") } - list = n.Content[i+1] + list = resolveAlias(n.Content[i+1]) } path = joinPath(path, c.key(inner)) } @@ -362,6 +363,15 @@ func (c *yamlCodec) decodeListSetting(n *yaml.Node, m protoreflect.Message, fd p return c.decodeField(list, m.Mutable(fd).Message(), inner, path) } +// resolveAlias follows a YAML alias, as "allow: *empty", to the node of its +// anchor. +func resolveAlias(n *yaml.Node) *yaml.Node { + for n != nil && n.Kind == yaml.AliasNode && n.Alias != nil { + n = n.Alias + } + return n +} + func (c *yamlCodec) knownFields(md protoreflect.MessageDescriptor) []string { names := make([]string, 0, md.Fields().Len()) for i := 0; i < md.Fields().Len(); i++ { diff --git a/internal/cloudpolicy/template_test.go b/internal/cloudpolicy/template_test.go index 744a363..aaa4b38 100644 --- a/internal/cloudpolicy/template_test.go +++ b/internal/cloudpolicy/template_test.go @@ -420,6 +420,26 @@ func TestUnmarshalPolicy_ListSettingForms(t *testing.T) { }) } + aliases := []struct { + name string + doc string + want []string + }{ + {"an alias to a wrapper", "deny: &empty {licenses: []}\n allow: *empty", []string{}}, + {"an alias to a bare list", "deny: &list [GPL-3.0-only]\n allow: *list", []string{"GPL-3.0-only"}}, + {"an alias to the list of a wrapper", "deny: {licenses: &list [MIT]}\n allow: {licenses: *list}", []string{"MIT"}}, + } + for _, tt := range aliases { + t.Run(tt.name, func(t *testing.T) { + got, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n " + tt.doc + "\n")) + require.NoError(t, err) + licenses := got.GetBase().GetScanGate().GetLicenses() + require.True(t, licenses.HasDeny()) + require.True(t, licenses.HasAllow(), "the alias sets the allow list") + assert.Equal(t, tt.want, append([]string{}, licenses.GetAllow().GetLicenses()...)) + }) + } + _, err := UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n deny: {licenses: [MIT], licences: [MIT]}\n")) assert.ErrorContains(t, err, "scan_gate.licenses.deny.licences: unknown field. Known fields: licenses") _, err = UnmarshalPolicy([]byte("base:\n scan_gate:\n licenses:\n deny: MIT\n")) diff --git a/internal/cmd/policy/rule_create.go b/internal/cmd/policy/rule_create.go index c2dff3e..028c151 100644 --- a/internal/cmd/policy/rule_create.go +++ b/internal/cmd/policy/rule_create.go @@ -30,12 +30,15 @@ type ruleCreateInput struct { Vers string Scopes []string Vulnerabilities []string - Reason string - Ticket string - RequestedBy string - Expires string - Override string - Message string + // VulnerabilitySet is true when the command line has --vulnerability, + // also with an empty value, which parses to no ids. + VulnerabilitySet bool + Reason string + Ticket string + RequestedBy string + Expires string + Override string + Message string } type ruleCreateResult struct { @@ -64,6 +67,7 @@ func ruleCreateCmd(a *app.App) *cobra.Command { if len(args) == 1 { in.Selector = args[0] } + in.VulnerabilitySet = cmd.Flags().Changed("vulnerability") return validateRuleCreate(in) }, RunE: func(cmd *cobra.Command, _ []string) error { diff --git a/internal/cmd/policy/rule_input.go b/internal/cmd/policy/rule_input.go index a2da3fb..3463d38 100644 --- a/internal/cmd/policy/rule_input.go +++ b/internal/cmd/policy/rule_input.go @@ -63,7 +63,7 @@ func validateRuleCreate(in ruleCreateInput) error { "Write each line as: PURL [RANGE]") case strings.TrimSpace(in.Reason) == "": return invalidInputError(errors.New("--reason is required"), "Say why the rule exists, as in --reason \"IR-2291 credential stealer\"") - case in.Trust && len(in.Scopes) == 0 && len(in.Vulnerabilities) > 0: + case in.Trust && len(in.Scopes) == 0 && in.waives(): return waivedNeedsScopeError() case in.Trust && len(in.Scopes) == 0: return invalidInputError(errors.New("a trust entry needs --scope"), @@ -72,7 +72,7 @@ func validateRuleCreate(in ruleCreateInput) error { return invalidInputError(errors.New("a trust entry needs --expires"), "As in --expires 30d") case in.Block && len(in.Scopes) > 0: return invalidInputError(errors.New("a block entry has no scope"), "Remove --scope") - case in.Block && len(in.Vulnerabilities) > 0: + case in.Block && in.waives(): return invalidInputError(errors.New("a block entry waives no vulnerability"), "Remove --vulnerability") } _, _, err := ruleScopes(in) @@ -84,7 +84,7 @@ func validateRuleCreate(in ruleCreateInput) error { // NAMED_VULNERABILITY. Without --vulnerability it waives every vulnerability. func ruleScopes(in ruleCreateInput) ([]corev1.TrustScope, []*corev1.WaivedVulnerability, error) { scopes, err := expandScopes(in.Scopes) - if err != nil || len(in.Vulnerabilities) == 0 { + if err != nil || !in.waives() { return scopes, nil, err } if err := checkWaivedScope(scopes); err != nil { @@ -100,31 +100,38 @@ func ruleScopes(in ruleCreateInput) ([]corev1.TrustScope, []*corev1.WaivedVulner // expandScopes reads the --scope values. "all" expands to every trust scope // that this SDK knows, because the contract has no "all" value: a scope that // a later release adds never widens a stored entry. +// Every value is checked before "all" expands, so a bad value after "all" +// still fails. func expandScopes(values []string) ([]corev1.TrustScope, error) { var out []corev1.TrustScope + all := false for _, v := range values { - if strings.EqualFold(strings.TrimSpace(v), scopeAll) { - out = out[:0] - for _, token := range createScopeTokens() { - scope, err := parseTrustScope(token, createScopeTokens()) - if err != nil { - return nil, err - } - out = append(out, scope) - } - return out, nil - } - if strings.EqualFold(strings.TrimSpace(v), namedVulnerabilityToken()) { + switch token := strings.TrimSpace(v); { + case strings.EqualFold(token, scopeAll): + all = true + case strings.EqualFold(token, namedVulnerabilityToken()): return nil, invalidInputError(fmt.Errorf("--scope %s is not a value of create: it needs vulnerability ids", v), "Use --scope vulnerability with --vulnerability ID") + default: + scope, err := parseTrustScope(v, createScopeTokens()) + if err != nil { + return nil, err + } + if !slices.Contains(out, scope) { + out = append(out, scope) + } } - scope, err := parseTrustScope(v, createScopeTokens()) + } + if !all { + return out, nil + } + out = out[:0] + for _, token := range createScopeTokens() { + scope, err := parseTrustScope(token, createScopeTokens()) if err != nil { return nil, err } - if !slices.Contains(out, scope) { - out = append(out, scope) - } + out = append(out, scope) } return out, nil } diff --git a/internal/cmd/policy/rule_test.go b/internal/cmd/policy/rule_test.go index 42254f1..2c22f95 100644 --- a/internal/cmd/policy/rule_test.go +++ b/internal/cmd/policy/rule_test.go @@ -49,6 +49,12 @@ func TestValidateRuleCreate(t *testing.T) { {"license", func(in *ruleCreateInput) { in.Scopes = []string{"license"} }, trust, ""}, {"named vulnerability needs ids", func(in *ruleCreateInput) { in.Scopes = []string{"named-vulnerability"} }, trust, "--scope named-vulnerability is not a value of create: it needs vulnerability ids"}, + {"named vulnerability after all", func(in *ruleCreateInput) { in.Scopes = []string{"all", "named-vulnerability"} }, trust, + "--scope named-vulnerability is not a value of create"}, + {"named vulnerability before all", func(in *ruleCreateInput) { in.Scopes = []string{"named-vulnerability", "all"} }, trust, + "--scope named-vulnerability is not a value of create"}, + {"unknown scope after all", func(in *ruleCreateInput) { in.Scopes = []string{"all", "secrets"} }, trust, + `unknown trust scope "secrets"`}, {"waived vulnerabilities with no scope", func(in *ruleCreateInput) { in.Scopes, in.Vulnerabilities = nil, []string{"CVE-2024-1234"} }, trust, "--vulnerability needs --scope vulnerability"}, diff --git a/internal/cmd/policy/rule_vulnerability.go b/internal/cmd/policy/rule_vulnerability.go index 8a04435..c9147a3 100644 --- a/internal/cmd/policy/rule_vulnerability.go +++ b/internal/cmd/policy/rule_vulnerability.go @@ -62,6 +62,18 @@ func parseJustification(name string) (corev1.VulnerabilityJustification, bool) { return 0, false } +// waives reports a create that names vulnerabilities. An empty +// --vulnerability counts, so it fails as a missing id and never creates an +// entry that waives every vulnerability. +func (in ruleCreateInput) waives() bool { + return in.VulnerabilitySet || len(in.Vulnerabilities) > 0 +} + +func missingVulnerabilityIDError() error { + return invalidInputError(errors.New("--vulnerability needs a vulnerability id"), + "As in: --vulnerability CVE-2024-3094. Omit --vulnerability to waive every vulnerability") +} + // parseWaivedVulnerability reads ID[:JUSTIFICATION]. An id can hold a ":", // so the value splits at its last ":" only when the text after it is a // justification name. Otherwise the whole value is the id. An id never holds @@ -70,6 +82,9 @@ func parseJustification(name string) (corev1.VulnerabilityJustification, bool) { // publishes one and no finding would match it. func parseWaivedVulnerability(value string) (*corev1.WaivedVulnerability, error) { id := strings.TrimSpace(value) + if id == "" { + return nil, missingVulnerabilityIDError() + } justification := corev1.VulnerabilityJustification_VULNERABILITY_JUSTIFICATION_UNSPECIFIED if i := strings.LastIndex(id, ":"); i >= 0 { suffix := strings.ToLower(id[i+1:]) @@ -97,6 +112,9 @@ func parseWaivedVulnerability(value string) (*corev1.WaivedVulnerability, error) // parseWaivedVulnerabilities reads every --vulnerability value. The contract // compares ids exactly, so the check of a duplicate does too. func parseWaivedVulnerabilities(values []string) ([]*corev1.WaivedVulnerability, error) { + if len(values) == 0 { + return nil, missingVulnerabilityIDError() + } if len(values) > maxWaivedVulnerabilities { return nil, invalidInputError( fmt.Errorf("a trust entry waives at most %d vulnerabilities, not %d", maxWaivedVulnerabilities, len(values)), diff --git a/internal/cmd/policy/rule_vulnerability_test.go b/internal/cmd/policy/rule_vulnerability_test.go index ec02db1..a1e9a65 100644 --- a/internal/cmd/policy/rule_vulnerability_test.go +++ b/internal/cmd/policy/rule_vulnerability_test.go @@ -75,6 +75,10 @@ func TestRuleCreateCmd_VulnerabilityFlag(t *testing.T) { []string{"CVE-1-1", "CVE-1-2:component_not_present"}, ""}, {"a duplicate across the split", []string{"--vulnerability", "CVE-1-1,CVE-1-2", "--vulnerability", "CVE-1-1"}, nil, "--vulnerability CVE-1-1 is given more than once"}, + {"omitted", nil, []string{}, ""}, + {"an empty value", []string{"--vulnerability="}, nil, "--vulnerability needs a vulnerability id"}, + {"only a comma", []string{"--vulnerability", ","}, nil, "--vulnerability needs a vulnerability id"}, + {"a trailing comma", []string{"--vulnerability", "CVE-1-1,"}, nil, "--vulnerability needs a vulnerability id"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {